diff --git a/.all-contributorsrc b/.all-contributorsrc new file mode 100644 index 000000000000..32f5734184c4 --- /dev/null +++ b/.all-contributorsrc @@ -0,0 +1,3543 @@ +{ + "files": [ + "README.md" + ], + "imageSize": 100, + "commit": false, + "contributors": [ + { + "login": "iluwatar", + "name": "Ilkka Seppälä", + "avatar_url": "https://avatars1.githubusercontent.com/u/582346?v=4", + "profile": "https://github.com/iluwatar", + "contributions": [ + "projectManagement", + "maintenance", + "content" + ] + }, + { + "login": "ohbus", + "name": "Subhrodip Mohanta", + "avatar_url": "https://avatars0.githubusercontent.com/u/13291222?v=4", + "profile": "http://subho.xyz", + "contributions": [ + "code", + "review", + "maintenance" + ] + }, + { + "login": "amit1307", + "name": "amit1307", + "avatar_url": "https://avatars0.githubusercontent.com/u/23420222?v=4", + "profile": "https://github.com/amit1307", + "contributions": [ + "code" + ] + }, + { + "login": "npathai", + "name": "Narendra Pathai", + "avatar_url": "https://avatars2.githubusercontent.com/u/1792515?v=4", + "profile": "https://github.com/npathai", + "contributions": [ + "code", + "ideas", + "review" + ] + }, + { + "login": "fluxw42", + "name": "Jeroen Meulemeester", + "avatar_url": "https://avatars1.githubusercontent.com/u/1545460?v=4", + "profile": "https://github.com/fluxw42", + "contributions": [ + "code" + ] + }, + { + "login": "mikulucky", + "name": "Joseph McCarthy", + "avatar_url": "https://avatars0.githubusercontent.com/u/4526195?v=4", + "profile": "http://www.joemccarthy.co.uk", + "contributions": [ + "code" + ] + }, + { + "login": "thomasoss", + "name": "Thomas", + "avatar_url": "https://avatars1.githubusercontent.com/u/22516154?v=4", + "profile": "https://github.com/thomasoss", + "contributions": [ + "code" + ] + }, + { + "login": "anuragagarwal561994", + "name": "Anurag Agarwal", + "avatar_url": "https://avatars1.githubusercontent.com/u/6075379?v=4", + "profile": "https://github.com/anuragagarwal561994", + "contributions": [ + "code" + ] + }, + { + "login": "markusmo3", + "name": "Markus Moser", + "avatar_url": "https://avatars1.githubusercontent.com/u/3317416?v=4", + "profile": "https://markusmo3.github.io", + "contributions": [ + "design", + "code", + "ideas" + ] + }, + { + "login": "isabiq", + "name": "Sabiq Ihab", + "avatar_url": "https://avatars1.githubusercontent.com/u/19510920?v=4", + "profile": "https://twitter.com/i_sabiq", + "contributions": [ + "code" + ] + }, + { + "login": "inbravo", + "name": "Amit Dixit", + "avatar_url": "https://avatars3.githubusercontent.com/u/5253764?v=4", + "profile": "http://inbravo.github.io", + "contributions": [ + "code" + ] + }, + { + "login": "piyushchaudhari04", + "name": "Piyush Kailash Chaudhari", + "avatar_url": "https://avatars3.githubusercontent.com/u/10268029?v=4", + "profile": "https://github.com/piyushchaudhari04", + "contributions": [ + "code" + ] + }, + { + "login": "joshzambales", + "name": "joshzambales", + "avatar_url": "https://avatars1.githubusercontent.com/u/8704552?v=4", + "profile": "https://github.com/joshzambales", + "contributions": [ + "code" + ] + }, + { + "login": "Crossy147", + "name": "Kamil Pietruszka", + "avatar_url": "https://avatars2.githubusercontent.com/u/7272996?v=4", + "profile": "https://github.com/Crossy147", + "contributions": [ + "code" + ] + }, + { + "login": "zafarella", + "name": "Zafar Khaydarov", + "avatar_url": "https://avatars2.githubusercontent.com/u/660742?v=4", + "profile": "http://cs.joensuu.fi/~zkhayda", + "contributions": [ + "code", + "doc" + ] + }, + { + "login": "kemitix", + "name": "Paul Campbell", + "avatar_url": "https://avatars1.githubusercontent.com/u/1147749?v=4", + "profile": "https://kemitix.github.io/", + "contributions": [ + "code" + ] + }, + { + "login": "Argyro-Sioziou", + "name": "Argyro Sioziou", + "avatar_url": "https://avatars0.githubusercontent.com/u/22822639?v=4", + "profile": "https://github.com/Argyro-Sioziou", + "contributions": [ + "code" + ] + }, + { + "login": "TylerMcConville", + "name": "TylerMcConville", + "avatar_url": "https://avatars0.githubusercontent.com/u/4946449?v=4", + "profile": "https://github.com/TylerMcConville", + "contributions": [ + "code" + ] + }, + { + "login": "saksham93", + "name": "saksham93", + "avatar_url": "https://avatars1.githubusercontent.com/u/37399540?v=4", + "profile": "https://github.com/saksham93", + "contributions": [ + "code" + ] + }, + { + "login": "nikhilbarar", + "name": "nikhilbarar", + "avatar_url": "https://avatars2.githubusercontent.com/u/37332144?v=4", + "profile": "https://github.com/nikhilbarar", + "contributions": [ + "code" + ] + }, + { + "login": "colinbut", + "name": "Colin But", + "avatar_url": "https://avatars2.githubusercontent.com/u/10725674?v=4", + "profile": "http://colinbut.com", + "contributions": [ + "code" + ] + }, + { + "login": "ruslanpa", + "name": "Ruslan", + "avatar_url": "https://avatars2.githubusercontent.com/u/1503411?v=4", + "profile": "https://github.com/ruslanpa", + "contributions": [ + "code" + ] + }, + { + "login": "JuhoKang", + "name": "Juho Kang", + "avatar_url": "https://avatars1.githubusercontent.com/u/4745294?v=4", + "profile": "https://github.com/JuhoKang", + "contributions": [ + "code" + ] + }, + { + "login": "dheeraj-mummareddy", + "name": "Dheeraj Mummareddy", + "avatar_url": "https://avatars2.githubusercontent.com/u/7002230?v=4", + "profile": "https://github.com/dheeraj-mummareddy", + "contributions": [ + "code" + ] + }, + { + "login": "bernardosulzbach", + "name": "Bernardo Sulzbach", + "avatar_url": "https://avatars0.githubusercontent.com/u/8271090?v=4", + "profile": "https://www.bernardosulzbach.com", + "contributions": [ + "code" + ] + }, + { + "login": "4lexis", + "name": "Aleksandar Dudukovic", + "avatar_url": "https://avatars0.githubusercontent.com/u/19871727?v=4", + "profile": "https://github.com/4lexis", + "contributions": [ + "code" + ] + }, + { + "login": "yusufaytas", + "name": "Yusuf Aytaş", + "avatar_url": "https://avatars2.githubusercontent.com/u/1049483?v=4", + "profile": "https://www.yusufaytas.com", + "contributions": [ + "code" + ] + }, + { + "login": "qpi", + "name": "Mihály Kuprivecz", + "avatar_url": "https://avatars2.githubusercontent.com/u/1001491?v=4", + "profile": "http://futurehomes.hu", + "contributions": [ + "code" + ] + }, + { + "login": "kapinuss", + "name": "Stanislav Kapinus", + "avatar_url": "https://avatars0.githubusercontent.com/u/17639945?v=4", + "profile": "https://github.com/kapinuss", + "contributions": [ + "code" + ] + }, + { + "login": "gvsharma", + "name": "GVSharma", + "avatar_url": "https://avatars1.githubusercontent.com/u/6648152?v=4", + "profile": "https://github.com/gvsharma", + "contributions": [ + "code" + ] + }, + { + "login": "SrdjanPaunovic", + "name": "Srđan Paunović", + "avatar_url": "https://avatars1.githubusercontent.com/u/22815104?v=4", + "profile": "https://github.com/SrdjanPaunovic", + "contributions": [ + "code" + ] + }, + { + "login": "sideris", + "name": "Petros G. Sideris", + "avatar_url": "https://avatars3.githubusercontent.com/u/5484694?v=4", + "profile": "https://sideris.xyz/", + "contributions": [ + "code" + ] + }, + { + "login": "IAmPramod", + "name": "Pramod Gupta", + "avatar_url": "https://avatars1.githubusercontent.com/u/2184241?v=4", + "profile": "https://www.linkedin.com/in/pramodgupta3/", + "contributions": [ + "review" + ] + }, + { + "login": "Amarnath510", + "name": "Amarnath Chandana", + "avatar_url": "https://avatars0.githubusercontent.com/u/4599623?v=4", + "profile": "https://amarnath510.github.io/portfolio", + "contributions": [ + "code" + ] + }, + { + "login": "Anurag870", + "name": "Anurag870", + "avatar_url": "https://avatars1.githubusercontent.com/u/6295975?v=4", + "profile": "https://github.com/Anurag870", + "contributions": [ + "code", + "doc" + ] + }, + { + "login": "Deathnerd", + "name": "Wes Gilleland", + "avatar_url": "https://avatars0.githubusercontent.com/u/1685953?v=4", + "profile": "http://theerroris.me", + "contributions": [ + "code" + ] + }, + { + "login": "Harshrajsinh", + "name": "Harshraj Thakor", + "avatar_url": "https://avatars2.githubusercontent.com/u/22811531?v=4", + "profile": "https://github.com/Harshrajsinh", + "contributions": [ + "code" + ] + }, + { + "login": "MaVdbussche", + "name": "Martin Vandenbussche", + "avatar_url": "https://avatars1.githubusercontent.com/u/26136934?v=4", + "profile": "https://github.com/MaVdbussche", + "contributions": [ + "code" + ] + }, + { + "login": "alexsomai", + "name": "Alexandru Somai", + "avatar_url": "https://avatars1.githubusercontent.com/u/5720977?v=4", + "profile": "https://alexsomai.com", + "contributions": [ + "code" + ] + }, + { + "login": "amogozov", + "name": "Artur Mogozov", + "avatar_url": "https://avatars3.githubusercontent.com/u/7372215?v=4", + "profile": "https://github.com/amogozov", + "contributions": [ + "code" + ] + }, + { + "login": "anthonycampbell", + "name": "anthony", + "avatar_url": "https://avatars3.githubusercontent.com/u/10249255?v=4", + "profile": "https://github.com/anthonycampbell", + "contributions": [ + "code" + ] + }, + { + "login": "christophercolumbusdog", + "name": "Christian Cygnus", + "avatar_url": "https://avatars1.githubusercontent.com/u/9342724?v=4", + "profile": "http://ccygnus.com/", + "contributions": [ + "code" + ] + }, + { + "login": "dzmitryh", + "name": "Dima Gubin", + "avatar_url": "https://avatars2.githubusercontent.com/u/5390492?v=4", + "profile": "https://about.me/dzmitryh", + "contributions": [ + "code" + ] + }, + { + "login": "jjjimenez100", + "name": "Joshua Jimenez", + "avatar_url": "https://avatars3.githubusercontent.com/u/22243493?v=4", + "profile": "https://github.com/jjjimenez100", + "contributions": [ + "code" + ] + }, + { + "login": "kaiwinter", + "name": "Kai Winter", + "avatar_url": "https://avatars0.githubusercontent.com/u/110982?v=4", + "profile": "http://about.me/kaiwinter", + "contributions": [ + "code" + ] + }, + { + "login": "lbroman", + "name": "lbroman", + "avatar_url": "https://avatars1.githubusercontent.com/u/86007?v=4", + "profile": "https://github.com/lbroman", + "contributions": [ + "code" + ] + }, + { + "login": "pnowy", + "name": "Przemek", + "avatar_url": "https://avatars1.githubusercontent.com/u/3254609?v=4", + "profile": "https://przemeknowak.com", + "contributions": [ + "code" + ] + }, + { + "login": "prafful1", + "name": "Prafful Agarwal", + "avatar_url": "https://avatars0.githubusercontent.com/u/14350274?v=4", + "profile": "https://github.com/prafful1", + "contributions": [ + "content" + ] + }, + { + "login": "sankypanhale", + "name": "Sanket Panhale", + "avatar_url": "https://avatars1.githubusercontent.com/u/6478783?v=4", + "profile": "https://github.com/sankypanhale", + "contributions": [ + "content" + ] + }, + { + "login": "staillebois", + "name": "staillebois", + "avatar_url": "https://avatars0.githubusercontent.com/u/23701200?v=4", + "profile": "https://github.com/staillebois", + "contributions": [ + "code" + ] + }, + { + "login": "valdar-hu", + "name": "Krisztián Nagy", + "avatar_url": "https://avatars3.githubusercontent.com/u/17962817?v=4", + "profile": "https://github.com/valdar-hu", + "contributions": [ + "code" + ] + }, + { + "login": "vanogrid", + "name": "Alexander Ivanov", + "avatar_url": "https://avatars0.githubusercontent.com/u/4307918?v=4", + "profile": "https://www.vanogrid.com", + "contributions": [ + "code" + ] + }, + { + "login": "yosfik", + "name": "Yosfik Alqadri", + "avatar_url": "https://avatars3.githubusercontent.com/u/4850270?v=4", + "profile": "https://github.com/yosfik", + "contributions": [ + "code" + ] + }, + { + "login": "7agustibm", + "name": "Agustí Becerra Milà", + "avatar_url": "https://avatars0.githubusercontent.com/u/8149332?v=4", + "profile": "https://github.com/7agustibm", + "contributions": [ + "code" + ] + }, + { + "login": "Juaanma", + "name": "Juan Manuel Suárez", + "avatar_url": "https://avatars3.githubusercontent.com/u/7390500?v=4", + "profile": "https://github.com/Juaanma", + "contributions": [ + "code" + ] + }, + { + "login": "LuigiCortese", + "name": "Luigi Cortese", + "avatar_url": "https://avatars0.githubusercontent.com/u/9956006?v=4", + "profile": "http://www.devsedge.net/", + "contributions": [ + "code" + ] + }, + { + "login": "Rzeposlaw", + "name": "Katarzyna Rzepecka", + "avatar_url": "https://avatars2.githubusercontent.com/u/18425745?v=4", + "profile": "https://github.com/Rzeposlaw", + "contributions": [ + "code" + ] + }, + { + "login": "akrystian", + "name": "adamski.pro", + "avatar_url": "https://avatars1.githubusercontent.com/u/6537430?v=4", + "profile": "http://adamski.pro", + "contributions": [ + "code" + ] + }, + { + "login": "baislsl", + "name": "Shengli Bai", + "avatar_url": "https://avatars0.githubusercontent.com/u/17060584?v=4", + "profile": "https://github.com/baislsl", + "contributions": [ + "code" + ] + }, + { + "login": "besok", + "name": "Boris", + "avatar_url": "https://avatars2.githubusercontent.com/u/29834592?v=4", + "profile": "https://github.com/besok", + "contributions": [ + "code" + ] + }, + { + "login": "dmitraver", + "name": "Dmitry Avershin", + "avatar_url": "https://avatars3.githubusercontent.com/u/1798156?v=4", + "profile": "https://github.com/dmitraver", + "contributions": [ + "code" + ] + }, + { + "login": "fanofxiaofeng", + "name": "靳阳", + "avatar_url": "https://avatars0.githubusercontent.com/u/3983683?v=4", + "profile": "https://github.com/fanofxiaofeng", + "contributions": [ + "code" + ] + }, + { + "login": "hoangnam2261", + "name": "hoangnam2261", + "avatar_url": "https://avatars2.githubusercontent.com/u/31692990?v=4", + "profile": "https://github.com/hoangnam2261", + "contributions": [ + "code" + ] + }, + { + "login": "jarpit96", + "name": "Arpit Jain", + "avatar_url": "https://avatars2.githubusercontent.com/u/10098713?v=4", + "profile": "https://github.com/jarpit96", + "contributions": [ + "code" + ] + }, + { + "login": "joningiwork", + "name": "Jón Ingi Sveinbjörnsson", + "avatar_url": "https://avatars2.githubusercontent.com/u/6115148?v=4", + "profile": "http://joningi.net", + "contributions": [ + "code" + ] + }, + { + "login": "kirill-vlasov", + "name": "Kirill Vlasov", + "avatar_url": "https://avatars3.githubusercontent.com/u/16112495?v=4", + "profile": "https://github.com/kirill-vlasov", + "contributions": [ + "code" + ] + }, + { + "login": "mitchellirvin", + "name": "Mitchell Irvin", + "avatar_url": "https://avatars0.githubusercontent.com/u/16233245?v=4", + "profile": "http://mitchell-irvin.com", + "contributions": [ + "code" + ] + }, + { + "login": "ranjeet-floyd", + "name": "Ranjeet", + "avatar_url": "https://avatars0.githubusercontent.com/u/1992972?v=4", + "profile": "https://ranjeet-floyd.github.io", + "contributions": [ + "code" + ] + }, + { + "login": "Alwayswithme", + "name": "PhoenixYip", + "avatar_url": "https://avatars3.githubusercontent.com/u/3234786?v=4", + "profile": "https://alwayswithme.github.io", + "contributions": [ + "code" + ] + }, + { + "login": "MSaifAsif", + "name": "M Saif Asif", + "avatar_url": "https://avatars1.githubusercontent.com/u/6280554?v=4", + "profile": "https://github.com/MSaifAsif", + "contributions": [ + "code" + ] + }, + { + "login": "kanwarpreet25", + "name": "kanwarpreet25", + "avatar_url": "https://avatars0.githubusercontent.com/u/39183641?v=4", + "profile": "https://github.com/kanwarpreet25", + "contributions": [ + "code" + ] + }, + { + "login": "leonmak", + "name": "Leon Mak", + "avatar_url": "https://avatars3.githubusercontent.com/u/13071508?v=4", + "profile": "http://leonmak.me", + "contributions": [ + "code" + ] + }, + { + "login": "perwramdemark", + "name": "Per Wramdemark", + "avatar_url": "https://avatars2.githubusercontent.com/u/7052193?v=4", + "profile": "http://www.wramdemark.se", + "contributions": [ + "code" + ] + }, + { + "login": "waisuan", + "name": "Evan Sia Wai Suan", + "avatar_url": "https://avatars2.githubusercontent.com/u/10975700?v=4", + "profile": "https://github.com/waisuan", + "contributions": [ + "code" + ] + }, + { + "login": "AnaghaSasikumar", + "name": "AnaghaSasikumar", + "avatar_url": "https://avatars2.githubusercontent.com/u/42939261?v=4", + "profile": "https://github.com/AnaghaSasikumar", + "contributions": [ + "code" + ] + }, + { + "login": "christofferh", + "name": "Christoffer Hamberg", + "avatar_url": "https://avatars1.githubusercontent.com/u/767643?v=4", + "profile": "https://christofferh.com", + "contributions": [ + "code" + ] + }, + { + "login": "dgruntz", + "name": "Dominik Gruntz", + "avatar_url": "https://avatars0.githubusercontent.com/u/1516800?v=4", + "profile": "https://github.com/dgruntz", + "contributions": [ + "code" + ] + }, + { + "login": "hannespernpeintner", + "name": "Hannes", + "avatar_url": "https://avatars3.githubusercontent.com/u/1679437?v=4", + "profile": "https://bitbucket.org/hannespernpeintner/", + "contributions": [ + "code" + ] + }, + { + "login": "leogtzr", + "name": "Leo Gutiérrez Ramírez", + "avatar_url": "https://avatars0.githubusercontent.com/u/1211969?v=4", + "profile": "https://github.com/leogtzr", + "contributions": [ + "code" + ] + }, + { + "login": "npczwh", + "name": "Zhang WH", + "avatar_url": "https://avatars0.githubusercontent.com/u/14066422?v=4", + "profile": "https://github.com/npczwh", + "contributions": [ + "code" + ] + }, + { + "login": "oconnelc", + "name": "Christopher O'Connell", + "avatar_url": "https://avatars0.githubusercontent.com/u/1112973?v=4", + "profile": "https://github.com/oconnelc", + "contributions": [ + "code" + ] + }, + { + "login": "giorgosmav21", + "name": "George Mavroeidis", + "avatar_url": "https://avatars2.githubusercontent.com/u/22855493?v=4", + "profile": "https://github.com/giorgosmav21", + "contributions": [ + "code" + ] + }, + { + "login": "hbothra15", + "name": "Hemant Bothra", + "avatar_url": "https://avatars1.githubusercontent.com/u/7418012?v=4", + "profile": "https://github.com/hbothra15", + "contributions": [ + "code", + "design" + ] + }, + { + "login": "igeligel", + "name": "Kevin Peters", + "avatar_url": "https://avatars1.githubusercontent.com/u/12736734?v=4", + "profile": "https://www.kevinpeters.net/about/", + "contributions": [ + "code" + ] + }, + { + "login": "llorllale", + "name": "George Aristy", + "avatar_url": "https://avatars1.githubusercontent.com/u/2019896?v=4", + "profile": "https://llorllale.github.io/", + "contributions": [ + "code" + ] + }, + { + "login": "mookkiah", + "name": "Mahendran Mookkiah", + "avatar_url": "https://avatars1.githubusercontent.com/u/8975264?v=4", + "profile": "https://github.com/mookkiah", + "contributions": [ + "code" + ] + }, + { + "login": "Azureyjt", + "name": "Azureyjt", + "avatar_url": "https://avatars2.githubusercontent.com/u/18476317?v=4", + "profile": "https://github.com/Azureyjt", + "contributions": [ + "code" + ] + }, + { + "login": "vehpsr", + "name": "gans", + "avatar_url": "https://avatars2.githubusercontent.com/u/3133265?v=4", + "profile": "https://github.com/vehpsr", + "contributions": [ + "code" + ] + }, + { + "login": "ThatGuyWithTheHat", + "name": "Matt", + "avatar_url": "https://avatars0.githubusercontent.com/u/24470582?v=4", + "profile": "https://github.com/ThatGuyWithTheHat", + "contributions": [ + "content" + ] + }, + { + "login": "gopinath-langote", + "name": "Gopinath Langote", + "avatar_url": "https://avatars2.githubusercontent.com/u/10210778?v=4", + "profile": "https://www.linkedin.com/in/gopinathlangote/", + "contributions": [ + "code" + ] + }, + { + "login": "hoswey", + "name": "Hoswey", + "avatar_url": "https://avatars3.githubusercontent.com/u/3689445?v=4", + "profile": "https://github.com/hoswey", + "contributions": [ + "code" + ] + }, + { + "login": "amit2103", + "name": "Amit Pandey", + "avatar_url": "https://avatars3.githubusercontent.com/u/7566692?v=4", + "profile": "https://github.com/amit2103", + "contributions": [ + "code" + ] + }, + { + "login": "gwildor28", + "name": "gwildor28", + "avatar_url": "https://avatars0.githubusercontent.com/u/16000365?v=4", + "profile": "https://github.com/gwildor28", + "contributions": [ + "content" + ] + }, + { + "login": "llitfkitfk", + "name": "田浩", + "avatar_url": "https://avatars1.githubusercontent.com/u/2404785?v=4", + "profile": "https://t.me/paul_docker", + "contributions": [ + "content" + ] + }, + { + "login": "pitsios-s", + "name": "Stamatis Pitsios", + "avatar_url": "https://avatars1.githubusercontent.com/u/6773603?v=4", + "profile": "https://twitter.com/StPitsios", + "contributions": [ + "code" + ] + }, + { + "login": "qza", + "name": "qza", + "avatar_url": "https://avatars3.githubusercontent.com/u/233149?v=4", + "profile": "https://github.com/qza", + "contributions": [ + "code" + ] + }, + { + "login": "Tschis", + "name": "Rodolfo Forte", + "avatar_url": "https://avatars1.githubusercontent.com/u/20662669?v=4", + "profile": "http://tschis.github.io", + "contributions": [ + "content" + ] + }, + { + "login": "ankurkaushal", + "name": "Ankur Kaushal", + "avatar_url": "https://avatars2.githubusercontent.com/u/2236616?v=4", + "profile": "https://github.com/ankurkaushal", + "contributions": [ + "code" + ] + }, + { + "login": "okinskas", + "name": "Ovidijus Okinskas", + "avatar_url": "https://avatars0.githubusercontent.com/u/20372387?v=4", + "profile": "https://www.linkedin.com/in/ovidijus-okinskas/", + "contributions": [ + "code" + ] + }, + { + "login": "robertt240", + "name": "Robert Kasperczyk", + "avatar_url": "https://avatars1.githubusercontent.com/u/9137432?v=4", + "profile": "https://github.com/robertt240", + "contributions": [ + "code" + ] + }, + { + "login": "trautonen", + "name": "Tapio Rautonen", + "avatar_url": "https://avatars3.githubusercontent.com/u/1641063?v=4", + "profile": "https://github.com/trautonen", + "contributions": [ + "code" + ] + }, + { + "login": "yorlov", + "name": "Yuri Orlov", + "avatar_url": "https://avatars0.githubusercontent.com/u/1595733?v=4", + "profile": "http://vk.com/yuri.orlov", + "contributions": [ + "code" + ] + }, + { + "login": "varunu28", + "name": "Varun Upadhyay", + "avatar_url": "https://avatars0.githubusercontent.com/u/7676016?v=4", + "profile": "https://www.linkedin.com/in/varunu28/", + "contributions": [ + "code" + ] + }, + { + "login": "PalAditya", + "name": "Aditya Pal", + "avatar_url": "https://avatars2.githubusercontent.com/u/25523604?v=4", + "profile": "https://github.com/PalAditya", + "contributions": [ + "code" + ] + }, + { + "login": "grzesiekkedzior", + "name": "grzesiekkedzior", + "avatar_url": "https://avatars3.githubusercontent.com/u/23739158?v=4", + "profile": "https://github.com/grzesiekkedzior", + "contributions": [ + "code", + "review" + ] + }, + { + "login": "sivasubramanim", + "name": "Sivasubramani M", + "avatar_url": "https://avatars2.githubusercontent.com/u/51107434?v=4", + "profile": "https://github.com/sivasubramanim", + "contributions": [ + "code" + ] + }, + { + "login": "d4gg4d", + "name": "Sami Airaksinen", + "avatar_url": "https://avatars2.githubusercontent.com/u/99457?v=4", + "profile": "https://github.com/d4gg4d", + "contributions": [ + "code" + ] + }, + { + "login": "vertti", + "name": "Janne Sinivirta", + "avatar_url": "https://avatars0.githubusercontent.com/u/557751?v=4", + "profile": "https://github.com/vertti", + "contributions": [ + "code" + ] + }, + { + "login": "Bobo1239", + "name": "Boris-Chengbiao Zhou", + "avatar_url": "https://avatars1.githubusercontent.com/u/2302947?v=4", + "profile": "https://github.com/Bobo1239", + "contributions": [ + "content" + ] + }, + { + "login": "Jahhein", + "name": "Jacob Hein", + "avatar_url": "https://avatars2.githubusercontent.com/u/10779515?v=4", + "profile": "https://jahhein.github.io", + "contributions": [ + "content" + ] + }, + { + "login": "iamrichardjones", + "name": "Richard Jones", + "avatar_url": "https://avatars3.githubusercontent.com/u/14842151?v=4", + "profile": "https://github.com/iamrichardjones", + "contributions": [ + "content" + ] + }, + { + "login": "rachelcarmena", + "name": "Rachel M. Carmena", + "avatar_url": "https://avatars0.githubusercontent.com/u/22792183?v=4", + "profile": "https://rachelcarmena.github.io", + "contributions": [ + "content" + ] + }, + { + "login": "zd-zero", + "name": "Zaerald Denze Lungos", + "avatar_url": "https://avatars0.githubusercontent.com/u/21978370?v=4", + "profile": "https://zd-zero.github.io", + "contributions": [ + "content" + ] + }, + { + "login": "webpro", + "name": "Lars Kappert", + "avatar_url": "https://avatars1.githubusercontent.com/u/456426?v=4", + "profile": "https://webpro.nl", + "contributions": [ + "content" + ] + }, + { + "login": "xiaod-dev", + "name": "Mike Liu", + "avatar_url": "https://avatars2.githubusercontent.com/u/21277644?v=4", + "profile": "https://xiaod.info", + "contributions": [ + "translation" + ] + }, + { + "login": "charlesfinley", + "name": "Matt Dolan", + "avatar_url": "https://avatars1.githubusercontent.com/u/6307904?v=4", + "profile": "https://github.com/charlesfinley", + "contributions": [ + "code", + "review" + ] + }, + { + "login": "MananS77", + "name": "Manan", + "avatar_url": "https://avatars3.githubusercontent.com/u/21033516?v=4", + "profile": "https://github.com/MananS77", + "contributions": [ + "review" + ] + }, + { + "login": "nishant", + "name": "Nishant Arora", + "avatar_url": "https://avatars2.githubusercontent.com/u/15331971?v=4", + "profile": "https://github.com/nishant", + "contributions": [ + "code" + ] + }, + { + "login": "raja-peeyush-kumar-singh", + "name": "Peeyush", + "avatar_url": "https://avatars0.githubusercontent.com/u/5496024?v=4", + "profile": "https://github.com/raja-peeyush-kumar-singh", + "contributions": [ + "code" + ] + }, + { + "login": "ravening", + "name": "Rakesh", + "avatar_url": "https://avatars1.githubusercontent.com/u/10645273?v=4", + "profile": "https://github.com/ravening", + "contributions": [ + "code", + "review" + ] + }, + { + "login": "vINCENT8888801", + "name": "Wei Seng", + "avatar_url": "https://avatars0.githubusercontent.com/u/8037883?v=4", + "profile": "https://github.com/vINCENT8888801", + "contributions": [ + "code" + ] + }, + { + "login": "ashishtrivedi16", + "name": "Ashish Trivedi", + "avatar_url": "https://avatars3.githubusercontent.com/u/23194128?v=4", + "profile": "https://www.linkedin.com/in/ashish-trivedi-218379135/", + "contributions": [ + "code" + ] + }, + { + "login": "RayYH", + "name": "洪月阳", + "avatar_url": "https://avatars1.githubusercontent.com/u/41055099?v=4", + "profile": "https://rayyounghong.com", + "contributions": [ + "code" + ] + }, + { + "login": "xdvrx1", + "name": "xdvrx1", + "avatar_url": "https://avatars0.githubusercontent.com/u/47092464?v=4", + "profile": "https://xdvrx1.github.io/", + "contributions": [ + "review", + "ideas" + ] + }, + { + "login": "nahteb", + "name": "Bethan Palmer", + "avatar_url": "https://avatars3.githubusercontent.com/u/13121570?v=4", + "profile": "https://github.com/nahteb", + "contributions": [ + "code" + ] + }, + { + "login": "ToxicDreamz", + "name": "Toxic Dreamz", + "avatar_url": "https://avatars0.githubusercontent.com/u/45225562?v=4", + "profile": "https://github.com/ToxicDreamz", + "contributions": [ + "code" + ] + }, + { + "login": "edycutjong", + "name": "Edy Cu Tjong", + "avatar_url": "https://avatars1.githubusercontent.com/u/1098102?v=4", + "profile": "http://www.edycutjong.com", + "contributions": [ + "doc" + ] + }, + { + "login": "mkrzywanski", + "name": "Michał Krzywański", + "avatar_url": "https://avatars0.githubusercontent.com/u/15279585?v=4", + "profile": "https://github.com/mkrzywanski", + "contributions": [ + "code" + ] + }, + { + "login": "stefanbirkner", + "name": "Stefan Birkner", + "avatar_url": "https://avatars1.githubusercontent.com/u/711349?v=4", + "profile": "https://www.stefan-birkner.de", + "contributions": [ + "code" + ] + }, + { + "login": "fedorskvorcov", + "name": "Fedor Skvorcov", + "avatar_url": "https://avatars3.githubusercontent.com/u/43882212?v=4", + "profile": "https://github.com/fedorskvorcov", + "contributions": [ + "code" + ] + }, + { + "login": "samilAyoub", + "name": "samilAyoub", + "avatar_url": "https://avatars0.githubusercontent.com/u/61546990?v=4", + "profile": "https://github.com/samilAyoub", + "contributions": [ + "code" + ] + }, + { + "login": "vdlald", + "name": "Vladislav Golubinov", + "avatar_url": "https://avatars0.githubusercontent.com/u/29997701?v=4", + "profile": "https://github.com/vdlald", + "contributions": [ + "code" + ] + }, + { + "login": "swarajsaaj", + "name": "Swaraj", + "avatar_url": "https://avatars2.githubusercontent.com/u/6285049?v=4", + "profile": "https://github.com/swarajsaaj", + "contributions": [ + "code" + ] + }, + { + "login": "ChFlick", + "name": "Christoph Flick", + "avatar_url": "https://avatars0.githubusercontent.com/u/4465376?v=4", + "profile": "http://christophflick.de", + "contributions": [ + "doc" + ] + }, + { + "login": "Ascenio", + "name": "Ascênio", + "avatar_url": "https://avatars1.githubusercontent.com/u/7662016?v=4", + "profile": "https://github.com/Ascenio", + "contributions": [ + "review" + ] + }, + { + "login": "dsibilio", + "name": "Domenico Sibilio", + "avatar_url": "https://avatars2.githubusercontent.com/u/24280982?v=4", + "profile": "https://www.linkedin.com/in/domenico-sibilio/", + "contributions": [ + "doc" + ] + }, + { + "login": "akashchandwani", + "name": "Akash Chandwani", + "avatar_url": "https://avatars2.githubusercontent.com/u/3483277?v=4", + "profile": "https://github.com/akashchandwani", + "contributions": [ + "review" + ] + }, + { + "login": "manannikov", + "name": "Pavlo Manannikov", + "avatar_url": "https://avatars2.githubusercontent.com/u/7019769?v=4", + "profile": "http://www.linkedin.com/in/manannikov", + "contributions": [ + "code" + ] + }, + { + "login": "eimanip", + "name": "Eiman", + "avatar_url": "https://avatars0.githubusercontent.com/u/20307301?v=4", + "profile": "https://github.com/eimanip", + "contributions": [ + "code" + ] + }, + { + "login": "OrangePants-R", + "name": "Rocky", + "avatar_url": "https://avatars0.githubusercontent.com/u/42976136?v=4", + "profile": "https://github.com/OrangePants-R", + "contributions": [ + "doc" + ] + }, + { + "login": "ibrahimAlii", + "name": "Ibrahim ali abdelghany", + "avatar_url": "https://avatars2.githubusercontent.com/u/21141301?v=4", + "profile": "https://ibrahimalii.github.io/", + "contributions": [ + "review" + ] + }, + { + "login": "gkulkarni2020", + "name": "Girish Kulkarni", + "avatar_url": "https://avatars3.githubusercontent.com/u/5161548?v=4", + "profile": "https://github.com/gkulkarni2020", + "contributions": [ + "doc" + ] + }, + { + "login": "omk13", + "name": "Omar Karazoun", + "avatar_url": "https://avatars0.githubusercontent.com/u/59054172?v=4", + "profile": "https://github.com/omk13", + "contributions": [ + "code" + ] + }, + { + "login": "jeff303", + "name": "Jeff Evans", + "avatar_url": "https://avatars0.githubusercontent.com/u/3521562?v=4", + "profile": "https://github.com/jeff303", + "contributions": [ + "code" + ] + }, + { + "login": "viveksb007", + "name": "Vivek Singh", + "avatar_url": "https://avatars1.githubusercontent.com/u/12713808?v=4", + "profile": "https://viveksb007.github.io", + "contributions": [ + "code" + ] + }, + { + "login": "siavashsoleymani", + "name": "siavash", + "avatar_url": "https://avatars2.githubusercontent.com/u/18074419?v=4", + "profile": "https://github.com/siavashsoleymani", + "contributions": [ + "code" + ] + }, + { + "login": "ruchpeanuts", + "name": "ruchpeanuts", + "avatar_url": "https://avatars0.githubusercontent.com/u/29301900?v=4", + "profile": "https://github.com/ruchpeanuts", + "contributions": [ + "doc" + ] + }, + { + "login": "warp125", + "name": "warp125", + "avatar_url": "https://avatars1.githubusercontent.com/u/48073115?v=4", + "profile": "https://github.com/warp125", + "contributions": [ + "translation" + ] + }, + { + "login": "tkhadir", + "name": "KHADIR Tayeb", + "avatar_url": "https://avatars1.githubusercontent.com/u/45130488?v=4", + "profile": "http://libkhadir.fr", + "contributions": [ + "translation" + ] + }, + { + "login": "ignite1771", + "name": "ignite1771", + "avatar_url": "https://avatars2.githubusercontent.com/u/59446563?v=4", + "profile": "https://github.com/ignite1771", + "contributions": [ + "code" + ] + }, + { + "login": "demirhalil", + "name": "Halil Demir", + "avatar_url": "https://avatars1.githubusercontent.com/u/22895118?v=4", + "profile": "https://github.com/demirhalil", + "contributions": [ + "translation" + ] + }, + { + "login": "rohit10000", + "name": "Rohit Singh", + "avatar_url": "https://avatars.githubusercontent.com/u/20845565?v=4", + "profile": "https://github.com/rohit10000", + "contributions": [ + "code" + ] + }, + { + "login": "byoungju94", + "name": "byoungju94", + "avatar_url": "https://avatars.githubusercontent.com/u/42516378?v=4", + "profile": "https://github.com/byoungju94", + "contributions": [ + "code" + ] + }, + { + "login": "moustafafarhat", + "name": "Moustafa Farhat", + "avatar_url": "https://avatars.githubusercontent.com/u/38836727?v=4", + "profile": "https://github.com/moustafafarhat", + "contributions": [ + "translation" + ] + }, + { + "login": "richardmr36", + "name": "Martel Richard", + "avatar_url": "https://avatars.githubusercontent.com/u/19147333?v=4", + "profile": "https://github.com/richardmr36", + "contributions": [ + "code" + ] + }, + { + "login": "va1m", + "name": "va1m", + "avatar_url": "https://avatars.githubusercontent.com/u/17025445?v=4", + "profile": "https://github.com/va1m", + "contributions": [ + "code" + ] + }, + { + "login": "noamgrinch", + "name": "Noam Greenshtain", + "avatar_url": "https://avatars.githubusercontent.com/u/31648669?v=4", + "profile": "https://github.com/noamgrinch", + "contributions": [ + "code" + ] + }, + { + "login": "qfxl", + "name": "yonghong Xu", + "avatar_url": "https://avatars.githubusercontent.com/u/14086462?v=4", + "profile": "https://xuyonghong.cn/", + "contributions": [ + "doc" + ] + }, + { + "login": "jinishavora", + "name": "jinishavora", + "avatar_url": "https://avatars.githubusercontent.com/u/40777762?v=4", + "profile": "https://www.linkedin.com/in/jinisha-vora", + "contributions": [ + "review", + "code" + ] + }, + { + "login": "eas5", + "name": "Elvys Soares", + "avatar_url": "https://avatars.githubusercontent.com/u/50836521?v=4", + "profile": "https://github.com/eas5", + "contributions": [ + "code" + ] + }, + { + "login": "zWeBrain", + "name": "zWeBrain", + "avatar_url": "https://avatars.githubusercontent.com/u/46642512?v=4", + "profile": "https://github.com/zWeBrain", + "contributions": [ + "code" + ] + }, + { + "login": "Al-assad", + "name": "余林颖", + "avatar_url": "https://avatars.githubusercontent.com/u/22493821?v=4", + "profile": "https://al-assad.github.io/notion/", + "contributions": [ + "translation" + ] + }, + { + "login": "STudio26", + "name": "Alain", + "avatar_url": "https://avatars.githubusercontent.com/u/6988911?v=4", + "profile": "https://github.com/STudio26", + "contributions": [ + "translation" + ] + }, + { + "login": "DEV-VRUPER", + "name": "VR", + "avatar_url": "https://avatars.githubusercontent.com/u/30525467?v=4", + "profile": "https://github.com/DEV-VRUPER", + "contributions": [ + "doc" + ] + }, + { + "login": "JackieNim", + "name": "JackieNim", + "avatar_url": "https://avatars.githubusercontent.com/u/4138836?v=4", + "profile": "https://github.com/JackieNim", + "contributions": [ + "code" + ] + }, + { + "login": "EdisonE3", + "name": "EdisonE3", + "avatar_url": "https://avatars.githubusercontent.com/u/52118917?v=4", + "profile": "https://github.com/EdisonE3", + "contributions": [ + "code" + ] + }, + { + "login": "tao-sun2", + "name": "Tao", + "avatar_url": "https://avatars.githubusercontent.com/u/66189688?v=4", + "profile": "https://github.com/tao-sun2", + "contributions": [ + "code" + ] + }, + { + "login": "JuanManuelAbate", + "name": "Juan Manuel Abate", + "avatar_url": "https://avatars.githubusercontent.com/u/16357060?v=4", + "profile": "https://github.com/JuanManuelAbate", + "contributions": [ + "translation" + ] + }, + { + "login": "Xenilo137", + "name": "Xenilo137", + "avatar_url": "https://avatars.githubusercontent.com/u/24865069?v=4", + "profile": "https://github.com/Xenilo137", + "contributions": [ + "code" + ] + }, + { + "login": "samuelpsouza", + "name": "Samuel Souza", + "avatar_url": "https://avatars.githubusercontent.com/u/17254162?v=4", + "profile": "https://www.linkedin.com/in/souzasamuel/", + "contributions": [ + "code", + "doc" + ] + }, + { + "login": "marlo2222", + "name": "Marlo Henrique", + "avatar_url": "https://avatars.githubusercontent.com/u/40809563?v=4", + "profile": "https://github.com/marlo2222", + "contributions": [ + "translation" + ] + }, + { + "login": "AndriyPyzh", + "name": "AndriyPyzh", + "avatar_url": "https://avatars.githubusercontent.com/u/57706635?v=4", + "profile": "https://github.com/AndriyPyzh", + "contributions": [ + "code" + ] + }, + { + "login": "karthikbhat13", + "name": "karthikbhat13", + "avatar_url": "https://avatars.githubusercontent.com/u/22431014?v=4", + "profile": "https://github.com/karthikbhat13", + "contributions": [ + "code" + ] + }, + { + "login": "mortezaadi", + "name": "Morteza Adigozalpour", + "avatar_url": "https://avatars.githubusercontent.com/u/1329687?v=4", + "profile": "https://github.com/mortezaadi", + "contributions": [ + "code" + ] + }, + { + "login": "tan31989", + "name": "Nagaraj Tantri", + "avatar_url": "https://avatars.githubusercontent.com/u/3784194?v=4", + "profile": "https://stackoverflow.com/users/308565/nagaraj-tantri", + "contributions": [ + "code" + ] + }, + { + "login": "frascu", + "name": "Francesco Scuccimarri", + "avatar_url": "https://avatars.githubusercontent.com/u/7107651?v=4", + "profile": "https://github.com/frascu", + "contributions": [ + "code" + ] + }, + { + "login": "Conhan93", + "name": "Conny Hansson", + "avatar_url": "https://avatars.githubusercontent.com/u/71334757?v=4", + "profile": "https://github.com/Conhan93", + "contributions": [ + "doc" + ] + }, + { + "login": "muklasr", + "name": "Muklas Rahmanto", + "avatar_url": "https://avatars.githubusercontent.com/u/43443753?v=4", + "profile": "http://muklasr.medium.com", + "contributions": [ + "translation" + ] + }, + { + "login": "VxDxK", + "name": "Vadim", + "avatar_url": "https://avatars.githubusercontent.com/u/38704817?v=4", + "profile": "https://github.com/VxDxK", + "contributions": [ + "translation" + ] + }, + { + "login": "sims-keshri", + "name": "Simran Keshri", + "avatar_url": "https://avatars.githubusercontent.com/u/62168475?v=4", + "profile": "https://github.com/sims-keshri", + "contributions": [ + "code" + ] + }, + { + "login": "JCarlosR", + "name": "JCarlos", + "avatar_url": "https://avatars.githubusercontent.com/u/3101238?v=4", + "profile": "https://programacionymas.com", + "contributions": [ + "translation" + ] + }, + { + "login": "Dev-AliGhasemi", + "name": "Ali Ghasemi", + "avatar_url": "https://avatars.githubusercontent.com/u/60359433?v=4", + "profile": "https://www.mrmoshkel.ir", + "contributions": [ + "code" + ] + }, + { + "login": "carldea", + "name": "Carl Dea", + "avatar_url": "https://avatars.githubusercontent.com/u/1594624?v=4", + "profile": "http://carlfx.wordpress.com", + "contributions": [ + "code" + ] + }, + { + "login": "Mozartuss", + "name": "Mozartus", + "avatar_url": "https://avatars.githubusercontent.com/u/32893711?v=4", + "profile": "https://github.com/Mozartuss", + "contributions": [ + "translation" + ] + }, + { + "login": "ManviGoel26", + "name": "Manvi Goel", + "avatar_url": "https://avatars.githubusercontent.com/u/55682355?v=4", + "profile": "https://github.com/ManviGoel26", + "contributions": [ + "doc" + ] + }, + { + "login": "blueberry404", + "name": "Anum Amin", + "avatar_url": "https://avatars.githubusercontent.com/u/39243539?v=4", + "profile": "https://github.com/blueberry404", + "contributions": [ + "doc" + ] + }, + { + "login": "uh-zz", + "name": "Reo Uehara", + "avatar_url": "https://avatars.githubusercontent.com/u/47747828?v=4", + "profile": "https://uh-zz.github.io/blog/", + "contributions": [ + "translation" + ] + }, + { + "login": "Fiordy", + "name": "Fiordy", + "avatar_url": "https://avatars.githubusercontent.com/u/53420573?v=4", + "profile": "https://github.com/Fiordy", + "contributions": [ + "doc" + ] + }, + { + "login": "harshalkh", + "name": "Harshal", + "avatar_url": "https://avatars.githubusercontent.com/u/37841724?v=4", + "profile": "https://github.com/harshalkh", + "contributions": [ + "code" + ] + }, + { + "login": "vashisthabhinav", + "name": "Abhinav Vashisth", + "avatar_url": "https://avatars.githubusercontent.com/u/89785800?v=4", + "profile": "https://www.linkedin.com/in/abhinav-vashisth-06613b208/", + "contributions": [ + "doc" + ] + }, + { + "login": "Kevinyl3", + "name": "Kevin", + "avatar_url": "https://avatars.githubusercontent.com/u/47126749?v=4", + "profile": "http://no website", + "contributions": [ + "review", + "code" + ] + }, + { + "login": "Shrirang97", + "name": "Shrirang", + "avatar_url": "https://avatars.githubusercontent.com/u/28738668?v=4", + "profile": "https://github.com/Shrirang97", + "contributions": [ + "review", + "code" + ] + }, + { + "login": "interactwithankush", + "name": "interactwithankush", + "avatar_url": "https://avatars.githubusercontent.com/u/18613127?v=4", + "profile": "https://github.com/interactwithankush", + "contributions": [ + "code" + ] + }, + { + "login": "yuhangbin", + "name": "CharlieYu", + "avatar_url": "https://avatars.githubusercontent.com/u/17566866?v=4", + "profile": "https://github.com/yuhangbin", + "contributions": [ + "code" + ] + }, + { + "login": "Leisterbecker", + "name": "Leisterbecker", + "avatar_url": "https://avatars.githubusercontent.com/u/20650323?v=4", + "profile": "https://github.com/Leisterbecker", + "contributions": [ + "code" + ] + }, + { + "login": "castleKing1997", + "name": "DragonDreamer", + "avatar_url": "https://avatars.githubusercontent.com/u/35420129?v=4", + "profile": "http://rosaecrucis.cn", + "contributions": [ + "code" + ] + }, + { + "login": "ShivanshCharak", + "name": "ShivanshCharak", + "avatar_url": "https://avatars.githubusercontent.com/u/96943825?v=4", + "profile": "https://github.com/ShivanshCharak", + "contributions": [ + "code" + ] + }, + { + "login": "HattoriHenzo", + "name": "HattoriHenzo", + "avatar_url": "https://avatars.githubusercontent.com/u/5141285?v=4", + "profile": "https://github.com/HattoriHenzo", + "contributions": [ + "code" + ] + }, + { + "login": "arnabsen1729", + "name": "Arnab Sen", + "avatar_url": "https://avatars.githubusercontent.com/u/51032928?v=4", + "profile": "http://arnabsen.bio.link", + "contributions": [ + "code" + ] + }, + { + "login": "mohanaraosv", + "name": "MohanaRao SV", + "avatar_url": "https://avatars.githubusercontent.com/u/1470114?v=4", + "profile": "https://javaforlife.wordpress.com/", + "contributions": [ + "code" + ] + }, + { + "login": "yonatankarp", + "name": "Yonatan Karp-Rudin", + "avatar_url": "https://avatars.githubusercontent.com/u/14914865?v=4", + "profile": "https://github.com/yonatankarp", + "contributions": [ + "code", + "review" + ] + }, + { + "login": "GustavoOliani", + "name": "Oliani", + "avatar_url": "https://avatars.githubusercontent.com/u/25756378?v=4", + "profile": "https://github.com/GustavoOliani", + "contributions": [ + "code" + ] + }, + { + "login": "Liu-rj", + "name": "Renjie LIU", + "avatar_url": "https://avatars.githubusercontent.com/u/64826925?v=4", + "profile": "https://github.com/Liu-rj", + "contributions": [ + "code" + ] + }, + { + "login": "TreeFireMen", + "name": "perfect guy", + "avatar_url": "https://avatars.githubusercontent.com/u/54127694?v=4", + "profile": "https://github.com/TreeFireMen", + "contributions": [ + "doc" + ] + }, + { + "login": "xyllq999", + "name": "xyllq999", + "avatar_url": "https://avatars.githubusercontent.com/u/72729433?v=4", + "profile": "https://github.com/xyllq999", + "contributions": [ + "code" + ] + }, + { + "login": "dmdbilal", + "name": "Mohamed Bilal", + "avatar_url": "https://avatars.githubusercontent.com/u/91405690?v=4", + "profile": "https://github.com/dmdbilal", + "contributions": [ + "doc" + ] + }, + { + "login": "karshil2309", + "name": "Karshil sheth", + "avatar_url": "https://avatars.githubusercontent.com/u/37497287?v=4", + "profile": "https://www.linkedin.com/in/karshilsheth/", + "contributions": [ + "code" + ] + }, + { + "login": "kongleong86", + "name": "kongleong86", + "avatar_url": "https://avatars.githubusercontent.com/u/3745455?v=4", + "profile": "https://github.com/kongleong86", + "contributions": [ + "code" + ] + }, + { + "login": "aitorfi", + "name": "Aitor Fidalgo Sánchez", + "avatar_url": "https://avatars.githubusercontent.com/u/64830228?v=4", + "profile": "https://github.com/aitorfi", + "contributions": [ + "translation", + "doc", + "review" + ] + }, + { + "login": "HeVictor", + "name": "Victor He", + "avatar_url": "https://avatars.githubusercontent.com/u/20733994?v=4", + "profile": "https://github.com/HeVictor", + "contributions": [ + "code" + ] + }, + { + "login": "m-inh", + "name": "Minh Nguyen", + "avatar_url": "https://avatars.githubusercontent.com/u/10632233?v=4", + "profile": "http://m-inh.github.io/", + "contributions": [ + "translation", + "doc" + ] + }, + { + "login": "HeVictor", + "name": "Victor He", + "avatar_url": "https://avatars.githubusercontent.com/u/20733994?v=4", + "profile": "https://github.com/HeVictor", + "contributions": [ + "doc" + ] + }, + { + "login": "YichuanSun", + "name": "yiichan", + "avatar_url": "https://avatars.githubusercontent.com/u/30886176?v=4", + "profile": "https://github.com/YichuanSun", + "contributions": [ + "doc" + ] + }, + { + "login": "PanSem", + "name": "Pan Sem", + "avatar_url": "https://avatars.githubusercontent.com/u/43316964?v=4", + "profile": "https://github.com/PanSem", + "contributions": [ + "doc" + ] + }, + { + "login": "zhoumengyks", + "name": "zhoumengyks", + "avatar_url": "https://avatars.githubusercontent.com/u/111965739?v=4", + "profile": "https://github.com/zhoumengyks", + "contributions": [ + "code" + ] + }, + { + "login": "you", + "name": "you", + "avatar_url": "https://avatars.githubusercontent.com/u/57100752?v=4", + "profile": "https://github.com/you", + "contributions": [ + "translation" + ] + }, + { + "login": "Thanks", + "name": "Thanks", + "avatar_url": "https://avatars.githubusercontent.com/u/1121545?v=4", + "profile": "https://github.com/thanks", + "contributions": [ + "translation" + ] + }, + { + "login": "lazy-pr0grammer", + "name": "LazyProgrammer", + "avatar_url": "https://avatars.githubusercontent.com/u/87204946?v=4", + "profile": "https://github.com/lazy-pr0grammer", + "contributions": [ + "doc" + ] + }, + { + "login": "mdfaizanahmed786", + "name": "Mohammed Faizan Ahmed", + "avatar_url": "https://avatars.githubusercontent.com/u/85175130?v=4", + "profile": "https://github.com/mdfaizanahmed786", + "contributions": [ + "doc" + ] + }, + { + "login": "burno1", + "name": "Bruno Fernandes", + "avatar_url": "https://avatars.githubusercontent.com/u/39165280?v=4", + "profile": "https://github.com/burno1", + "contributions": [ + "code" + ] + }, + { + "login": "SammanPali", + "name": "SammanPali", + "avatar_url": "https://avatars.githubusercontent.com/u/110753804?v=4", + "profile": "https://github.com/SammanPali", + "contributions": [ + "doc" + ] + }, + { + "login": "LeseChe", + "name": "Qixiang Chen", + "avatar_url": "https://avatars.githubusercontent.com/u/79553089?v=4", + "profile": "https://github.com/LeseChe", + "contributions": [ + "doc" + ] + }, + { + "login": "shouryamanekar", + "name": "Shourya Manekar", + "avatar_url": "https://avatars.githubusercontent.com/u/72398499?v=4", + "profile": "https://github.com/shouryamanekar", + "contributions": [ + "translation" + ] + }, + { + "login": "seongkyu-lim", + "name": "Alan", + "avatar_url": "https://avatars.githubusercontent.com/u/55138532?v=4", + "profile": "https://seongkyu-lim.github.io/Blog/", + "contributions": [ + "translation" + ] + }, + { + "login": "JanFidor", + "name": "JanFidor", + "avatar_url": "https://avatars.githubusercontent.com/u/66260538?v=4", + "profile": "https://github.com/JanFidor", + "contributions": [ + "code", + "doc" + ] + }, + { + "login": "drakulavich", + "name": "Anton Yakutovich", + "avatar_url": "https://avatars.githubusercontent.com/u/129260?v=4", + "profile": "https://github.com/drakulavich", + "contributions": [ + "code" + ] + }, + { + "login": "steph88ss", + "name": "steph88ss", + "avatar_url": "https://avatars.githubusercontent.com/u/111041594?v=4", + "profile": "https://github.com/steph88ss", + "contributions": [ + "doc" + ] + }, + { + "login": "0xYujan", + "name": "Yujan Ranjitkar", + "avatar_url": "https://avatars.githubusercontent.com/u/63731234?v=4", + "profile": "http://yujanranjitkar.com.np", + "contributions": [ + "translation" + ] + }, + { + "login": "yusha-g", + "name": "yusha-g", + "avatar_url": "https://avatars.githubusercontent.com/u/110189579?v=4", + "profile": "https://github.com/yusha-g", + "contributions": [ + "translation" + ] + }, + { + "login": "robertvolkmann", + "name": "Robert Volkmann", + "avatar_url": "https://avatars.githubusercontent.com/u/20912167?v=4", + "profile": "https://github.com/robertvolkmann", + "contributions": [ + "code", + "review" + ] + }, + { + "login": "bipin-k", + "name": "Bipin Kumar Chaurasia", + "avatar_url": "https://avatars.githubusercontent.com/u/21119358?v=4", + "profile": "https://github.com/bipin-k", + "contributions": [ + "doc" + ] + }, + { + "login": "KyleSong30", + "name": "KyleSong30", + "avatar_url": "https://avatars.githubusercontent.com/u/100892032?v=4", + "profile": "https://github.com/KyleSong30", + "contributions": [ + "doc" + ] + }, + { + "login": "u7281975", + "name": "u7281975", + "avatar_url": "https://avatars.githubusercontent.com/u/111095623?v=4", + "profile": "https://github.com/u7281975", + "contributions": [ + "doc" + ] + }, + { + "login": "harshalkhachane", + "name": "harshalkhachane", + "avatar_url": "https://avatars.githubusercontent.com/u/92866584?v=4", + "profile": "https://github.com/harshalkhachane", + "contributions": [ + "code" + ] + }, + { + "login": "ec-026", + "name": "Tejas Singh", + "avatar_url": "https://avatars.githubusercontent.com/u/95495584?v=4", + "profile": "https://github.com/ec-026", + "contributions": [ + "doc", + "translation" + ] + }, + { + "login": "artfuldev", + "name": "Sudarsan Balaji", + "avatar_url": "https://avatars.githubusercontent.com/u/3091087?v=4", + "profile": "https://journal.artfuldev.com", + "contributions": [ + "code" + ] + }, + { + "login": "vaibhav-if", + "name": "Vaibhav Agrawal", + "avatar_url": "https://avatars.githubusercontent.com/u/78676331?v=4", + "profile": "https://www.linkedin.com/in/vaibhav-agr/", + "contributions": [ + "doc" + ] + }, + { + "login": "u7275858", + "name": "u7275858", + "avatar_url": "https://avatars.githubusercontent.com/u/110969489?v=4", + "profile": "https://github.com/u7275858", + "contributions": [ + "code" + ] + }, + { + "login": "prasad-333", + "name": "prasad-333", + "avatar_url": "https://avatars.githubusercontent.com/u/37048768?v=4", + "profile": "https://gist.github.com/prasad-333", + "contributions": [ + "doc" + ] + }, + { + "login": "JurenXu", + "name": "JurenXu", + "avatar_url": "https://avatars.githubusercontent.com/u/101047547?v=4", + "profile": "https://github.com/JurenXu", + "contributions": [ + "code" + ] + }, + { + "login": "murphShaw", + "name": "murphShaw", + "avatar_url": "https://avatars.githubusercontent.com/u/111167533?v=4", + "profile": "https://github.com/murphShaw", + "contributions": [ + "doc" + ] + }, + { + "login": "XianWu99", + "name": "XianWu99", + "avatar_url": "https://avatars.githubusercontent.com/u/111103319?v=4", + "profile": "https://github.com/XianWu99", + "contributions": [ + "doc" + ] + }, + { + "login": "JoshuaSinglaANU", + "name": "JoshuaSinglaANU", + "avatar_url": "https://avatars.githubusercontent.com/u/109902734?v=4", + "profile": "https://github.com/JoshuaSinglaANU", + "contributions": [ + "code" + ] + }, + { + "login": "ricardo-ramos-moura", + "name": "Ricardo Ramos", + "avatar_url": "https://avatars.githubusercontent.com/u/36955909?v=4", + "profile": "http://www.linkedin.com/in/ricardo-ramos-moura", + "contributions": [ + "translation" + ] + }, + { + "login": "zhrfrd", + "name": "Farid Zouheir", + "avatar_url": "https://avatars.githubusercontent.com/u/72947724?v=4", + "profile": "https://zhrfrd.github.io/faridzouheir/", + "contributions": [ + "translation" + ] + }, + { + "login": "Viniberaldo", + "name": "Vinícius A. B.", + "avatar_url": "https://avatars.githubusercontent.com/u/91766068?v=4", + "profile": "https://www.linkedin.com/in/vinicius-beraldo/", + "contributions": [ + "translation" + ] + }, + { + "login": "StefanelStan", + "name": "Stefanel Stan", + "avatar_url": "https://avatars.githubusercontent.com/u/25990078?v=4", + "profile": "http://www.linkedin.com/in/stefanel-stan/", + "contributions": [ + "code" + ] + }, + { + "login": "bhati00", + "name": "Prince bhati", + "avatar_url": "https://avatars.githubusercontent.com/u/79313705?v=4", + "profile": "https://github.com/bhati00", + "contributions": [ + "translation" + ] + }, + { + "login": "wulangcode", + "name": "WuLang", + "avatar_url": "https://avatars.githubusercontent.com/u/48200100?v=4", + "profile": "https://github.com/wulangcode", + "contributions": [ + "doc" + ] + }, + { + "login": "hkattt", + "name": "Hugo Kat", + "avatar_url": "https://avatars.githubusercontent.com/u/54300585?v=4", + "profile": "https://github.com/hkattt", + "contributions": [ + "code" + ] + }, + { + "login": "shivu2002a", + "name": "Shivanagouda Agasimani", + "avatar_url": "https://avatars.githubusercontent.com/u/88313126?v=4", + "profile": "https://github.com/shivu2002a", + "contributions": [ + "code" + ] + }, + { + "login": "Ap284", + "name": "Aparna", + "avatar_url": "https://avatars.githubusercontent.com/u/13827254?v=4", + "profile": "https://github.com/Ap284", + "contributions": [ + "code" + ] + }, + { + "login": "girolamo-giordano", + "name": "Girolamo Giordano", + "avatar_url": "https://avatars.githubusercontent.com/u/56109364?v=4", + "profile": "https://github.com/girolamo-giordano", + "contributions": [ + "translation" + ] + }, + { + "login": "Chak-C", + "name": "Chak-C", + "avatar_url": "https://avatars.githubusercontent.com/u/114961815?v=4", + "profile": "https://github.com/Chak-C", + "contributions": [ + "code" + ] + }, + { + "login": "nakul251197", + "name": "Nakul Nambiar", + "avatar_url": "https://avatars.githubusercontent.com/u/39953357?v=4", + "profile": "https://github.com/nakul251197", + "contributions": [ + "code" + ] + }, + { + "login": "KarmaTashiCat", + "name": "KarmaTashiCat", + "avatar_url": "https://avatars.githubusercontent.com/u/76797146?v=4", + "profile": "https://github.com/KarmaTashiCat", + "contributions": [ + "translation" + ] + }, + { + "login": "Marikattt", + "name": "marikattt", + "avatar_url": "https://avatars.githubusercontent.com/u/49302558?v=4", + "profile": "https://github.com/Marikattt", + "contributions": [ + "code" + ] + }, + { + "login": "Harsh4902", + "name": "Hashvardhan Parmar", + "avatar_url": "https://avatars.githubusercontent.com/u/84663071?v=4", + "profile": "https://github.com/Harsh4902", + "contributions": [ + "translation" + ] + }, + { + "login": "yongyongkr", + "name": "YongHwan", + "avatar_url": "https://avatars.githubusercontent.com/u/67625677?v=4", + "profile": "https://hwan33.tistory.com/", + "contributions": [ + "doc", + "translation" + ] + }, + { + "login": "shogohida", + "name": "Shogo Hida", + "avatar_url": "https://avatars.githubusercontent.com/u/10365357?v=4", + "profile": "https://github.com/shogohida", + "contributions": [ + "translation" + ] + }, + { + "login": "Regyl", + "name": "Eugene", + "avatar_url": "https://avatars.githubusercontent.com/u/48804404?v=4", + "profile": "https://github.com/Regyl", + "contributions": [ + "code" + ] + }, + { + "login": "piyush280599", + "name": "Piyush", + "avatar_url": "https://avatars.githubusercontent.com/u/118425491?v=4", + "profile": "https://github.com/piyush280599", + "contributions": [ + "doc" + ] + }, + { + "login": "rahul-raj", + "name": "Rahul Raj", + "avatar_url": "https://avatars.githubusercontent.com/u/517415?v=4", + "profile": "https://www.linkedin.com/in/rahulraj90/", + "contributions": [ + "code" + ] + }, + { + "login": "bharathkalyans", + "name": "Bharath Kalyan S", + "avatar_url": "https://avatars.githubusercontent.com/u/49526472?v=4", + "profile": "https://www.linkedin.com/in/bharathkalyans/", + "contributions": [ + "code" + ] + }, + { + "login": "saiteja55", + "name": "Saiteja Reddy", + "avatar_url": "https://avatars.githubusercontent.com/u/13088886?v=4", + "profile": "https://www.linkedin.com/in/thisissaiteja/", + "contributions": [ + "translation" + ] + }, + { + "login": "TheClerici", + "name": "Enrique Clerici", + "avatar_url": "https://avatars.githubusercontent.com/u/115318468?v=4", + "profile": "http://twitch.tv/clerici", + "contributions": [ + "translation" + ] + }, + { + "login": "ramilS", + "name": "Ramil Sayetov", + "avatar_url": "https://avatars.githubusercontent.com/u/13589365?v=4", + "profile": "https://github.com/ramilS", + "contributions": [ + "translation" + ] + }, + { + "login": "pikapiu", + "name": "东方未白", + "avatar_url": "https://avatars.githubusercontent.com/u/50656114?v=4", + "profile": "https://pkq.xyz", + "contributions": [ + "code" + ] + }, + { + "login": "swashb0ckler", + "name": "Fredrik Sejr", + "avatar_url": "https://avatars.githubusercontent.com/u/62488841?v=4", + "profile": "https://github.com/swashb0ckler", + "contributions": [ + "translation" + ] + }, + { + "login": "akshatarora0013", + "name": "akshatarora0013", + "avatar_url": "https://avatars.githubusercontent.com/u/102645021?v=4", + "profile": "https://github.com/akshatarora0013", + "contributions": [ + "code" + ] + }, + { + "login": "MugheesQasim", + "name": "Mughees Qasim", + "avatar_url": "https://avatars.githubusercontent.com/u/45170085?v=4", + "profile": "https://mugheesqasimmq.wixsite.com/portfolio-website", + "contributions": [ + "code" + ] + }, + { + "login": "behappyleee", + "name": "behappyleee", + "avatar_url": "https://avatars.githubusercontent.com/u/72903623?v=4", + "profile": "https://github.com/behappyleee", + "contributions": [ + "translation" + ] + }, + { + "login": "Ayush-Thakur-geek", + "name": "Ayush Thakur", + "avatar_url": "https://avatars.githubusercontent.com/u/116510022?v=4", + "profile": "https://github.com/Ayush-Thakur-geek", + "contributions": [ + "translation" + ] + }, + { + "login": "boscha1", + "name": "Anthony Bosch", + "avatar_url": "https://avatars.githubusercontent.com/u/55814237?v=4", + "profile": "https://github.com/boscha1", + "contributions": [ + "code" + ] + }, + { + "login": "AnsonTran", + "name": "trananso", + "avatar_url": "https://avatars.githubusercontent.com/u/37683428?v=4", + "profile": "https://github.com/AnsonTran", + "contributions": [ + "doc" + ] + }, + { + "login": "beef-e", + "name": "Giammaria Biffi", + "avatar_url": "https://avatars.githubusercontent.com/u/102854627?v=4", + "profile": "https://github.com/beef-e", + "contributions": [ + "translation" + ] + }, + { + "login": "saif7159", + "name": "Saiful Haque", + "avatar_url": "https://avatars.githubusercontent.com/u/36008396?v=4", + "profile": "https://github.com/saif7159", + "contributions": [ + "code" + ] + }, + { + "login": "JabezBrew", + "name": "JabezBrew", + "avatar_url": "https://avatars.githubusercontent.com/u/74483609?v=4", + "profile": "https://github.com/JabezBrew", + "contributions": [ + "code" + ] + }, + { + "login": "konstantin-goldman", + "name": "konstantin-goldman", + "avatar_url": "https://avatars.githubusercontent.com/u/47669472?v=4", + "profile": "https://github.com/konstantin-goldman", + "contributions": [ + "doc" + ] + }, + { + "login": "tiennm99", + "name": "Tien Nguyen Minh", + "avatar_url": "https://avatars.githubusercontent.com/u/39063457?v=4", + "profile": "https://github.com/tiennm99", + "contributions": [ + "code", + "translation" + ] + }, + { + "login": "VladimirCreator", + "name": "Vladimir", + "avatar_url": "https://avatars.githubusercontent.com/u/49140851?v=4", + "profile": "https://github.com/VladimirCreator", + "contributions": [ + "translation" + ] + }, + { + "login": "surjendu104", + "name": "Surjendu", + "avatar_url": "https://avatars.githubusercontent.com/u/101238933?v=4", + "profile": "https://surjendu-pal.netlify.app/", + "contributions": [ + "translation", + "code" + ] + }, + { + "login": "bakazhou", + "name": "bakazhou", + "avatar_url": "https://avatars.githubusercontent.com/u/81795984?v=4", + "profile": "https://github.com/bakazhou", + "contributions": [ + "code" + ] + }, + { + "login": "Owen-CH-Leung", + "name": "Owen Leung", + "avatar_url": "https://avatars.githubusercontent.com/u/43698890?v=4", + "profile": "https://github.com/Owen-CH-Leung", + "contributions": [ + "code" + ] + }, + { + "login": "thestbar", + "name": "Stavros Barousis", + "avatar_url": "https://avatars.githubusercontent.com/u/20283468?v=4", + "profile": "https://github.com/thestbar", + "contributions": [ + "doc" + ] + }, + { + "login": "ibrahim89", + "name": "Syyed Ibrahim Abdullah", + "avatar_url": "https://avatars.githubusercontent.com/u/20753671?v=4", + "profile": "https://github.com/ibrahim89", + "contributions": [ + "translation" + ] + }, + { + "login": "JanisZhang", + "name": "JiaDi Zhang", + "avatar_url": "https://avatars.githubusercontent.com/u/95570096?v=4", + "profile": "https://github.com/JanisZhang", + "contributions": [ + "translation" + ] + }, + { + "login": "sanchitbansal10", + "name": "Sanchit Bansal", + "avatar_url": "https://avatars.githubusercontent.com/u/16536741?v=4", + "profile": "https://github.com/sanchitbansal10", + "contributions": [ + "doc" + ] + }, + { + "login": "mm-saiful6854", + "name": "Md Saiful Islam", + "avatar_url": "https://avatars.githubusercontent.com/u/48361160?v=4", + "profile": "https://github.com/mm-saiful6854", + "contributions": [ + "doc" + ] + }, + { + "login": "AddeusExMachina", + "name": "Antonio Addeo", + "avatar_url": "https://avatars.githubusercontent.com/u/39912670?v=4", + "profile": "https://github.com/AddeusExMachina", + "contributions": [ + "doc", + "code" + ] + }, + { + "login": "Upendra-Allagadda", + "name": "Allagadda Sai Upendranath", + "avatar_url": "https://avatars.githubusercontent.com/u/25962010?v=4", + "profile": "https://github.com/Upendra-Allagadda", + "contributions": [ + "doc" + ] + }, + { + "login": "mathbraga", + "name": "Matheus Braga", + "avatar_url": "https://avatars.githubusercontent.com/u/31048764?v=4", + "profile": "https://www.linkedin.com/in/mobraga/", + "contributions": [ + "translation", + "doc" + ] + }, + { + "login": "satyabarghav", + "name": "Appari Satya Barghav", + "avatar_url": "https://avatars.githubusercontent.com/u/36763910?v=4", + "profile": "https://github.com/satyabarghav", + "contributions": [ + "doc" + ] + }, + { + "login": "mribeirodantas", + "name": "Marcel Ribeiro-Dantas", + "avatar_url": "https://avatars.githubusercontent.com/u/1023197?v=4", + "profile": "http://mribeirodantas.me", + "contributions": [ + "doc" + ] + }, + { + "login": "hamexhanif", + "name": "Muhammad Hanif Amrullah", + "avatar_url": "https://avatars.githubusercontent.com/u/74542852?v=4", + "profile": "https://github.com/hamexhanif", + "contributions": [ + "translation" + ] + }, + { + "login": "JackH408", + "name": "JackH408", + "avatar_url": "https://avatars.githubusercontent.com/u/141727294?v=4", + "profile": "https://github.com/JackH408", + "contributions": [ + "doc" + ] + }, + { + "login": "versus2004", + "name": "Shubham", + "avatar_url": "https://avatars.githubusercontent.com/u/132815243?v=4", + "profile": "https://github.com/versus2004", + "contributions": [ + "translation" + ] + }, + { + "login": "inishantjain", + "name": "Nishant Jain", + "avatar_url": "https://avatars.githubusercontent.com/u/121454072?v=4", + "profile": "https://github.com/inishantjain", + "contributions": [ + "doc" + ] + }, + { + "login": "hallowshaw", + "name": "Rhitam Chaudhury", + "avatar_url": "https://avatars.githubusercontent.com/u/90751158?v=4", + "profile": "https://github.com/hallowshaw", + "contributions": [ + "doc" + ] + }, + { + "login": "JerryZhao275", + "name": "JerryZhao275", + "avatar_url": "https://avatars.githubusercontent.com/u/132061401?v=4", + "profile": "https://github.com/JerryZhao275", + "contributions": [ + "doc" + ] + }, + { + "login": "leonardol", + "name": "Leonardo Lisanti", + "avatar_url": "https://avatars.githubusercontent.com/u/1445890?v=4", + "profile": "https://twitter.com/llisant", + "contributions": [ + "translation" + ] + }, + { + "login": "Yenniferh", + "name": "Yennifer Herrera", + "avatar_url": "https://avatars.githubusercontent.com/u/19285706?v=4", + "profile": "http://www.linkedin.com/in/yenniferh", + "contributions": [ + "translation", + "review" + ] + }, + { + "login": "jnniu-n", + "name": "jnniu-n", + "avatar_url": "https://avatars.githubusercontent.com/u/141746282?v=4", + "profile": "https://github.com/jnniu-n", + "contributions": [ + "translation", + "doc" + ] + }, + { + "login": "miguel-is-coding", + "name": "Miguel Angel Perez Garcia", + "avatar_url": "https://avatars.githubusercontent.com/u/48435117?v=4", + "profile": "https://github.com/miguel-is-coding", + "contributions": [ + "review", + "translation" + ] + }, + { + "login": "SuwanSankaja", + "name": "Suwan Sankaja", + "avatar_url": "https://avatars.githubusercontent.com/u/86839778?v=4", + "profile": "https://github.com/SuwanSankaja", + "contributions": [ + "translation" + ] + }, + { + "login": "Iamalok007", + "name": "alok", + "avatar_url": "https://avatars.githubusercontent.com/u/97467835?v=4", + "profile": "https://github.com/Iamalok007", + "contributions": [ + "doc" + ] + }, + { + "login": "dlvideira", + "name": "Daniel Lisboa", + "avatar_url": "https://avatars.githubusercontent.com/u/53951425?v=4", + "profile": "https://github.com/dlvideira", + "contributions": [ + "translation" + ] + }, + { + "login": "ComplexOW", + "name": "Sam Powell", + "avatar_url": "https://avatars.githubusercontent.com/u/105279107?v=4", + "profile": "https://github.com/ComplexOW", + "contributions": [ + "doc" + ] + }, + { + "login": "jppf22", + "name": "João Fernandes", + "avatar_url": "https://avatars.githubusercontent.com/u/104360594?v=4", + "profile": "https://github.com/jppf22", + "contributions": [ + "translation" + ] + }, + { + "login": "HongGeonUi", + "name": "Hong Geon-ui", + "avatar_url": "https://avatars.githubusercontent.com/u/89684956?v=4", + "profile": "https://github.com/HongGeonUi", + "contributions": [ + "translation" + ] + }, + { + "login": "ylcn91", + "name": "Doksanbir", + "avatar_url": "https://avatars.githubusercontent.com/u/7249450?v=4", + "profile": "https://github.com/ylcn91", + "contributions": [ + "code", + "doc", + "review" + ] + }, + { + "login": "Chant3ll3", + "name": "Chant3ll3", + "avatar_url": "https://avatars.githubusercontent.com/u/141697333?v=4", + "profile": "https://github.com/Chant3ll3", + "contributions": [ + "doc", + "translation" + ] + }, + { + "login": "hwan33", + "name": "YongHwan Kwon", + "avatar_url": "https://avatars.githubusercontent.com/u/67625677?v=4", + "profile": "https://hwan33.tistory.com/", + "contributions": [ + "code" + ] + }, + { + "login": "takikuba", + "name": "Jakub Klimek", + "avatar_url": "https://avatars.githubusercontent.com/u/58841343?v=4", + "profile": "https://github.com/takikuba", + "contributions": [ + "code" + ] + }, + { + "login": "bachbil", + "name": "believe", + "avatar_url": "https://avatars.githubusercontent.com/u/28935461?v=4", + "profile": "https://github.com/bachbil", + "contributions": [ + "translation" + ] + }, + { + "login": "egg0102030405", + "name": "egg0102030405", + "avatar_url": "https://avatars.githubusercontent.com/u/59650695?v=4", + "profile": "https://github.com/egg0102030405", + "contributions": [ + "translation", + "doc" + ] + }, + { + "login": "ved-asole", + "name": "Ved Asole", + "avatar_url": "https://avatars.githubusercontent.com/u/77259804?v=4", + "profile": "http://vedasole.cloud", + "contributions": [ + "code" + ] + }, + { + "login": "Holiday-C", + "name": "NewMorning", + "avatar_url": "https://avatars.githubusercontent.com/u/95869761?v=4", + "profile": "https://github.com/Holiday-C", + "contributions": [ + "translation" + ] + }, + { + "login": "Kiro-Young", + "name": "资深老萌新", + "avatar_url": "https://avatars.githubusercontent.com/u/98251397?v=4", + "profile": "https://github.com/Kiro-Young", + "contributions": [ + "translation" + ] + }, + { + "login": "Nickolodeon98", + "name": "Seunghwan Jeon", + "avatar_url": "https://avatars.githubusercontent.com/u/113348293?v=4", + "profile": "https://itistori.tistory.com/", + "contributions": [ + "translation" + ] + }, + { + "login": "sugan0tech", + "name": "sugavanesh", + "avatar_url": "https://avatars.githubusercontent.com/u/71312159?v=4", + "profile": "https://github.com/sugan0tech", + "contributions": [ + "code" + ] + }, + { + "login": "FinnS-F", + "name": "FinnS-F", + "avatar_url": "https://avatars.githubusercontent.com/u/126026830?v=4", + "profile": "https://github.com/FinnS-F", + "contributions": [ + "code" + ] + }, + { + "login": "jerryyummy", + "name": "jerryyummy", + "avatar_url": "https://avatars.githubusercontent.com/u/62087610?v=4", + "profile": "https://github.com/jerryyummy", + "contributions": [ + "translation" + ] + }, + { + "login": "Manojkumarchow", + "name": "Manoj Chowdary", + "avatar_url": "https://avatars.githubusercontent.com/u/28005510?v=4", + "profile": "https://manojkumarchow.github.io/", + "contributions": [ + "code" + ] + }, + { + "login": "MaverickWingman", + "name": "Aditya", + "avatar_url": "https://avatars.githubusercontent.com/u/76624290?v=4", + "profile": "https://github.com/MaverickWingman", + "contributions": [ + "doc", + "code" + ] + }, + { + "login": "nooynayr", + "name": "nooynayr", + "avatar_url": "https://avatars.githubusercontent.com/u/141696269?v=4", + "profile": "https://github.com/nooynayr", + "contributions": [ + "doc" + ] + }, + { + "login": "pushpander1010", + "name": "CYBERCRUX2", + "avatar_url": "https://avatars.githubusercontent.com/u/41006191?v=4", + "profile": "https://github.com/pushpander1010", + "contributions": [ + "doc" + ] + }, + { + "login": "luismateoh", + "name": "Luis Mateo Hincapié Martinez", + "avatar_url": "https://avatars.githubusercontent.com/u/44934142?v=4", + "profile": "https://github.com/luismateoh", + "contributions": [ + "translation", + "review" + ] + }, + { + "login": "guqing", + "name": "guqing", + "avatar_url": "https://avatars.githubusercontent.com/u/38999863?v=4", + "profile": "https://guqing.io", + "contributions": [ + "code" + ] + }, + { + "login": "sashirestela", + "name": "Sashir Estela", + "avatar_url": "https://avatars.githubusercontent.com/u/14045506?v=4", + "profile": "https://github.com/sashirestela", + "contributions": [ + "code" + ] + }, + { + "login": "omahs", + "name": "omahs", + "avatar_url": "https://avatars.githubusercontent.com/u/73983677?v=4", + "profile": "https://github.com/omahs", + "contributions": [ + "doc" + ] + }, + { + "login": "leiferksn", + "name": "leif e.", + "avatar_url": "https://avatars.githubusercontent.com/u/4026636?v=4", + "profile": "https://github.com/leiferksn", + "contributions": [ + "code" + ] + }, + { + "login": "junhkang", + "name": "Jun Kang", + "avatar_url": "https://avatars.githubusercontent.com/u/20232155?v=4", + "profile": "https://junhkang.tistory.com/", + "contributions": [ + "code" + ] + }, + { + "login": "KishalayP", + "name": "Kishalay Pandey", + "avatar_url": "https://avatars.githubusercontent.com/u/71012321?v=4", + "profile": "https://github.com/KishalayP", + "contributions": [ + "code" + ] + }, + { + "login": "drishtii7", + "name": "drishtii7", + "avatar_url": "https://avatars.githubusercontent.com/u/82076566?v=4", + "profile": "https://github.com/drishtii7", + "contributions": [ + "code" + ] + }, + { + "login": "DavidMedinaO", + "name": "David Medina Orozco", + "avatar_url": "https://avatars.githubusercontent.com/u/53974843?v=4", + "profile": "https://github.com/DavidMedinaO", + "contributions": [ + "translation", + "review" + ] + }, + { + "login": "Romo4ka-bot", + "name": "Roman Leontev", + "avatar_url": "https://avatars.githubusercontent.com/u/61774094?v=4", + "profile": "https://github.com/Romo4ka-bot", + "contributions": [ + "code" + ] + }, + { + "login": "Ehspresso", + "name": "Riley", + "avatar_url": "https://avatars.githubusercontent.com/u/144370752?v=4", + "profile": "https://github.com/Ehspresso", + "contributions": [ + "code" + ] + }, + { + "login": "k1w1dev", + "name": "k1w1dev", + "avatar_url": "https://avatars.githubusercontent.com/u/121696782?v=4", + "profile": "https://github.com/k1w1dev", + "contributions": [ + "code" + ] + }, + { + "login": "dev-yugantar", + "name": "dev-yugantar", + "avatar_url": "https://avatars.githubusercontent.com/u/153066190?v=4", + "profile": "https://github.com/dev-yugantar", + "contributions": [ + "code" + ] + }, + { + "login": "Adelechka", + "name": "Adelya", + "avatar_url": "https://avatars.githubusercontent.com/u/65678470?v=4", + "profile": "https://github.com/Adelechka", + "contributions": [ + "code" + ] + }, + { + "login": "gatlanagaprasanna", + "name": "gatlanagaprasanna", + "avatar_url": "https://avatars.githubusercontent.com/u/154739216?v=4", + "profile": "https://github.com/gatlanagaprasanna", + "contributions": [ + "doc" + ] + }, + { + "login": "Avinash2110", + "name": "Avinash Shukla", + "avatar_url": "https://avatars.githubusercontent.com/u/37360069?v=4", + "profile": "https://github.com/Avinash2110", + "contributions": [ + "code" + ] + }, + { + "login": "Mayankchoudhary294", + "name": "Mayank Choudhary", + "avatar_url": "https://avatars.githubusercontent.com/u/97609699?v=4", + "profile": "https://github.com/Mayankchoudhary294", + "contributions": [ + "code" + ] + }, + { + "login": "romannimets", + "name": "romannimets", + "avatar_url": "https://avatars.githubusercontent.com/u/137268574?v=4", + "profile": "https://github.com/romannimets", + "contributions": [ + "code" + ] + }, + { + "login": "Joel-Dandin", + "name": "Joel", + "avatar_url": "https://avatars.githubusercontent.com/u/60149879?v=4", + "profile": "https://github.com/Joel-Dandin", + "contributions": [ + "code" + ] + }, + { + "login": "244Walyson", + "name": "Walyson Moises", + "avatar_url": "https://avatars.githubusercontent.com/u/125759796?v=4", + "profile": "https://github.com/244Walyson", + "contributions": [ + "code" + ] + }, + { + "login": "Xcyq", + "name": "Xcyq", + "avatar_url": "https://avatars.githubusercontent.com/u/39086666?v=4", + "profile": "https://github.com/Xcyq", + "contributions": [ + "code" + ] + }, + { + "login": "Ritabrata1080", + "name": "Ritabrata", + "avatar_url": "https://avatars.githubusercontent.com/u/60834250?v=4", + "profile": "https://github.com/Ritabrata1080", + "contributions": [ + "review" + ] + }, + { + "login": "trivikr", + "name": "Trivikram Kamat", + "avatar_url": "https://avatars.githubusercontent.com/u/16024985?v=4", + "profile": "https://github.com/trivikr", + "contributions": [ + "code" + ] + }, + { + "login": "vvanghelle", + "name": "Vincent Vanghelle", + "avatar_url": "https://avatars.githubusercontent.com/u/3204600?v=4", + "profile": "https://github.com/vvanghelle", + "contributions": [ + "translation" + ] + }, + { + "login": "antoheri", + "name": "Antoine Héritier", + "avatar_url": "https://avatars.githubusercontent.com/u/79988396?v=4", + "profile": "https://github.com/antoheri", + "contributions": [ + "translation" + ] + }, + { + "login": "fishandsheep", + "name": "QinShower", + "avatar_url": "https://avatars.githubusercontent.com/u/43347407?v=4", + "profile": "https://github.com/fishandsheep", + "contributions": [ + "translation" + ] + }, + { + "login": "LakshyaPunyani-01", + "name": "LakshyaPunyani-01", + "avatar_url": "https://avatars.githubusercontent.com/u/103628913?v=4", + "profile": "https://github.com/LakshyaPunyani-01", + "contributions": [ + "code" + ] + }, + { + "login": "jasonjyu", + "name": "jasonjyu", + "avatar_url": "https://avatars.githubusercontent.com/u/10333076?v=4", + "profile": "https://github.com/jasonjyu", + "contributions": [ + "code" + ] + }, + { + "login": "jeffmorrison", + "name": "jeffmorrison", + "avatar_url": "https://avatars.githubusercontent.com/u/26047158?v=4", + "profile": "https://github.com/jeffmorrison", + "contributions": [ + "code" + ] + }, + { + "login": "dmgodoy", + "name": "David M.", + "avatar_url": "https://avatars.githubusercontent.com/u/10840681?v=4", + "profile": "https://github.com/dmgodoy", + "contributions": [ + "code" + ] + }, + { + "login": "apophizzz", + "name": "Patrick Kleindienst", + "avatar_url": "https://avatars.githubusercontent.com/u/12052783?v=4", + "profile": "https://github.com/apophizzz", + "contributions": [ + "code" + ] + }, + { + "login": "proceane", + "name": "Juyeon", + "avatar_url": "https://avatars.githubusercontent.com/u/62143949?v=4", + "profile": "https://github.com/proceane", + "contributions": [ + "translation" + ] + }, + { + "login": "mammadyahyayev", + "name": "Mammad Yahyayev", + "avatar_url": "https://avatars.githubusercontent.com/u/66476643?v=4", + "profile": "https://mammadyahya.vercel.app", + "contributions": [ + "doc" + ] + }, + { + "login": "SalmaAzeem", + "name": "Salma", + "avatar_url": "https://avatars.githubusercontent.com/u/121863224?v=4", + "profile": "https://github.com/SalmaAzeem", + "contributions": [ + "code" + ] + }, + { + "login": "CodeMaverick-143", + "name": "Arpit Sarang", + "avatar_url": "https://avatars.githubusercontent.com/u/182847716?v=4", + "profile": "https://codemaverick-143.github.io/My-Portfolio/", + "contributions": [ + "code" + ] + }, + { + "login": "mayatarek", + "name": "Maya", + "avatar_url": "https://avatars.githubusercontent.com/u/111644421?v=4", + "profile": "https://github.com/mayatarek", + "contributions": [ + "translation" + ] + }, + { + "login": "HabibaMekay", + "name": "HabibaMekay", + "avatar_url": "https://avatars.githubusercontent.com/u/133516736?v=4", + "profile": "https://github.com/HabibaMekay", + "contributions": [ + "code" + ] + }, + { + "login": "Ahmed-Taha-981", + "name": "Ahmed-Taha-981", + "avatar_url": "https://avatars.githubusercontent.com/u/122402269?v=4", + "profile": "https://github.com/Ahmed-Taha-981", + "contributions": [ + "code" + ] + }, + { + "login": "malak-elbanna", + "name": "Malak Elbanna", + "avatar_url": "https://avatars.githubusercontent.com/u/67643605?v=4", + "profile": "https://malakelbanna.netlify.app/", + "contributions": [ + "code" + ] + }, + { + "login": "depthlending", + "name": "BiKangNing", + "avatar_url": "https://avatars.githubusercontent.com/u/164312726?v=4", + "profile": "https://github.com/depthlending", + "contributions": [ + "doc" + ] + }, + { + "login": "TarunVishwakarma1", + "name": "Tarun Vishwakarma", + "avatar_url": "https://avatars.githubusercontent.com/u/138651451?v=4", + "profile": "https://github.com/TarunVishwakarma1", + "contributions": [ + "code" + ] + }, + { + "login": "shahdhoss", + "name": "Shahd Hossam", + "avatar_url": "https://avatars.githubusercontent.com/u/132148556?v=4", + "profile": "https://github.com/shahdhoss", + "contributions": [ + "code" + ] + }, + { + "login": "mehdirahimi", + "name": "Mehdi Rahimi", + "avatar_url": "https://avatars.githubusercontent.com/u/24210842?v=4", + "profile": "https://mehdirahimi.github.io", + "contributions": [ + "code" + ] + }, + { + "login": "clintaire", + "name": "Clint Airé", + "avatar_url": "https://avatars.githubusercontent.com/u/111376518?v=4", + "profile": "https://github.com/clintaire", + "contributions": [ + "code" + ] + }, + { + "login": "darkhyper24", + "name": "darkhyper24", + "avatar_url": "https://avatars.githubusercontent.com/u/132711528?v=4", + "profile": "https://github.com/darkhyper24", + "contributions": [ + "code" + ] + }, + { + "login": "MohanedAtef238", + "name": "Mohaned Atef", + "avatar_url": "https://avatars.githubusercontent.com/u/105852138?v=4", + "profile": "https://github.com/MohanedAtef238", + "contributions": [ + "code" + ] + }, + { + "login": "maximevtush", + "name": "Maxim Evtush", + "avatar_url": "https://avatars.githubusercontent.com/u/154841002?v=4", + "profile": "https://github.com/maximevtush", + "contributions": [ + "code" + ] + }, + { + "login": "hvgh88", + "name": "Harshita Vidapanakal", + "avatar_url": "https://avatars.githubusercontent.com/u/65297242?v=4", + "profile": "https://github.com/hvgh88", + "contributions": [ + "code" + ] + }, + { + "login": "smile-ab", + "name": "smile-ab", + "avatar_url": "https://avatars.githubusercontent.com/u/202159894?v=4", + "profile": "https://github.com/smile-ab", + "contributions": [ + "translation", + "code" + ] + }, + { + "login": "Francisco-G-P", + "name": "Francisco-G-P", + "avatar_url": "https://avatars.githubusercontent.com/u/186766789?v=4", + "profile": "https://github.com/Francisco-G-P", + "contributions": [ + "translation" + ] + }, + { + "login": "Duartegdm", + "name": "Gabriel Duarte", + "avatar_url": "https://avatars.githubusercontent.com/u/137895372?v=4", + "profile": "https://github.com/Duartegdm", + "contributions": [ + "doc" + ] + }, + { + "login": "DenizAltunkapan", + "name": "Deniz Altunkapan", + "avatar_url": "https://avatars.githubusercontent.com/u/93663085?v=4", + "profile": "https://github.com/DenizAltunkapan", + "contributions": [ + "translation" + ] + }, + { + "login": "johnklint81", + "name": "John Klint", + "avatar_url": "https://avatars.githubusercontent.com/u/70539458?v=4", + "profile": "https://github.com/johnklint81", + "contributions": [ + "code" + ] + }, + { + "login": "sanurah", + "name": "Sanura Hettiarachchi", + "avatar_url": "https://avatars.githubusercontent.com/u/16178588?v=4", + "profile": "https://github.com/sanurah", + "contributions": [ + "code" + ] + }, + { + "login": "2897robo", + "name": "Kim Gi Uk", + "avatar_url": "https://avatars.githubusercontent.com/u/31699375?v=4", + "profile": "https://github.com/2897robo", + "contributions": [ + "code" + ] + }, + { + "login": "Suchismita-Deb", + "name": "Suchismita Deb", + "avatar_url": "https://avatars.githubusercontent.com/u/68535074?v=4", + "profile": "https://github.com/Suchismita-Deb", + "contributions": [ + "code" + ] + }, + { + "login": "ssrijan-007-sys", + "name": "ssrijan-007-sys", + "avatar_url": "https://avatars.githubusercontent.com/u/137605821?v=4", + "profile": "https://github.com/ssrijan-007-sys", + "contributions": [ + "code" + ] + }, + { + "login": "e5LA", + "name": "e5LA", + "avatar_url": "https://avatars.githubusercontent.com/u/208197507?v=4", + "profile": "https://github.com/e5LA", + "contributions": [ + "code", + "doc" + ] + }, + { + "login": "maziyar-gerami", + "name": "Maziyar Gerami", + "avatar_url": "https://avatars.githubusercontent.com/u/122622721?v=4", + "profile": "http://maziyar-gerami.github.io/portfolio/", + "contributions": [ + "translation" + ] + }, + { + "login": "yybmion", + "name": "yoobin_mion", + "avatar_url": "https://avatars.githubusercontent.com/u/113106136?v=4", + "profile": "https://github.com/yybmion", + "contributions": [ + "code" + ] + } + ], + "contributorsPerLine": 6, + "projectName": "java-design-patterns", + "projectOwner": "iluwatar", + "repoType": "github", + "repoHost": "https://github.com", + "skipCi": true, + "commitConvention": "angular", + "commitType": "docs" +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000000..4afde59eb070 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,366 @@ +# +# This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). +# +# The MIT License +# Copyright © 2014-2022 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. +# + +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = false +max_line_length = off +tab_width = 4 +ij_continuation_indent_size = 8 +ij_formatter_off_tag = @formatter:off +ij_formatter_on_tag = @formatter:on +ij_formatter_tags_enabled = true +ij_smart_tabs = false +ij_visual_guides = +ij_wrap_on_typing = false + +[*.java] +indent_size = 2 +max_line_length = 100 +ij_continuation_indent_size = 4 +ij_java_align_consecutive_assignments = false +ij_java_align_consecutive_variable_declarations = false +ij_java_align_group_field_declarations = false +ij_java_align_multiline_annotation_parameters = false +ij_java_align_multiline_array_initializer_expression = false +ij_java_align_multiline_assignment = false +ij_java_align_multiline_binary_operation = false +ij_java_align_multiline_chained_methods = false +ij_java_align_multiline_deconstruction_list_components = true +ij_java_align_multiline_extends_list = false +ij_java_align_multiline_for = true +ij_java_align_multiline_method_parentheses = false +ij_java_align_multiline_parameters = true +ij_java_align_multiline_parameters_in_calls = false +ij_java_align_multiline_parenthesized_expression = false +ij_java_align_multiline_records = true +ij_java_align_multiline_resources = true +ij_java_align_multiline_ternary_operation = false +ij_java_align_multiline_text_blocks = false +ij_java_align_multiline_throws_list = false +ij_java_align_subsequent_simple_methods = false +ij_java_align_throws_keyword = false +ij_java_align_types_in_multi_catch = true +ij_java_annotation_parameter_wrap = off +ij_java_array_initializer_new_line_after_left_brace = false +ij_java_array_initializer_right_brace_on_new_line = false +ij_java_array_initializer_wrap = normal +ij_java_assert_statement_colon_on_next_line = false +ij_java_assert_statement_wrap = normal +ij_java_assignment_wrap = normal +ij_java_binary_operation_sign_on_next_line = false +ij_java_binary_operation_wrap = normal +ij_java_blank_lines_after_anonymous_class_header = 0 +ij_java_blank_lines_after_class_header = 0 +ij_java_blank_lines_after_imports = 1 +ij_java_blank_lines_after_package = 1 +ij_java_blank_lines_around_class = 1 +ij_java_blank_lines_around_field = 0 +ij_java_blank_lines_around_field_in_interface = 0 +ij_java_blank_lines_around_initializer = 1 +ij_java_blank_lines_around_method = 1 +ij_java_blank_lines_around_method_in_interface = 1 +ij_java_blank_lines_before_class_end = 0 +ij_java_blank_lines_before_imports = 1 +ij_java_blank_lines_before_method_body = 0 +ij_java_blank_lines_before_package = 1 +ij_java_block_brace_style = end_of_line +ij_java_block_comment_add_space = false +ij_java_block_comment_at_first_column = true +ij_java_builder_methods = +ij_java_call_parameters_new_line_after_left_paren = false +ij_java_call_parameters_right_paren_on_new_line = false +ij_java_call_parameters_wrap = normal +ij_java_case_statement_on_separate_line = true +ij_java_catch_on_new_line = false +ij_java_class_annotation_wrap = split_into_lines +ij_java_class_brace_style = end_of_line +ij_java_class_count_to_use_import_on_demand = 999 +ij_java_class_names_in_javadoc = 1 +ij_java_deconstruction_list_wrap = normal +ij_java_do_not_indent_top_level_class_members = false +ij_java_do_not_wrap_after_single_annotation = false +ij_java_do_not_wrap_after_single_annotation_in_parameter = false +ij_java_do_while_brace_force = always +ij_java_doc_add_blank_line_after_description = true +ij_java_doc_add_blank_line_after_param_comments = false +ij_java_doc_add_blank_line_after_return = false +ij_java_doc_add_p_tag_on_empty_lines = true +ij_java_doc_align_exception_comments = true +ij_java_doc_align_param_comments = true +ij_java_doc_do_not_wrap_if_one_line = false +ij_java_doc_enable_formatting = true +ij_java_doc_enable_leading_asterisks = true +ij_java_doc_indent_on_continuation = false +ij_java_doc_keep_empty_lines = true +ij_java_doc_keep_empty_parameter_tag = true +ij_java_doc_keep_empty_return_tag = true +ij_java_doc_keep_empty_throws_tag = true +ij_java_doc_keep_invalid_tags = true +ij_java_doc_param_description_on_new_line = false +ij_java_doc_preserve_line_breaks = false +ij_java_doc_use_throws_not_exception_tag = true +ij_java_else_on_new_line = false +ij_java_entity_dd_prefix = +ij_java_entity_dd_suffix = EJB +ij_java_entity_eb_prefix = +ij_java_entity_eb_suffix = Bean +ij_java_entity_hi_prefix = +ij_java_entity_hi_suffix = Home +ij_java_entity_lhi_prefix = Local +ij_java_entity_lhi_suffix = Home +ij_java_entity_li_prefix = Local +ij_java_entity_li_suffix = +ij_java_entity_pk_class = java.lang.String +ij_java_entity_ri_prefix = +ij_java_entity_ri_suffix = +ij_java_entity_vo_prefix = +ij_java_entity_vo_suffix = VO +ij_java_enum_constants_wrap = normal +ij_java_extends_keyword_wrap = normal +ij_java_extends_list_wrap = normal +ij_java_field_annotation_wrap = split_into_lines +ij_java_field_name_prefix = +ij_java_field_name_suffix = +ij_java_filter_class_prefix = +ij_java_filter_class_suffix = +ij_java_filter_dd_prefix = +ij_java_filter_dd_suffix = +ij_java_finally_on_new_line = false +ij_java_for_brace_force = always +ij_java_for_statement_new_line_after_left_paren = false +ij_java_for_statement_right_paren_on_new_line = false +ij_java_for_statement_wrap = normal +ij_java_generate_final_locals = false +ij_java_generate_final_parameters = false +ij_java_if_brace_force = always +ij_java_imports_layout = $*,|,* +ij_java_indent_case_from_switch = true +ij_java_insert_inner_class_imports = false +ij_java_insert_override_annotation = true +ij_java_keep_blank_lines_before_right_brace = 2 +ij_java_keep_blank_lines_between_package_declaration_and_header = 2 +ij_java_keep_blank_lines_in_code = 2 +ij_java_keep_blank_lines_in_declarations = 2 +ij_java_keep_builder_methods_indents = false +ij_java_keep_control_statement_in_one_line = true +ij_java_keep_first_column_comment = true +ij_java_keep_indents_on_empty_lines = false +ij_java_keep_line_breaks = true +ij_java_keep_multiple_expressions_in_one_line = false +ij_java_keep_simple_blocks_in_one_line = false +ij_java_keep_simple_classes_in_one_line = false +ij_java_keep_simple_lambdas_in_one_line = false +ij_java_keep_simple_methods_in_one_line = false +ij_java_label_indent_absolute = false +ij_java_label_indent_size = 0 +ij_java_lambda_brace_style = end_of_line +ij_java_layout_static_imports_separately = true +ij_java_line_comment_add_space = false +ij_java_line_comment_add_space_on_reformat = false +ij_java_line_comment_at_first_column = true +ij_java_listener_class_prefix = +ij_java_listener_class_suffix = +ij_java_local_variable_name_prefix = +ij_java_local_variable_name_suffix = +ij_java_message_dd_prefix = +ij_java_message_dd_suffix = EJB +ij_java_message_eb_prefix = +ij_java_message_eb_suffix = Bean +ij_java_method_annotation_wrap = split_into_lines +ij_java_method_brace_style = end_of_line +ij_java_method_call_chain_wrap = normal +ij_java_method_parameters_new_line_after_left_paren = false +ij_java_method_parameters_right_paren_on_new_line = false +ij_java_method_parameters_wrap = normal +ij_java_modifier_list_wrap = false +ij_java_multi_catch_types_wrap = normal +ij_java_names_count_to_use_import_on_demand = 999 +ij_java_new_line_after_lparen_in_annotation = false +ij_java_new_line_after_lparen_in_deconstruction_pattern = true +ij_java_new_line_after_lparen_in_record_header = false +ij_java_packages_to_use_import_on_demand = +ij_java_parameter_annotation_wrap = normal +ij_java_parameter_name_prefix = +ij_java_parameter_name_suffix = +ij_java_parentheses_expression_new_line_after_left_paren = false +ij_java_parentheses_expression_right_paren_on_new_line = false +ij_java_place_assignment_sign_on_next_line = false +ij_java_prefer_longer_names = true +ij_java_prefer_parameters_wrap = false +ij_java_record_components_wrap = normal +ij_java_repeat_annotations = +ij_java_repeat_synchronized = true +ij_java_replace_instanceof_and_cast = false +ij_java_replace_null_check = true +ij_java_replace_sum_lambda_with_method_ref = true +ij_java_resource_list_new_line_after_left_paren = false +ij_java_resource_list_right_paren_on_new_line = false +ij_java_resource_list_wrap = normal +ij_java_rparen_on_new_line_in_annotation = false +ij_java_rparen_on_new_line_in_deconstruction_pattern = true +ij_java_rparen_on_new_line_in_record_header = false +ij_java_servlet_class_prefix = +ij_java_servlet_class_suffix = +ij_java_servlet_dd_prefix = +ij_java_servlet_dd_suffix = +ij_java_session_dd_prefix = +ij_java_session_dd_suffix = EJB +ij_java_session_eb_prefix = +ij_java_session_eb_suffix = Bean +ij_java_session_hi_prefix = +ij_java_session_hi_suffix = Home +ij_java_session_lhi_prefix = Local +ij_java_session_lhi_suffix = Home +ij_java_session_li_prefix = Local +ij_java_session_li_suffix = +ij_java_session_ri_prefix = +ij_java_session_ri_suffix = +ij_java_session_si_prefix = +ij_java_session_si_suffix = Service +ij_java_space_after_closing_angle_bracket_in_type_argument = false +ij_java_space_after_colon = true +ij_java_space_after_comma = true +ij_java_space_after_comma_in_type_arguments = true +ij_java_space_after_for_semicolon = true +ij_java_space_after_quest = true +ij_java_space_after_type_cast = true +ij_java_space_before_annotation_array_initializer_left_brace = false +ij_java_space_before_annotation_parameter_list = false +ij_java_space_before_array_initializer_left_brace = true +ij_java_space_before_catch_keyword = true +ij_java_space_before_catch_left_brace = true +ij_java_space_before_catch_parentheses = true +ij_java_space_before_class_left_brace = true +ij_java_space_before_colon = true +ij_java_space_before_colon_in_foreach = true +ij_java_space_before_comma = false +ij_java_space_before_deconstruction_list = false +ij_java_space_before_do_left_brace = true +ij_java_space_before_else_keyword = true +ij_java_space_before_else_left_brace = true +ij_java_space_before_finally_keyword = true +ij_java_space_before_finally_left_brace = true +ij_java_space_before_for_left_brace = true +ij_java_space_before_for_parentheses = true +ij_java_space_before_for_semicolon = false +ij_java_space_before_if_left_brace = true +ij_java_space_before_if_parentheses = true +ij_java_space_before_method_call_parentheses = false +ij_java_space_before_method_left_brace = true +ij_java_space_before_method_parentheses = false +ij_java_space_before_opening_angle_bracket_in_type_parameter = false +ij_java_space_before_quest = true +ij_java_space_before_switch_left_brace = true +ij_java_space_before_switch_parentheses = true +ij_java_space_before_synchronized_left_brace = true +ij_java_space_before_synchronized_parentheses = true +ij_java_space_before_try_left_brace = true +ij_java_space_before_try_parentheses = true +ij_java_space_before_type_parameter_list = false +ij_java_space_before_while_keyword = true +ij_java_space_before_while_left_brace = true +ij_java_space_before_while_parentheses = true +ij_java_space_inside_one_line_enum_braces = false +ij_java_space_within_empty_array_initializer_braces = false +ij_java_space_within_empty_method_call_parentheses = false +ij_java_space_within_empty_method_parentheses = false +ij_java_spaces_around_additive_operators = true +ij_java_spaces_around_annotation_eq = true +ij_java_spaces_around_assignment_operators = true +ij_java_spaces_around_bitwise_operators = true +ij_java_spaces_around_equality_operators = true +ij_java_spaces_around_lambda_arrow = true +ij_java_spaces_around_logical_operators = true +ij_java_spaces_around_method_ref_dbl_colon = false +ij_java_spaces_around_multiplicative_operators = true +ij_java_spaces_around_relational_operators = true +ij_java_spaces_around_shift_operators = true +ij_java_spaces_around_type_bounds_in_type_parameters = true +ij_java_spaces_around_unary_operator = false +ij_java_spaces_within_angle_brackets = false +ij_java_spaces_within_annotation_parentheses = false +ij_java_spaces_within_array_initializer_braces = false +ij_java_spaces_within_braces = false +ij_java_spaces_within_brackets = false +ij_java_spaces_within_cast_parentheses = false +ij_java_spaces_within_catch_parentheses = false +ij_java_spaces_within_deconstruction_list = false +ij_java_spaces_within_for_parentheses = false +ij_java_spaces_within_if_parentheses = false +ij_java_spaces_within_method_call_parentheses = false +ij_java_spaces_within_method_parentheses = false +ij_java_spaces_within_parentheses = false +ij_java_spaces_within_record_header = false +ij_java_spaces_within_switch_parentheses = false +ij_java_spaces_within_synchronized_parentheses = false +ij_java_spaces_within_try_parentheses = false +ij_java_spaces_within_while_parentheses = false +ij_java_special_else_if_treatment = true +ij_java_static_field_name_prefix = +ij_java_static_field_name_suffix = +ij_java_subclass_name_prefix = +ij_java_subclass_name_suffix = Impl +ij_java_ternary_operation_signs_on_next_line = false +ij_java_ternary_operation_wrap = normal +ij_java_test_name_prefix = +ij_java_test_name_suffix = Test +ij_java_throws_keyword_wrap = normal +ij_java_throws_list_wrap = normal +ij_java_use_external_annotations = false +ij_java_use_fq_class_names = false +ij_java_use_relative_indents = false +ij_java_use_single_class_imports = true +ij_java_variable_annotation_wrap = normal +ij_java_visibility = public +ij_java_while_brace_force = always +ij_java_while_on_new_line = false +ij_java_wrap_comments = false +ij_java_wrap_first_method_in_call_chain = false +ij_java_wrap_long_lines = false + +[{*.markdown,*.md}] +ij_markdown_force_one_space_after_blockquote_symbol = true +ij_markdown_force_one_space_after_header_symbol = true +ij_markdown_force_one_space_after_list_bullet = true +ij_markdown_force_one_space_between_words = true +ij_markdown_format_tables = true +ij_markdown_insert_quote_arrows_on_wrap = true +ij_markdown_keep_indents_on_empty_lines = false +ij_markdown_keep_line_breaks_inside_text_blocks = true +ij_markdown_max_line_length = off +ij_markdown_max_lines_around_block_elements = 1 +ij_markdown_max_lines_around_header = 1 +ij_markdown_max_lines_between_paragraphs = 1 +ij_markdown_min_lines_around_block_elements = 1 +ij_markdown_min_lines_around_header = 1 +ij_markdown_min_lines_between_paragraphs = 1 +ij_markdown_wrap_text_if_long = true +ij_markdown_wrap_text_inside_blockquotes = true diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000000..0155bcdcd2b3 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [iluwatar] diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000000..1f63bf5ff8b3 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "maven" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" \ No newline at end of file diff --git a/.github/workflows/maven-ci.yml b/.github/workflows/maven-ci.yml new file mode 100644 index 000000000000..5d2812e72fb7 --- /dev/null +++ b/.github/workflows/maven-ci.yml @@ -0,0 +1,53 @@ +name: Java CI + +on: + push: + branches: [ master ] + +jobs: + + build-and-analyze: + + name: Build and Run Sonar analysis on JDK 21 + runs-on: ubuntu-22.04 + steps: + + - name: Checkout Code + uses: actions/checkout@v4 + with: + # Disabling shallow clone for improving relevancy of SonarQube reporting + fetch-depth: 0 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + cache: 'maven' + + - name: Cache local Maven repository + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + # Cache Sonar packages which are used to run analysis and collect metrics + - name: Cache SonarCloud packages + uses: actions/cache@v4 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + + # Some tests need screen access + - name: Install xvfb + run: sudo apt-get install -y xvfb + + - name: Build with Maven and run SonarQube analysis + run: xvfb-run ./mvnw clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar + env: + # These two env variables are needed for sonar analysis + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/maven-pr-builder.yml b/.github/workflows/maven-pr-builder.yml new file mode 100644 index 000000000000..99ee85152962 --- /dev/null +++ b/.github/workflows/maven-pr-builder.yml @@ -0,0 +1,57 @@ +name: Java PR Builder + +on: + pull_request_target: + branches: [ master ] + types: [ opened, reopened, synchronize ] + +permissions: + contents: read + +jobs: + build-and-analyze: + + name: Build on JDK 21 + runs-on: ubuntu-22.04 + steps: + + - name: Checkout Code + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + cache: 'maven' + + - name: Cache local Maven repository + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + # Cache Sonar packages which are used to run analysis and collect metrics + - name: Cache SonarCloud packages + uses: actions/cache@v4 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + + # Some tests need screen access + - name: Install xvfb + run: sudo apt-get install -y xvfb + + - name: Build with Maven and run SonarQube analysis + env: + # Intermediate variable + HEAD_REF: ${{ github.head_ref }} + # These two env variables are needed for sonar analysis + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + run: xvfb-run ./mvnw clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.organization=iluwatar -Dsonar.projectKey=iluwatar_java-design-patterns -Dsonar.pullrequest.branch=$HEAD_REF -Dsonar.pullrequest.base=${{ github.base_ref }} -Dsonar.pullrequest.key=${{ github.event.pull_request.number }} \ No newline at end of file diff --git a/.github/workflows/presubmit.yml b/.github/workflows/presubmit.yml new file mode 100644 index 000000000000..cac1250b70e8 --- /dev/null +++ b/.github/workflows/presubmit.yml @@ -0,0 +1,35 @@ +name: Presubmit.ai + +permissions: + contents: read + pull-requests: write + issues: write + +on: + pull_request_target: # Handle forked repository PRs in the base repository context + types: [opened, synchronize] + pull_request_review_comment: # Handle review comments + types: [created] + +jobs: + review: + runs-on: ubuntu-latest + steps: + - name: Check required secrets + run: | + if [ -z "${{ secrets.LLM_API_KEY }}" ]; then + echo "Error: LLM_API_KEY secret is not configured" + exit 1 + fi + + - name: Check out PR code + uses: actions/checkout@v3 + with: + ref: ${{ github.event.pull_request.head.sha }} + + - name: Run AI Reviewer + uses: presubmit/ai-reviewer@latest + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + LLM_API_KEY: ${{ secrets.LLM_API_KEY }} + LLM_MODEL: "gemini-1.5-flash" diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 000000000000..48a4271e470b --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,20 @@ +name: 'Comment on stale issues and PRs' +on: + schedule: + - cron: '30 1 * * *' + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + stale-issue-message: 'This issue is stale because it has been open 60 days with no activity.' + stale-pr-message: 'This PR is stale because it has been open 60 days with no activity.' + close-issue-message: 'This issue was closed because it has been stalled for too long with no activity.' + close-pr-message: 'This PR was closed because it has been stalled for too long with no activity.' + days-before-issue-stale: 60 + days-before-pr-stale: 60 + days-before-issue-close: -1 + days-before-pr-close: -1 + exempt-issue-labels: 'info: help wanted' diff --git a/.gitignore b/.gitignore index fd0bb7810faf..166aa2ede438 100644 --- a/.gitignore +++ b/.gitignore @@ -1,20 +1,61 @@ +################## Eclipse ###################### target .metadata .settings .classpath .project *.class -# Package Files # +tmp/ +*.tmp +*.bak +*~.nib +local.properties +.loadpath +.recommenders +.DS_Store + +####### Java annotation processor (APT) ######## +.factorypath + +################ Package Files ################## *.jar *.war *.ear -.idea -*.iml *.swp datanucleus.log /bin/ -/bin/ -/bin/ *.log -data-mapper/src/main/resources/log4j.xml event-sourcing/Journal.json + +################## Checkstyle ################### +.checkstyle + +##################### STS ####################### +.apt_generated +.springBeans +.sts4-cache + +################# IntelliJ IDEA ################# +.idea +*.iws +*.iml +*.ipr + +################### NetBeans #################### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +#################### VS Code #################### +.vscode/ + +#################### Java Design Patterns ####### +etc/Java Design Patterns.urm.puml +serialized-entity/output.txt +fish1.out +fish2.out diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000000..4f15c4db1572 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 85f53bcd3024..000000000000 --- a/.travis.yml +++ /dev/null @@ -1,39 +0,0 @@ -language: java -jdk: -- oraclejdk8 - -env: - global: - - GH_REF: github.com/iluwatar/java-design-patterns.git - - secure: LxTDuNS/rBWIvKkaEqr79ImZAe48mCdoYCF41coxNXgNoippo4GIBArknqtv+XvdkiuRZ1yGyj6pn8GU33c/yn+krddTUkVCwTbVatbalW5jhQjDbHYym/JcxaK9ZS/3JTeGcWrBgiPqHEEDhCf26vPZsXoMSeVCEORVKTp1BSg= - - secure: "eoWlW9GyTJY04P8K3pxayXwU9/hmptQg/LfirispQkV9YvmziCfSzXnatnBhNfud98sCzY8BScXnb+OWLTnjLKpId4rtEqb0aJ40Jc32cUKzgzFAUn7cNcDAbUIfyPAGVqyQqfj/11wYSADwWMMOPlW97ExUtoyiH2WenXuRHso=" - -before_install: -- export DISPLAY=:99.0 -- sh -e /etc/init.d/xvfb start - -# default install command is just "mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V" -install: -- mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -e - -after_success: -- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=$SONAR_TOKEN -- bash update-ghpages.sh - -# use latest java version available instead of travis default -addons: - apt: - packages: - - oracle-java8-installer - -notifications: - email: - - iluwatar@gmail.com - webhooks: - urls: - - https://webhooks.gitter.im/e/3319623945358a093a6f - on_success: change # options: [always|never|change] default: always - on_failure: always # options: [always|never|change] default: always - on_start: never # options: [always|never|change] default: always - -sudo: required diff --git a/CODE_COVERAGE.md b/CODE_COVERAGE.md deleted file mode 100644 index d1ce7afd2ac7..000000000000 --- a/CODE_COVERAGE.md +++ /dev/null @@ -1,13 +0,0 @@ -# Code Coverage Report generation - -To generate the code coverage report, execute the following command: -> mvn clean verify jacoco:report - -This will generate code coverage report in each of the modules. In order to view the same, open the following file in your browser. -> target/site/jacoco/index.html - -Please note that the above folder is created under each of the modules. For example: -* adapter/target/site/jacoco/index.html -* busniess-delegate/target/site/jacoco/index.html - - diff --git a/CONTRIBUTING.MD b/CONTRIBUTING.MD index 39087fbf12d3..8346d331ebfd 100644 --- a/CONTRIBUTING.MD +++ b/CONTRIBUTING.MD @@ -1,4 +1,3 @@ -This is great you have something to contribute! +The project guidelines can be found in [Java Design Patterns developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). -Before going any further please read the [wiki](https://github.com/iluwatar/java-design-patterns/wiki) -with conventions and rules we used for this project. +A good place to start is: https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute diff --git a/LICENSE.md b/LICENSE.md index e73cf6618a69..bcae7daadee9 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014-2016 Ilkka Seppälä +Copyright � 2014-2024 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 @@ -19,3 +19,6 @@ 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. + +Module Model-view-viewmodel is using ZK framework +ZK framework is licensed under LGPL and the license can be found at lgpl-3.0.txt diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 097054fe54b3..bd5b40615e7f 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -1,15 +1,7 @@ +# Pull Request Template -Pull request title +## What does this PR do? -- Clearly and concisely describes what it does -- Refer to the issue that it solves, if available + - -Pull request description - -- Describes the main changes that come with the pull request -- Any relevant additional information is provided - - - -> For detailed contributing instructions see https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute + diff --git a/README.md b/README.md index 4ec0f33bd350..2c2e375bf4f9 100644 --- a/README.md +++ b/README.md @@ -1,48 +1,586 @@ - +# Design Patterns Implemented in Java -# Design patterns implemented in Java - -[![Build status](https://travis-ci.org/iluwatar/java-design-patterns.svg?branch=master)](https://travis-ci.org/iluwatar/java-design-patterns) +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) [![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) [![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=com.iluwatar%3Ajava-design-patterns&metric=alert_status)](https://sonarcloud.io/dashboard/index/com.iluwatar%3Ajava-design-patterns) -[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/1503/badge)](https://bestpractices.coreinfrastructure.org/projects/1503) + +[![All Contributors](https://img.shields.io/badge/all_contributors-387-orange.svg?style=flat-square)](#contributors-) + + +
+ +Read in different language : [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md), [**vi**](localization/vi/README.md), [**bn**](localization/bn/README.md), [**np**](localization/ne/README.md), [**it**](localization/it/README.md), [**da**](localization/da/README.md) +
# Introduction -Design patterns are formalized best practices that the programmer can use to -solve common problems when designing an application or system. +Design patterns are the best, formalized practices a programmer can use to solve common problems when designing an application or system. -Design patterns can speed up the development process by providing tested, proven -development paradigms. +Design patterns can speed up the development process by providing tested, proven development paradigms. -Reusing design patterns helps to prevent subtle issues that can cause major -problems, and it also improves code readability for coders and architects who -are familiar with the patterns. +Reusing design patterns helps prevent subtle issues that cause major problems, and it also improves code readability for coders and architects who are familiar with the patterns. -# Getting started +# Getting Started -Before you dive into the material, you should be familiar with various -Programming/Software Design Principles. +This site showcases Java Design Patterns. The solutions have been developed by experienced programmers and architects from the open-source community. The patterns can be browsed by their high-level descriptions or by looking at their +source code. The source code examples are well commented and can be thought of as programming tutorials on how to implement a specific pattern. We use the most popular battle-proven open-source Java technologies. -All designs should be as simple as possible. You should start with KISS, YAGNI, -and Do The Simplest Thing That Could Possibly Work principles. Complexity and -patterns should only be introduced when they are needed for practical -extensibility. +Before you dive into the material, you should be familiar with various [Software Design Principles](https://java-design-patterns.com/principles/). -Once you are familiar with these concepts you can start drilling down into -patterns by any of the following approaches +All designs should be as simple as possible. You should start with KISS, YAGNI, and Do The Simplest Thing That Could Possibly Work principles. Complexity and patterns should only be introduced when they are needed for practical extensibility. - - Using difficulty tags, `Difficulty-Beginner`, `Difficulty-Intermediate` & `Difficulty-Expert`. - - Using pattern categories, `Creational`, `Behavioral` and others. - - Search for a specific pattern. Can't find one? Please report a new pattern [here](https://github.com/iluwatar/java-design-patterns/issues). +Once you are familiar with these concepts you can start drilling down into the [available design patterns](https://java-design-patterns.com/patterns/) by any of the following approaches: -# How to contribute + - Search for a specific pattern by name. Can't find one? Please report a new pattern [here](https://github.com/iluwatar/java-design-patterns/issues). + - Using tags such as `Performance`, `Gang of Four` or `Data access`. + - Using pattern categories, `Creational`, `Behavioral`, and others. + +Hopefully, you find the object-oriented solutions presented on this site useful in your architectures and have as much fun learning them as we had while developing them. + +# How to Contribute If you are willing to contribute to the project you will find the relevant information in our [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). We will help you and answer your questions in the [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns). +# The Book + +The design patterns are now available as an e-book. Find out more about "Open Source Java Design Patterns" here: https://payhip.com/b/bNQFX + +The project contributors can get the book for free. Contact the maintainer via [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns) or email (iluwatar (at) gmail (dot) com ). Send a message that contains your email address, Github username, and a link to an accepted pull request. + # License This project is licensed under the terms of the MIT license. + +# Contributors + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Ilkka Seppälä
Ilkka Seppälä

📆 🚧 🖋
Subhrodip Mohanta
Subhrodip Mohanta

💻 👀 🚧
amit1307
amit1307

💻
Narendra Pathai
Narendra Pathai

💻 🤔 👀
Jeroen Meulemeester
Jeroen Meulemeester

💻
Joseph McCarthy
Joseph McCarthy

💻
Thomas
Thomas

💻
Anurag Agarwal
Anurag Agarwal

💻
Markus Moser
Markus Moser

🎨 💻 🤔
Sabiq Ihab
Sabiq Ihab

💻
Amit Dixit
Amit Dixit

💻
Piyush Kailash Chaudhari
Piyush Kailash Chaudhari

💻
joshzambales
joshzambales

💻
Kamil Pietruszka
Kamil Pietruszka

💻
Zafar Khaydarov
Zafar Khaydarov

💻 📖
Paul Campbell
Paul Campbell

💻
Argyro Sioziou
Argyro Sioziou

💻
TylerMcConville
TylerMcConville

💻
saksham93
saksham93

💻
nikhilbarar
nikhilbarar

💻
Colin But
Colin But

💻
Ruslan
Ruslan

💻
Juho Kang
Juho Kang

💻
Dheeraj Mummareddy
Dheeraj Mummareddy

💻
Bernardo Sulzbach
Bernardo Sulzbach

💻
Aleksandar Dudukovic
Aleksandar Dudukovic

💻
Yusuf Aytaş
Yusuf Aytaş

💻
Mihály Kuprivecz
Mihály Kuprivecz

💻
Stanislav Kapinus
Stanislav Kapinus

💻
GVSharma
GVSharma

💻
Srđan Paunović
Srđan Paunović

💻
Petros G. Sideris
Petros G. Sideris

💻
Pramod Gupta
Pramod Gupta

👀
Amarnath Chandana
Amarnath Chandana

💻
Anurag870
Anurag870

💻 📖
Wes Gilleland
Wes Gilleland

💻
Harshraj Thakor
Harshraj Thakor

💻
Martin Vandenbussche
Martin Vandenbussche

💻
Alexandru Somai
Alexandru Somai

💻
Artur Mogozov
Artur Mogozov

💻
anthony
anthony

💻
Christian Cygnus
Christian Cygnus

💻
Dima Gubin
Dima Gubin

💻
Joshua Jimenez
Joshua Jimenez

💻
Kai Winter
Kai Winter

💻
lbroman
lbroman

💻
Przemek
Przemek

💻
Prafful Agarwal
Prafful Agarwal

🖋
Sanket Panhale
Sanket Panhale

🖋
staillebois
staillebois

💻
Krisztián Nagy
Krisztián Nagy

💻
Alexander Ivanov
Alexander Ivanov

💻
Yosfik Alqadri
Yosfik Alqadri

💻
Agustí Becerra Milà
Agustí Becerra Milà

💻
Juan Manuel Suárez
Juan Manuel Suárez

💻
Luigi Cortese
Luigi Cortese

💻
Katarzyna Rzepecka
Katarzyna Rzepecka

💻
adamski.pro
adamski.pro

💻
Shengli Bai
Shengli Bai

💻
Boris
Boris

💻
Dmitry Avershin
Dmitry Avershin

💻
靳阳
靳阳

💻
hoangnam2261
hoangnam2261

💻
Arpit Jain
Arpit Jain

💻
Jón Ingi Sveinbjörnsson
Jón Ingi Sveinbjörnsson

💻
Kirill Vlasov
Kirill Vlasov

💻
Mitchell Irvin
Mitchell Irvin

💻
Ranjeet
Ranjeet

💻
PhoenixYip
PhoenixYip

💻
M Saif Asif
M Saif Asif

💻
kanwarpreet25
kanwarpreet25

💻
Leon Mak
Leon Mak

💻
Per Wramdemark
Per Wramdemark

💻
Evan Sia Wai Suan
Evan Sia Wai Suan

💻
AnaghaSasikumar
AnaghaSasikumar

💻
Christoffer Hamberg
Christoffer Hamberg

💻
Dominik Gruntz
Dominik Gruntz

💻
Hannes
Hannes

💻
Leo Gutiérrez Ramírez
Leo Gutiérrez Ramírez

💻
Zhang WH
Zhang WH

💻
Christopher O'Connell
Christopher O'Connell

💻
George Mavroeidis
George Mavroeidis

💻
Hemant Bothra
Hemant Bothra

💻 🎨
Kevin Peters
Kevin Peters

💻
George Aristy
George Aristy

💻
Mahendran Mookkiah
Mahendran Mookkiah

💻
Azureyjt
Azureyjt

💻
gans
gans

💻
Matt
Matt

🖋
Gopinath Langote
Gopinath Langote

💻
Hoswey
Hoswey

💻
Amit Pandey
Amit Pandey

💻
gwildor28
gwildor28

🖋
田浩
田浩

🖋
Stamatis Pitsios
Stamatis Pitsios

💻
qza
qza

💻
Rodolfo Forte
Rodolfo Forte

🖋
Ankur Kaushal
Ankur Kaushal

💻
Ovidijus Okinskas
Ovidijus Okinskas

💻
Robert Kasperczyk
Robert Kasperczyk

💻
Tapio Rautonen
Tapio Rautonen

💻
Yuri Orlov
Yuri Orlov

💻
Varun Upadhyay
Varun Upadhyay

💻
Aditya Pal
Aditya Pal

💻
grzesiekkedzior
grzesiekkedzior

💻 👀
Sivasubramani M
Sivasubramani M

💻
Sami Airaksinen
Sami Airaksinen

💻
Janne Sinivirta
Janne Sinivirta

💻
Boris-Chengbiao Zhou
Boris-Chengbiao Zhou

🖋
Jacob Hein
Jacob Hein

🖋
Richard Jones
Richard Jones

🖋
Rachel M. Carmena
Rachel M. Carmena

🖋
Zaerald Denze Lungos
Zaerald Denze Lungos

🖋
Lars Kappert
Lars Kappert

🖋
Mike Liu
Mike Liu

🌍
Matt Dolan
Matt Dolan

💻 👀
Manan
Manan

👀
Nishant Arora
Nishant Arora

💻
Peeyush
Peeyush

💻
Rakesh
Rakesh

💻 👀
Wei Seng
Wei Seng

💻
Ashish Trivedi
Ashish Trivedi

💻
洪月阳
洪月阳

💻
xdvrx1
xdvrx1

👀 🤔
Bethan Palmer
Bethan Palmer

💻
Toxic Dreamz
Toxic Dreamz

💻
Edy Cu Tjong
Edy Cu Tjong

📖
Michał Krzywański
Michał Krzywański

💻
Stefan Birkner
Stefan Birkner

💻
Fedor Skvorcov
Fedor Skvorcov

💻
samilAyoub
samilAyoub

💻
Vladislav Golubinov
Vladislav Golubinov

💻
Swaraj
Swaraj

💻
Christoph Flick
Christoph Flick

📖
Ascênio
Ascênio

👀
Domenico Sibilio
Domenico Sibilio

📖
Akash Chandwani
Akash Chandwani

👀
Pavlo Manannikov
Pavlo Manannikov

💻
Eiman
Eiman

💻
Rocky
Rocky

📖
Ibrahim ali abdelghany
Ibrahim ali abdelghany

👀
Girish Kulkarni
Girish Kulkarni

📖
Omar Karazoun
Omar Karazoun

💻
Jeff Evans
Jeff Evans

💻
Vivek Singh
Vivek Singh

💻
siavash
siavash

💻
ruchpeanuts
ruchpeanuts

📖
warp125
warp125

🌍
KHADIR Tayeb
KHADIR Tayeb

🌍
ignite1771
ignite1771

💻
Halil Demir
Halil Demir

🌍
Rohit Singh
Rohit Singh

💻
byoungju94
byoungju94

💻
Moustafa Farhat
Moustafa Farhat

🌍
Martel Richard
Martel Richard

💻
va1m
va1m

💻
Noam Greenshtain
Noam Greenshtain

💻
yonghong Xu
yonghong Xu

📖
jinishavora
jinishavora

👀 💻
Elvys Soares
Elvys Soares

💻
zWeBrain
zWeBrain

💻
余林颖
余林颖

🌍
Alain
Alain

🌍
VR
VR

📖
JackieNim
JackieNim

💻
EdisonE3
EdisonE3

💻
Tao
Tao

💻
Juan Manuel Abate
Juan Manuel Abate

🌍
Xenilo137
Xenilo137

💻
Samuel Souza
Samuel Souza

💻 📖
Marlo Henrique
Marlo Henrique

🌍
AndriyPyzh
AndriyPyzh

💻
karthikbhat13
karthikbhat13

💻
Morteza Adigozalpour
Morteza Adigozalpour

💻
Nagaraj Tantri
Nagaraj Tantri

💻
Francesco Scuccimarri
Francesco Scuccimarri

💻
Conny Hansson
Conny Hansson

📖
Muklas Rahmanto
Muklas Rahmanto

🌍
Vadim
Vadim

🌍
Simran Keshri
Simran Keshri

💻
JCarlos
JCarlos

🌍
Ali Ghasemi
Ali Ghasemi

💻
Carl Dea
Carl Dea

💻
Mozartus
Mozartus

🌍
Manvi Goel
Manvi Goel

📖
Anum Amin
Anum Amin

📖
Reo Uehara
Reo Uehara

🌍
Fiordy
Fiordy

📖
Harshal
Harshal

💻
Abhinav Vashisth
Abhinav Vashisth

📖
Kevin
Kevin

👀 💻
Shrirang
Shrirang

👀 💻
interactwithankush
interactwithankush

💻
CharlieYu
CharlieYu

💻
Leisterbecker
Leisterbecker

💻
DragonDreamer
DragonDreamer

💻
ShivanshCharak
ShivanshCharak

💻
HattoriHenzo
HattoriHenzo

💻
Arnab Sen
Arnab Sen

💻
MohanaRao SV
MohanaRao SV

💻
Yonatan Karp-Rudin
Yonatan Karp-Rudin

💻 👀
Oliani
Oliani

💻
Renjie LIU
Renjie LIU

💻
perfect guy
perfect guy

📖
xyllq999
xyllq999

💻
Mohamed Bilal
Mohamed Bilal

📖
Karshil sheth
Karshil sheth

💻
kongleong86
kongleong86

💻
Aitor Fidalgo Sánchez
Aitor Fidalgo Sánchez

🌍 📖 👀
Victor He
Victor He

💻
Minh Nguyen
Minh Nguyen

🌍 📖
Victor He
Victor He

📖
yiichan
yiichan

📖
Pan Sem
Pan Sem

📖
zhoumengyks
zhoumengyks

💻
you
you

🌍
Thanks
Thanks

🌍
LazyProgrammer
LazyProgrammer

📖
Mohammed Faizan Ahmed
Mohammed Faizan Ahmed

📖
Bruno Fernandes
Bruno Fernandes

💻
SammanPali
SammanPali

📖
Qixiang Chen
Qixiang Chen

📖
Shourya Manekar
Shourya Manekar

🌍
Alan
Alan

🌍
JanFidor
JanFidor

💻 📖
Anton Yakutovich
Anton Yakutovich

💻
steph88ss
steph88ss

📖
Yujan Ranjitkar
Yujan Ranjitkar

🌍
yusha-g
yusha-g

🌍
Robert Volkmann
Robert Volkmann

💻 👀
Bipin Kumar Chaurasia
Bipin Kumar Chaurasia

📖
KyleSong30
KyleSong30

📖
u7281975
u7281975

📖
harshalkhachane
harshalkhachane

💻
Tejas Singh
Tejas Singh

📖 🌍
Sudarsan Balaji
Sudarsan Balaji

💻
Vaibhav Agrawal
Vaibhav Agrawal

📖
u7275858
u7275858

💻
prasad-333
prasad-333

📖
JurenXu
JurenXu

💻
murphShaw
murphShaw

📖
XianWu99
XianWu99

📖
JoshuaSinglaANU
JoshuaSinglaANU

💻
Ricardo Ramos
Ricardo Ramos

🌍
Farid Zouheir
Farid Zouheir

🌍
Vinícius A. B.
Vinícius A. B.

🌍
Stefanel Stan
Stefanel Stan

💻
Prince bhati
Prince bhati

🌍
WuLang
WuLang

📖
Hugo Kat
Hugo Kat

💻
Shivanagouda Agasimani
Shivanagouda Agasimani

💻
Aparna
Aparna

💻
Girolamo Giordano
Girolamo Giordano

🌍
Chak-C
Chak-C

💻
Nakul Nambiar
Nakul Nambiar

💻
KarmaTashiCat
KarmaTashiCat

🌍
marikattt
marikattt

💻
Hashvardhan Parmar
Hashvardhan Parmar

🌍
YongHwan
YongHwan

📖 🌍
Shogo Hida
Shogo Hida

🌍
Eugene
Eugene

💻
Piyush
Piyush

📖
Rahul Raj
Rahul Raj

💻
Bharath Kalyan S
Bharath Kalyan S

💻
Saiteja Reddy
Saiteja Reddy

🌍
Enrique Clerici
Enrique Clerici

🌍
Ramil Sayetov
Ramil Sayetov

🌍
东方未白
东方未白

💻
Fredrik Sejr
Fredrik Sejr

🌍
akshatarora0013
akshatarora0013

💻
Mughees Qasim
Mughees Qasim

💻
behappyleee
behappyleee

🌍
Ayush Thakur
Ayush Thakur

🌍
Anthony Bosch
Anthony Bosch

💻
trananso
trananso

📖
Giammaria Biffi
Giammaria Biffi

🌍
Saiful Haque
Saiful Haque

💻
JabezBrew
JabezBrew

💻
konstantin-goldman
konstantin-goldman

📖
Tien Nguyen Minh
Tien Nguyen Minh

💻 🌍
Vladimir
Vladimir

🌍
Surjendu
Surjendu

🌍 💻
bakazhou
bakazhou

💻
Owen Leung
Owen Leung

💻
Stavros Barousis
Stavros Barousis

📖
Syyed Ibrahim Abdullah
Syyed Ibrahim Abdullah

🌍
JiaDi Zhang
JiaDi Zhang

🌍
Sanchit Bansal
Sanchit Bansal

📖
Md Saiful Islam
Md Saiful Islam

📖
Antonio Addeo
Antonio Addeo

📖 💻
Allagadda Sai Upendranath
Allagadda Sai Upendranath

📖
Matheus Braga
Matheus Braga

🌍 📖
Appari Satya Barghav
Appari Satya Barghav

📖
Marcel Ribeiro-Dantas
Marcel Ribeiro-Dantas

📖
Muhammad Hanif Amrullah
Muhammad Hanif Amrullah

🌍
JackH408
JackH408

📖
Shubham
Shubham

🌍
Nishant Jain
Nishant Jain

📖
Rhitam Chaudhury
Rhitam Chaudhury

📖
JerryZhao275
JerryZhao275

📖
Leonardo Lisanti
Leonardo Lisanti

🌍
Yennifer Herrera
Yennifer Herrera

🌍 👀
jnniu-n
jnniu-n

🌍 📖
Miguel Angel Perez Garcia
Miguel Angel Perez Garcia

👀 🌍
Suwan Sankaja
Suwan Sankaja

🌍
alok
alok

📖
Daniel Lisboa
Daniel Lisboa

🌍
Sam Powell
Sam Powell

📖
João Fernandes
João Fernandes

🌍
Hong Geon-ui
Hong Geon-ui

🌍
Doksanbir
Doksanbir

💻 📖 👀
Chant3ll3
Chant3ll3

📖 🌍
YongHwan Kwon
YongHwan Kwon

💻
Jakub Klimek
Jakub Klimek

💻
believe
believe

🌍
egg0102030405
egg0102030405

🌍 📖
Ved Asole
Ved Asole

💻
NewMorning
NewMorning

🌍
资深老萌新
资深老萌新

🌍
Seunghwan Jeon
Seunghwan Jeon

🌍
sugavanesh
sugavanesh

💻
FinnS-F
FinnS-F

💻
jerryyummy
jerryyummy

🌍
Manoj Chowdary
Manoj Chowdary

💻
Aditya
Aditya

📖 💻
nooynayr
nooynayr

📖
CYBERCRUX2
CYBERCRUX2

📖
Luis Mateo Hincapié Martinez
Luis Mateo Hincapié Martinez

🌍 👀
guqing
guqing

💻
Sashir Estela
Sashir Estela

💻
omahs
omahs

📖
leif e.
leif e.

💻
Jun Kang
Jun Kang

💻
Kishalay Pandey
Kishalay Pandey

💻
drishtii7
drishtii7

💻
David Medina Orozco
David Medina Orozco

🌍 👀
Roman Leontev
Roman Leontev

💻
Riley
Riley

💻
k1w1dev
k1w1dev

💻
dev-yugantar
dev-yugantar

💻
Adelya
Adelya

💻
gatlanagaprasanna
gatlanagaprasanna

📖
Avinash Shukla
Avinash Shukla

💻
Mayank Choudhary
Mayank Choudhary

💻
romannimets
romannimets

💻
Joel
Joel

💻
Walyson Moises
Walyson Moises

💻
Xcyq
Xcyq

💻
Ritabrata
Ritabrata

👀
Trivikram Kamat
Trivikram Kamat

💻
Vincent Vanghelle
Vincent Vanghelle

🌍
Antoine Héritier
Antoine Héritier

🌍
QinShower
QinShower

🌍
LakshyaPunyani-01
LakshyaPunyani-01

💻
jasonjyu
jasonjyu

💻
jeffmorrison
jeffmorrison

💻
David M.
David M.

💻
Patrick Kleindienst
Patrick Kleindienst

💻
Juyeon
Juyeon

🌍
Mammad Yahyayev
Mammad Yahyayev

📖
Salma
Salma

💻
Arpit Sarang
Arpit Sarang

💻
Maya
Maya

🌍
HabibaMekay
HabibaMekay

💻
Ahmed-Taha-981
Ahmed-Taha-981

💻
Malak Elbanna
Malak Elbanna

💻
BiKangNing
BiKangNing

📖
Tarun Vishwakarma
Tarun Vishwakarma

💻
Shahd Hossam
Shahd Hossam

💻
Mehdi Rahimi
Mehdi Rahimi

💻
Clint Airé
Clint Airé

💻
darkhyper24
darkhyper24

💻
Mohaned Atef
Mohaned Atef

💻
Maxim Evtush
Maxim Evtush

💻
Harshita Vidapanakal
Harshita Vidapanakal

💻
smile-ab
smile-ab

🌍 💻
Francisco-G-P
Francisco-G-P

🌍
Gabriel Duarte
Gabriel Duarte

📖
Deniz Altunkapan
Deniz Altunkapan

🌍
John Klint
John Klint

💻
Sanura Hettiarachchi
Sanura Hettiarachchi

💻
Kim Gi Uk
Kim Gi Uk

💻
Suchismita Deb
Suchismita Deb

💻
ssrijan-007-sys
ssrijan-007-sys

💻
e5LA
e5LA

💻 📖
Maziyar Gerami
Maziyar Gerami

🌍
yoobin_mion
yoobin_mion

💻
+ + + + + diff --git a/abstract-document/README.md b/abstract-document/README.md index 2adb3732b822..56f8e775c676 100644 --- a/abstract-document/README.md +++ b/abstract-document/README.md @@ -1,29 +1,247 @@ --- -layout: pattern -title: Abstract Document -folder: abstract-document -permalink: /patterns/abstract-document/ -categories: Structural -tags: - - Java - - Difficulty-Intermediate +title: "Abstract Document Pattern in Java: Simplifying Data Handling with Flexibility" +shortTitle: Abstract Document +description: "Explore the Abstract Document design pattern in Java. Learn its intent, explanation, applicability, benefits, and see real-world examples to implement flexible and dynamic data structures." +category: Structural +language: en +tag: + - Abstraction + - Decoupling + - Dynamic typing + - Encapsulation + - Extensibility + - Polymorphism --- -## Intent -Achieve flexibility of untyped languages and keep the type-safety +## Intent of Abstract Document Design Pattern -![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain") +The Abstract Document design pattern in Java is a crucial structural design pattern that provides a consistent way to handle hierarchical and tree-like data structures by defining a common interface for various document types. It separates the core document structure from specific data formats, enabling dynamic updates and simplified maintenance. +## Detailed Explanation of Abstract Document Pattern with Real-World Examples -## Applicability -Use the Abstract Document Pattern when +The Abstract Document design pattern in Java allows dynamic handling of non-static properties. This pattern uses concept of traits to enable type safety and separate properties of different classes into set of interfaces. -* there is a need to add new properties on the fly -* you want a flexible way to organize domain in tree like structure -* you want more loosely coupled system +Real-world example +> Consider a library system implementing the Abstract Document design pattern in Java, where books can have diverse formats and attributes: physical books, eBooks, and audiobooks. Each format has unique properties, such as page count for physical books, file size for eBooks, and duration for audiobooks. The Abstract Document design pattern allows the library system to manage these diverse formats flexibly. By using this pattern, the system can store and retrieve properties dynamically, without needing a rigid structure for each book type, making it easier to add new formats or attributes in the future without significant changes to the codebase. -## Credits +In plain words -* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) -* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) \ No newline at end of file +> Abstract Document pattern allows attaching properties to objects without them knowing about it. + +Wikipedia says + +> An object-oriented structural design pattern for organizing objects in loosely typed key-value stores and exposing the data using typed views. The purpose of the pattern is to achieve a high degree of flexibility between components in a strongly typed language where new properties can be added to the object-tree on the fly, without losing the support of type-safety. The pattern makes use of traits to separate different properties of a class into different interfaces. + +Class diagram + +![Abstract Document class diagram](./etc/abstract-document.png "Abstract Document class diagram") + + +## Programmatic Example of Abstract Document Pattern in Java + +Consider a car that consists of multiple parts. However, we don't know if the specific car really has all the parts, or just some of them. Our cars are dynamic and extremely flexible. + +Let's first define the base classes `Document` and `AbstractDocument`. They basically make the object hold a property map and any amount of child objects. + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + + // Other properties and methods... +} +``` + +Next we define an enum `Property` and a set of interfaces for type, price, model and parts. This allows us to create static looking interface to our `Car` class. + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} + +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} + +public class Part extends AbstractDocument implements HasType, HasModel, HasPrice { + + public Part(Map properties) { + super(properties); + } +} +``` + +Now we are ready to introduce the `Car`. + +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` + +And finally here's how we construct and use the `Car` in a full example. + +```java + public static void main(String[] args) { + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); +} +``` + +The program output: + +``` +07:21:57.391 [main] INFO com.iluwatar.abstractdocument.App -- Constructing parts and car +07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- Here is our car: +07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- -> model: 300SL +07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> price: 10000 +07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> parts: +07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- wheel/15C/100 +07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- door/Lambo/300 +``` + +## When to Use the Abstract Document Pattern in Java + +The Abstract Document design pattern is especially beneficial in scenarios requiring management of different document types in Java that share some common attributes or behaviors, but also have unique attributes or behaviors specific to their individual types. Here are some scenarios where the Abstract Document design pattern can be applicable: + +* Content Management Systems (CMS): In a CMS, you might have various types of content such as articles, images, videos, etc. Each type of content could have shared attributes like creation date, author, and tags, while also having specific attributes like image dimensions for images or video duration for videos. + +* File Systems: If you're designing a file system where different types of files need to be managed, such as documents, images, audio files, and directories, the Abstract Document pattern can help provide a consistent way to access attributes like file size, creation date, etc., while allowing for specific attributes like image resolution or audio duration. + +* E-commerce Systems: An e-commerce platform might have different product types such as physical products, digital downloads, and subscriptions. Each type could share common attributes like name, price, and description, while having unique attributes like shipping weight for physical products or download link for digital products. + +* Medical Records Systems: In healthcare, patient records might include various types of data such as demographics, medical history, test results, and prescriptions. The Abstract Document pattern can help manage shared attributes like patient ID and date of birth, while accommodating specialized attributes like test results or prescribed medications. + +* Configuration Management: When dealing with configuration settings for software applications, there can be different types of configuration elements, each with its own set of attributes. The Abstract Document pattern can be used to manage these configuration elements while ensuring a consistent way to access and manipulate their attributes. + +* Educational Platforms: Educational systems might have various types of learning materials such as text-based content, videos, quizzes, and assignments. Common attributes like title, author, and publication date can be shared, while unique attributes like video duration or assignment due dates can be specific to each type. + +* Project Management Tools: In project management applications, you could have different types of tasks like to-do items, milestones, and issues. The Abstract Document pattern could be used to handle general attributes like task name and assignee, while allowing for specific attributes like milestone date or issue priority. + +* Documents have diverse and evolving attribute structures. + +* Dynamically adding new properties is a common requirement. + +* Decoupling data access from specific formats is crucial. + +* Maintainability and flexibility are critical for the codebase. + +The key idea behind the Abstract Document design pattern is to provide a flexible and extensible way to manage different types of documents or entities with shared and distinct attributes. By defining a common interface and implementing it across various document types, you can achieve a more organized and consistent approach to handling complex data structures. + +## Benefits and Trade-offs of Abstract Document Pattern + +Benefits: + +* Flexibility: Accommodates varied document structures and properties. + +* Extensibility: Dynamically add new attributes without breaking existing code. + +* Maintainability: Promotes clean and adaptable code due to separation of concerns. + +* Reusability: Typed views enable code reuse for accessing specific attribute types. + +Trade-offs: + +* Complexity: Requires defining interfaces and views, adding implementation overhead. + +* Performance: Might introduce slight performance overhead compared to direct data access. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://amzn.to/49zRP4R) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) +* [Abstract Document Pattern (Wikipedia)](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Dealing with Properties (Martin Fowler)](http://martinfowler.com/apsupp/properties.pdf) diff --git a/abstract-document/etc/abstract-document.urm.puml b/abstract-document/etc/abstract-document.urm.puml new file mode 100644 index 000000000000..9940dc2cfd05 --- /dev/null +++ b/abstract-document/etc/abstract-document.urm.puml @@ -0,0 +1,65 @@ +@startuml +package com.iluwatar.abstractdocument.domain.enums { + enum Property { + + MODEL {static} + + PARTS {static} + + PRICE {static} + + TYPE {static} + + valueOf(name : String) : Property {static} + + values() : Property[] {static} + } +} +package com.iluwatar.abstractdocument.domain { + class Car { + + Car(properties : Map) + } + interface HasModel { + + getModel() : Optional + } + interface HasParts { + + getParts() : Stream + } + interface HasPrice { + + getPrice() : Optional + } + interface HasType { + + getType() : Optional + } + class Part { + + Part(properties : Map) + } +} +package com.iluwatar.abstractdocument { + abstract class AbstractDocument { + - properties : Map + # AbstractDocument(properties : Map) + + children(key : String, constructor : Function, T>) : Stream + + get(key : String) : Object + + put(key : String, value : Object) + + toString() : String + } + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + interface Document { + + children(String, Function, T>) : Stream {abstract} + + get(String) : Object {abstract} + + put(String, Object) {abstract} + } +} +AbstractDocument ..|> Document +Car ..|> HasModel +Car ..|> HasPrice +Car ..|> HasParts +Car --|> AbstractDocument +HasModel --|> Document +HasParts --|> Document +HasPrice --|> Document +HasType --|> Document +Part ..|> HasType +Part ..|> HasModel +Part ..|> HasPrice +Part --|> AbstractDocument +@enduml \ No newline at end of file diff --git a/abstract-document/pom.xml b/abstract-document/pom.xml index d1b10a9fd84f..ef190e088d5e 100644 --- a/abstract-document/pom.xml +++ b/abstract-document/pom.xml @@ -1,8 +1,10 @@ - - 4.0.0 - - java-design-patterns - com.iluwatar - 1.20.0-SNAPSHOT - - abstract-document - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - \ No newline at end of file + + 4.0.0 + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + abstract-document + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.abstractdocument.App + + + + + + + + + diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java index 36a946cc9eca..ab5ccada1414 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -22,51 +24,78 @@ */ package com.iluwatar.abstractdocument; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Optional; import java.util.function.Function; import java.util.stream.Stream; -/** - * Abstract implementation of Document interface - */ +/** Abstract implementation of Document interface. */ public abstract class AbstractDocument implements Document { - private final Map properties; + private final Map documentProperties; protected AbstractDocument(Map properties) { Objects.requireNonNull(properties, "properties map is required"); - this.properties = properties; + this.documentProperties = properties; } @Override public Void put(String key, Object value) { - properties.put(key, value); + documentProperties.put(key, value); return null; } @Override public Object get(String key) { - return properties.get(key); + return documentProperties.get(key); } @Override - public Stream children(String key, Function, T> constructor) { - Optional>> any = Stream.of(get(key)).filter(el -> el != null) - .map(el -> (List>) el).findAny(); - return any.isPresent() ? any.get().stream().map(constructor) : Stream.empty(); + public Stream children(String key, Function, T> childConstructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(childConstructor); } @Override public String toString() { - StringBuilder builder = new StringBuilder(); + return buildStringRepresentation(); + } + + private String buildStringRepresentation() { + var builder = new StringBuilder(); builder.append(getClass().getName()).append("["); - properties.entrySet() - .forEach(e -> builder.append("[").append(e.getKey()).append(" : ").append(e.getValue()).append("]")); + + // Explaining variable for document properties map + Map documentProperties = this.documentProperties; + + // Explaining variable for the size of document properties map + int numProperties = documentProperties.size(); + + // Explaining variable for tracking the current property index + int currentPropertyIndex = 0; + + // Iterate over document properties map + for (Map.Entry entry : documentProperties.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + // Append key-value pair + builder.append("[").append(key).append(" : ").append(value).append("]"); + + // Add comma if not last property + if (++currentPropertyIndex < numProperties) { + builder.append(", "); + } + } + builder.append("]"); return builder.toString(); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java index 83f6ab3d59dd..607b4a7f7913 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -23,69 +25,64 @@ package com.iluwatar.abstractdocument; import com.iluwatar.abstractdocument.domain.Car; -import com.iluwatar.abstractdocument.domain.HasModel; -import com.iluwatar.abstractdocument.domain.HasParts; -import com.iluwatar.abstractdocument.domain.HasPrice; -import com.iluwatar.abstractdocument.domain.HasType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Arrays; -import java.util.HashMap; +import com.iluwatar.abstractdocument.domain.enums.Property; +import java.util.List; import java.util.Map; +import lombok.extern.slf4j.Slf4j; /** - * The Abstract Document pattern enables handling additional, non-static - * properties. This pattern uses concept of traits to enable type safety and - * separate properties of different classes into set of interfaces. - *

- *

- * In Abstract Document pattern,({@link AbstractDocument}) fully implements - * {@link Document}) interface. Traits are then defined to enable access to - * properties in usual, static way. + * The Abstract Document pattern enables handling additional, non-static properties. This pattern + * uses concept of traits to enable type safety and separate properties of different classes into + * set of interfaces. + * + *

In Abstract Document pattern,({@link AbstractDocument}) fully implements {@link Document}) + * interface. Traits are then defined to enable access to properties in usual, static way. */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * Executes the App + * Program entry point. + * + * @param args command line args */ - public App() { + public static void main(String[] args) { LOGGER.info("Constructing parts and car"); - Map carProperties = new HashMap<>(); - carProperties.put(HasModel.PROPERTY, "300SL"); - carProperties.put(HasPrice.PROPERTY, 10000L); + var wheelProperties = + Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); - Map wheelProperties = new HashMap<>(); - wheelProperties.put(HasType.PROPERTY, "wheel"); - wheelProperties.put(HasModel.PROPERTY, "15C"); - wheelProperties.put(HasPrice.PROPERTY, 100L); + var doorProperties = + Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); - Map doorProperties = new HashMap<>(); - doorProperties.put(HasType.PROPERTY, "door"); - doorProperties.put(HasModel.PROPERTY, "Lambo"); - doorProperties.put(HasPrice.PROPERTY, 300L); + var carProperties = + Map.of( + Property.MODEL.toString(), + "300SL", + Property.PRICE.toString(), + 10000L, + Property.PARTS.toString(), + List.of(wheelProperties, doorProperties)); - carProperties.put(HasParts.PROPERTY, Arrays.asList(wheelProperties, doorProperties)); - - Car car = new Car(carProperties); + var car = new Car(carProperties); LOGGER.info("Here is our car:"); - LOGGER.info("-> model: {}", car.getModel().get()); - LOGGER.info("-> price: {}", car.getPrice().get()); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); LOGGER.info("-> parts: "); - car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", p.getType().get(), p.getModel().get(), p.getPrice().get())); + car.getParts() + .forEach( + p -> + LOGGER.info( + "\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null))); } - - /** - * Program entry point - * - * @param args command line args - */ - public static void main(String[] args) { - new App(); - } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java index 13782351492f..79a51b610337 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -26,22 +28,20 @@ import java.util.function.Function; import java.util.stream.Stream; -/** - * Document interface - */ +/** Document interface. */ public interface Document { /** - * Puts the value related to the key + * Puts the value related to the key. * - * @param key element key + * @param key element key * @param value element value * @return Void */ Void put(String key, Object value); /** - * Gets the value for the key + * Gets the value for the key. * * @param key element key * @return value or null @@ -49,9 +49,9 @@ public interface Document { Object get(String key); /** - * Gets the stream of child documents + * Gets the stream of child documents. * - * @param key element key + * @param key element key * @param constructor constructor of child class * @return child documents */ diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java index 44f640b415fd..93fbbb9c1eae 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -22,17 +24,13 @@ */ package com.iluwatar.abstractdocument.domain; -import java.util.Map; - import com.iluwatar.abstractdocument.AbstractDocument; +import java.util.Map; -/** - * Car entity - */ +/** Car entity. */ public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { public Car(Map properties) { super(properties); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java index 252a4644f289..6f517588e5a0 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -22,19 +24,14 @@ */ package com.iluwatar.abstractdocument.domain; -import java.util.Optional; - import com.iluwatar.abstractdocument.Document; +import com.iluwatar.abstractdocument.domain.enums.Property; +import java.util.Optional; -/** - * HasModel trait for static access to 'model' property - */ +/** HasModel trait for static access to 'model' property. */ public interface HasModel extends Document { - String PROPERTY = "model"; - default Optional getModel() { - return Optional.ofNullable((String) get(PROPERTY)); + return Optional.ofNullable((String) get(Property.MODEL.toString())); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java index 9df836376f55..8bffa753e6ef 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -22,19 +24,14 @@ */ package com.iluwatar.abstractdocument.domain; -import java.util.stream.Stream; - import com.iluwatar.abstractdocument.Document; +import com.iluwatar.abstractdocument.domain.enums.Property; +import java.util.stream.Stream; -/** - * HasParts trait for static access to 'parts' property - */ +/** HasParts trait for static access to 'parts' property. */ public interface HasParts extends Document { - String PROPERTY = "parts"; - default Stream getParts() { - return children(PROPERTY, Part::new); + return children(Property.PARTS.toString(), Part::new); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java index 39e4d159ce58..ce876e5faf54 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -22,19 +24,14 @@ */ package com.iluwatar.abstractdocument.domain; -import java.util.Optional; - import com.iluwatar.abstractdocument.Document; +import com.iluwatar.abstractdocument.domain.enums.Property; +import java.util.Optional; -/** - * HasPrice trait for static access to 'price' property - */ +/** HasPrice trait for static access to 'price' property. */ public interface HasPrice extends Document { - String PROPERTY = "price"; - default Optional getPrice() { - return Optional.ofNullable((Number) get(PROPERTY)); + return Optional.ofNullable((Number) get(Property.PRICE.toString())); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java index 4a80bff20c16..5e0f49df7b7b 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -23,18 +25,13 @@ package com.iluwatar.abstractdocument.domain; import com.iluwatar.abstractdocument.Document; - +import com.iluwatar.abstractdocument.domain.enums.Property; import java.util.Optional; -/** - * HasType trait for static access to 'type' property - */ +/** HasType trait for static access to 'type' property. */ public interface HasType extends Document { - String PROPERTY = "type"; - default Optional getType() { - return Optional.ofNullable((String) get(PROPERTY)); + return Optional.ofNullable((String) get(Property.TYPE.toString())); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java index 649ccf41365b..6eec08b0d2a4 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -22,17 +24,13 @@ */ package com.iluwatar.abstractdocument.domain; -import java.util.Map; - import com.iluwatar.abstractdocument.AbstractDocument; +import java.util.Map; -/** - * Part entity - */ +/** Part entity. */ public class Part extends AbstractDocument implements HasType, HasModel, HasPrice { public Part(Map properties) { super(properties); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/enums/Property.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/enums/Property.java new file mode 100644 index 000000000000..3e0d6d10ab1f --- /dev/null +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/enums/Property.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.abstractdocument.domain.enums; + +/** Enum To Describe Property type. */ +public enum Property { + PARTS, + TYPE, + PRICE, + MODEL +} diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java index 63a9974b99eb..a098517c3a69 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -22,67 +24,107 @@ */ package com.iluwatar.abstractdocument; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Stream; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -/** - * AbstractDocument test class - */ -public class AbstractDocumentTest { +/** AbstractDocument test class */ +class AbstractDocumentTest { private static final String KEY = "key"; private static final String VALUE = "value"; - private class DocumentImplementation extends AbstractDocument { + private static class DocumentImplementation extends AbstractDocument { DocumentImplementation(Map properties) { super(properties); } } - private DocumentImplementation document = new DocumentImplementation(new HashMap<>()); + private final DocumentImplementation document = new DocumentImplementation(new HashMap<>()); @Test - public void shouldPutAndGetValue() { + void shouldPutAndGetValue() { document.put(KEY, VALUE); assertEquals(VALUE, document.get(KEY)); } @Test - public void shouldRetrieveChildren() { - Map child1 = new HashMap<>(); - Map child2 = new HashMap<>(); - List> children = Arrays.asList(child1, child2); + void shouldRetrieveChildren() { + var children = List.of(Map.of(), Map.of()); document.put(KEY, children); - Stream childrenStream = document.children(KEY, DocumentImplementation::new); + var childrenStream = document.children(KEY, DocumentImplementation::new); assertNotNull(children); assertEquals(2, childrenStream.count()); } @Test - public void shouldRetrieveEmptyStreamForNonExistingChildren() { - Stream children = document.children(KEY, DocumentImplementation::new); + void shouldRetrieveEmptyStreamForNonExistingChildren() { + var children = document.children(KEY, DocumentImplementation::new); assertNotNull(children); assertEquals(0, children.count()); } @Test - public void shouldIncludePropsInToString() { - Map props = new HashMap<>(); - props.put(KEY, VALUE); - DocumentImplementation document = new DocumentImplementation(props); - assertNotNull(document.toString().contains(KEY)); - assertNotNull(document.toString().contains(VALUE)); + void shouldIncludePropsInToString() { + var props = Map.of(KEY, (Object) VALUE); + var document = new DocumentImplementation(props); + assertTrue(document.toString().contains(KEY)); + assertTrue(document.toString().contains(VALUE)); + } + + @Test + void shouldHandleExceptionDuringConstruction() { + Map invalidProperties = + null; // Invalid properties, causing NullPointerException + + // Throw null pointer exception + assertThrows( + NullPointerException.class, + () -> { + // Attempt to construct a document with invalid properties + new DocumentImplementation(invalidProperties); + }); + } + + @Test + void shouldPutAndGetNestedDocument() { + // Creating a nested document + DocumentImplementation nestedDocument = new DocumentImplementation(new HashMap<>()); + nestedDocument.put("nestedKey", "nestedValue"); + + document.put("nested", nestedDocument); + + // Retrieving the nested document + DocumentImplementation retrievedNestedDocument = + (DocumentImplementation) document.get("nested"); + + assertNotNull(retrievedNestedDocument); + assertEquals("nestedValue", retrievedNestedDocument.get("nestedKey")); } + @Test + void shouldUpdateExistingValue() { + // Arrange + final String key = "key"; + final String originalValue = "originalValue"; + final String updatedValue = "updatedValue"; + + // Initializing the value + document.put(key, originalValue); + + // Verifying that the initial value is retrieved correctly + assertEquals(originalValue, document.get(key)); + + // Updating the value + document.put(key, updatedValue); + + // Verifying that the updated value is retrieved correctly + assertEquals(updatedValue, document.get(key)); + } } diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java index 0546be523f67..16dcba0db37f 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -22,16 +24,21 @@ */ package com.iluwatar.abstractdocument; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * Simple App test - */ -public class AppTest { +/** Simple App test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ @Test - public void shouldExecuteAppWithoutException() { - App.main(null); + void shouldExecuteAppWithoutException() { + assertDoesNotThrow(() -> App.main(null)); } - } diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java index 891e5a45763e..fc29dea45c43 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

+ * Copyright © 2014-2022 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 @@ -22,24 +24,17 @@ */ package com.iluwatar.abstractdocument; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.abstractdocument.domain.Car; -import com.iluwatar.abstractdocument.domain.HasModel; -import com.iluwatar.abstractdocument.domain.HasParts; -import com.iluwatar.abstractdocument.domain.HasPrice; -import com.iluwatar.abstractdocument.domain.HasType; import com.iluwatar.abstractdocument.domain.Part; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.HashMap; +import com.iluwatar.abstractdocument.domain.enums.Property; +import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Test for Part and Car - */ -public class DomainTest { +/** Test for Part and Car */ +class DomainTest { private static final String TEST_PART_TYPE = "test-part-type"; private static final String TEST_PART_MODEL = "test-part-model"; @@ -49,29 +44,28 @@ public class DomainTest { private static final long TEST_CAR_PRICE = 1L; @Test - public void shouldConstructPart() { - Map partProperties = new HashMap<>(); - partProperties.put(HasType.PROPERTY, TEST_PART_TYPE); - partProperties.put(HasModel.PROPERTY, TEST_PART_MODEL); - partProperties.put(HasPrice.PROPERTY, TEST_PART_PRICE); - Part part = new Part(partProperties); - - assertEquals(TEST_PART_TYPE, part.getType().get()); - assertEquals(TEST_PART_MODEL, part.getModel().get()); - assertEquals(TEST_PART_PRICE, part.getPrice().get()); + void shouldConstructPart() { + var partProperties = + Map.of( + Property.TYPE.toString(), TEST_PART_TYPE, + Property.MODEL.toString(), TEST_PART_MODEL, + Property.PRICE.toString(), (Object) TEST_PART_PRICE); + var part = new Part(partProperties); + assertEquals(TEST_PART_TYPE, part.getType().orElseThrow()); + assertEquals(TEST_PART_MODEL, part.getModel().orElseThrow()); + assertEquals(TEST_PART_PRICE, part.getPrice().orElseThrow()); } @Test - public void shouldConstructCar() { - Map carProperties = new HashMap<>(); - carProperties.put(HasModel.PROPERTY, TEST_CAR_MODEL); - carProperties.put(HasPrice.PROPERTY, TEST_CAR_PRICE); - carProperties.put(HasParts.PROPERTY, Arrays.asList(new HashMap<>(), new HashMap<>())); - Car car = new Car(carProperties); - - assertEquals(TEST_CAR_MODEL, car.getModel().get()); - assertEquals(TEST_CAR_PRICE, car.getPrice().get()); + void shouldConstructCar() { + var carProperties = + Map.of( + Property.MODEL.toString(), TEST_CAR_MODEL, + Property.PRICE.toString(), TEST_CAR_PRICE, + Property.PARTS.toString(), List.of(Map.of(), Map.of())); + var car = new Car(carProperties); + assertEquals(TEST_CAR_MODEL, car.getModel().orElseThrow()); + assertEquals(TEST_CAR_PRICE, car.getPrice().orElseThrow()); assertEquals(2, car.getParts().count()); } - } diff --git a/abstract-factory/README.md b/abstract-factory/README.md index 0bf86dfa6a91..ee9823a39a5f 100644 --- a/abstract-factory/README.md +++ b/abstract-factory/README.md @@ -1,26 +1,32 @@ --- -layout: pattern -title: Abstract Factory -folder: abstract-factory -permalink: /patterns/abstract-factory/ -categories: Creational -tags: - - Java - - Gang Of Four - - Difficulty-Intermediate +title: "Abstract Factory Pattern in Java: Mastering Object Creation Elegantly" +shortTitle: Abstract Factory +description: "Learn the Abstract Factory pattern in Java with real-world examples, class diagrams, and tutorials. Understand its intent, applicability, benefits, and known uses to enhance your design pattern knowledge." +category: Creational +language: en +tag: + - Abstraction + - Decoupling + - Gang of Four + - Instantiation + - Polymorphism --- ## Also known as -Kit -## Intent -Provide an interface for creating families of related or dependent -objects without specifying their concrete classes. +* Kit -## Explanation -Real world example +## Intent of Abstract Factory Design Pattern -> 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. +The Abstract Factory pattern in Java provides an interface for creating families of related or dependent objects without specifying their concrete classes, enhancing modularity and flexibility in software design. + +## Detailed Explanation of Abstract Factory Pattern with Real-World Examples + +Real-world example + +> Imagine a furniture company that uses the Abstract Factory pattern in Java to produce various styles of furniture: modern, Victorian, and rustic. Each style includes products like chairs, tables, and sofas. To ensure consistency within each style, the company uses an Abstract Factory pattern. +> +> In this scenario, the Abstract Factory is an interface for creating families of related furniture objects (chairs, tables, sofas). Each concrete factory (ModernFurnitureFactory, VictorianFurnitureFactory, RusticFurnitureFactory) implements the Abstract Factory interface and creates a set of products that match the specific style. This way, clients can create a whole set of modern or Victorian furniture without worrying about the details of their instantiation. This maintains a consistent style and allows easy swapping of one style of furniture for another. In plain words @@ -30,170 +36,192 @@ 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** +Class diagram + +![Abstract Factory class diagram](./etc/abstract-factory.urm.png "Abstract Factory class diagram") + +## Programmatic Example of Abstract Factory in Java -Translating the kingdom example above. First of all we have some interfaces and implementation for the objects in the kingdom +To create a kingdom using the Abstract Factory pattern in Java, we need objects with a common theme. The elven kingdom needs an elven king, elven castle, and elven army whereas the orcish kingdom needs an orcish king, orcish castle, and orcish army. There is a dependency between the objects in the kingdom. + +Translating the kingdom example above. First of all, we have some interfaces and implementation for the objects in the kingdom. ```java public interface Castle { - String getDescription(); + String getDescription(); } + public interface King { - String getDescription(); + String getDescription(); } + public interface Army { - String getDescription(); + String getDescription(); } // Elven implementations -> public class ElfCastle implements Castle { - static final String DESCRIPTION = "This is the Elven castle!"; - @Override - public String getDescription() { - return DESCRIPTION; - } + 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; - } + 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; - } -} + static final String DESCRIPTION = "This is the elven Army!"; -// Orcish implementations similarly... + @Override + public String getDescription() { + return DESCRIPTION; + } +} +// Orcish implementations similarly -> ... ``` -Then we have the abstraction and implementations for the kingdom factory +Then we have the abstraction and implementations for the kingdom factory. ```java public interface KingdomFactory { - Castle createCastle(); - King createKing(); - Army createArmy(); + 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(); - } -} -``` + @Override + public Castle createCastle() { + return new ElfCastle(); + } -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. + @Override + public King createKing() { + return new ElfKing(); + } -```java -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! + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +// Orcish implementations similarly -> ... ``` -Now, we can design a factory for our different kingdom factories. In this example, we created FactoryMaker, responsible for returning an instance of either ElfKingdomFactory or OrcKingdomFactory. -The client can use FactoryMaker to create the desired concrete factory which, in turn, will produce different concrete objects (Army, King, Castle). -In this example, we also used an enum to parameterize which type of kingdom factory the client will ask for. +Now, we can design a factory for our different kingdom factories. In this example, we created `FactoryMaker`, responsible for returning an instance of either `ElfKingdomFactory` or `OrcKingdomFactory`. The client can use `FactoryMaker` to create the desired concrete factory which, in turn, will produce different concrete objects (derived from `Army`, `King`, `Castle`). In this example, we also used an enum to parameterize which type of kingdom factory the client will ask for. ```java public static class FactoryMaker { - public enum KingdomType { - ELF, ORC - } - - public static KingdomFactory makeFactory(KingdomType type) { - switch (type) { - case ELF: - return new ElfKingdomFactory(); - case ORC: - return new OrcKingdomFactory(); - default: - throw new IllegalArgumentException("KingdomType not supported."); + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + }; } - } } +``` -public static void main(String[] args) { - App app = new App(); +Here is the main function of our example application: - LOGGER.info("Elf Kingdom"); - app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); - LOGGER.info(app.getArmy().getDescription()); - LOGGER.info(app.getCastle().getDescription()); - LOGGER.info(app.getKing().getDescription()); +```java +LOGGER.info("elf kingdom"); +createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); +LOGGER.info(kingdom.getArmy().getDescription()); +LOGGER.info(kingdom.getCastle().getDescription()); +LOGGER.info(kingdom.getKing().getDescription()); + +LOGGER.info("orc kingdom"); +createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); +LOGGER.info(kingdom.getArmy().getDescription()); +LOGGER.info(kingdom.getCastle().getDescription()); +LOGGER.info(kingdom.getKing().getDescription()); +``` + +The program output: - LOGGER.info("Orc Kingdom"); - app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); - -- similar use of the orc factory -} ``` +07:35:46.340 [main] INFO com.iluwatar.abstractfactory.App -- elf kingdom +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven army! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven castle! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven king! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- orc kingdom +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc army! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc castle! +07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc king! +``` + +## When to Use the Abstract Factory Pattern in Java + +Use the Abstract Factory pattern in Java when: +* The system should be independent of how its products are created, composed, and represented. +* You need to configure the system with one of multiple families of products. +* A family of related product objects must be used together, enforcing consistency. +* You want to provide a class library of products, exposing only their interfaces, not their implementations. +* The lifetime of dependencies is shorter than the consumer's lifetime. +* Dependencies need to be constructed using runtime values or parameters. +* You need to choose which product to use from a family at runtime. +* Adding new products or families should not require changes to existing code. -## Applicability -Use the Abstract Factory pattern when +## Abstract Factory Pattern Java Tutorials -* a system should be independent of how its products are created, composed and represented -* a system should be configured with one of multiple families of products -* a family of related product objects is designed to be used together, and you need to enforce this constraint -* you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations -* the lifetime of the dependency is conceptually shorter than the lifetime of the consumer. -* you need a run-time value to construct a particular dependency -* you want to decide which product to call from a family at runtime. -* you need to supply one or more parameters only known at run-time before you can resolve a dependency. +* [Abstract Factory Design Pattern in Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/abstract-factory-design-pattern-in-java) +* [Abstract Factory(Refactoring Guru)](https://refactoring.guru/design-patterns/abstract-factory) -## Use Cases: +## Benefits and Trade-offs of Abstract Factory Pattern -* Selecting to call the appropriate implementation of FileSystemAcmeService or DatabaseAcmeService or NetworkAcmeService at runtime. -* Unit test case writing becomes much easier +Benefits: -## Consequences: +* Flexibility: Easily switch between product families without code modifications. -* Dependency injection in java hides the service class dependencies that can lead to runtime errors that would have been caught at compile time. +* Decoupling: Client code only interacts with abstract interfaces, promoting portability and maintainability. +* Reusability: Abstract factories and products facilitate component reuse across projects. -## Tutorial -* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) +* Maintainability: Changes to individual product families are localized, simplifying updates. -## Presentations +Trade-offs: -* [Abstract Factory Pattern](etc/presentation.html) +* Complexity: Defining abstract interfaces and concrete factories adds initial overhead. +* Indirectness: Client code interacts with products indirectly through factories, potentially reducing transparency. -## Real world examples +## Real-World Applications of Abstract Factory Pattern in Java +* Java Swing's `LookAndFeel` classes for providing different look-and-feel options. +* Various implementations in the Java Abstract Window Toolkit (AWT) for creating different GUI components. * [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) * [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) * [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) -## Credits +## Related Java Design Patterns + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Abstract Factory uses Factory Methods to create products. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Abstract Factory classes are often implemented as Singletons. +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): Similar to Abstract Factory but focuses on configuring and managing a set of related objects in a flexible way. + +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Design Patterns in Java](https://amzn.to/3Syw0vC) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3HWNf4U) diff --git a/abstract-factory/etc/abstract-factory.urm.png b/abstract-factory/etc/abstract-factory.urm.png new file mode 100644 index 000000000000..836858a2c652 Binary files /dev/null and b/abstract-factory/etc/abstract-factory.urm.png differ diff --git a/abstract-factory/etc/abstract-factory.urm.puml b/abstract-factory/etc/abstract-factory.urm.puml new file mode 100644 index 000000000000..999091ef54f6 --- /dev/null +++ b/abstract-factory/etc/abstract-factory.urm.puml @@ -0,0 +1,101 @@ +@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) + } + class FactoryMaker { + + FactoryMaker() + + makeFactory(type : KingdomType) : KingdomFactory {static} + } + enum KingdomType { + + ELF {static} + + ORC {static} + + valueOf(name : String) : KingdomType {static} + + values() : KingdomType[] {static} + } + 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 + } +} +KingdomType ..+ FactoryMaker +App --> "-castle" Castle +FactoryMaker ..+ App +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/diagram1.png b/abstract-factory/etc/diagram1.png deleted file mode 100644 index e9c3c84c212d..000000000000 Binary files a/abstract-factory/etc/diagram1.png and /dev/null differ diff --git a/abstract-factory/etc/diagram2.png b/abstract-factory/etc/diagram2.png deleted file mode 100644 index 2ab52453533f..000000000000 Binary files a/abstract-factory/etc/diagram2.png and /dev/null differ diff --git a/abstract-factory/etc/presentation.html b/abstract-factory/etc/presentation.html deleted file mode 100644 index 9e549faf8069..000000000000 --- a/abstract-factory/etc/presentation.html +++ /dev/null @@ -1,190 +0,0 @@ - - - - - Design Patterns - Abstract Factory Presentation - - - - - - - - - \ No newline at end of file diff --git a/abstract-factory/pom.xml b/abstract-factory/pom.xml index 6d94e70ceab5..60fbf72eff54 100644 --- a/abstract-factory/pom.xml +++ b/abstract-factory/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT abstract-factory - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,4 +48,25 @@ test + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.abstractfactory.App + + + + + + + + diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java index 4d6043abc007..798cbe4fd118 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,126 +24,63 @@ */ package com.iluwatar.abstractfactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.iluwatar.abstractfactory.App.FactoryMaker.KingdomType; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; /** - * - * The Abstract Factory pattern provides a way to encapsulate a group of individual factories that have a common theme - * without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of - * the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part - * of the theme. The client does not know (or care) which concrete objects it gets from each of these internal - * factories, since it uses only the generic interfaces of their products. This pattern separates the details of - * implementation of a set of objects from their general usage and relies on object composition, as object creation is - * implemented in methods exposed in the factory interface. - *

- * The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) and its implementations ( - * {@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses both concrete implementations to create a - * king, a castle and an army. - * + * The Abstract Factory pattern provides a way to encapsulate a group of individual factories that + * have a common theme without specifying their concrete classes. In normal usage, the client + * software creates a concrete implementation of the abstract factory and then uses the generic + * interface of the factory to create the concrete objects that are part of the theme. The client + * does not know (or care) which concrete objects it gets from each of these internal factories, + * since it uses only the generic interfaces of their products. This pattern separates the details + * of implementation of a set of objects from their general usage and relies on object composition, + * as object creation is implemented in methods exposed in the factory interface. + * + *

The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) + * and its implementations ( {@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses + * both concrete implementations to create a king, a castle, and an army. */ -public class App { +@Slf4j +@Getter +public class App implements Runnable { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - private King king; - private Castle castle; - private Army army; + private final Kingdom kingdom = new Kingdom(); /** - * Creates kingdom + * Program entry point. + * + * @param args command line args */ - public void createKingdom(final KingdomFactory factory) { - setKing(factory.createKing()); - setCastle(factory.createCastle()); - setArmy(factory.createArmy()); - } - - King getKing(final KingdomFactory factory) { - return factory.createKing(); - } - - public King getKing() { - return king; - } - - private void setKing(final King king) { - this.king = king; - } - - Castle getCastle(final KingdomFactory factory) { - return factory.createCastle(); - } - - public Castle getCastle() { - return castle; - } - - private void setCastle(final Castle castle) { - this.castle = castle; - } - - Army getArmy(final KingdomFactory factory) { - return factory.createArmy(); - } - - public Army getArmy() { - return army; + public static void main(String[] args) { + var app = new App(); + app.run(); } - private void setArmy(final Army army) { - this.army = army; + @Override + public void run() { + LOGGER.info("elf kingdom"); + createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); + LOGGER.info(kingdom.getArmy().getDescription()); + LOGGER.info(kingdom.getCastle().getDescription()); + LOGGER.info(kingdom.getKing().getDescription()); + + LOGGER.info("orc kingdom"); + createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); + LOGGER.info(kingdom.getArmy().getDescription()); + LOGGER.info(kingdom.getCastle().getDescription()); + LOGGER.info(kingdom.getKing().getDescription()); } /** - * The factory of kingdom factories. + * Creates kingdom. + * + * @param kingdomType type of Kingdom */ - public static class FactoryMaker { - - /** - * Enumeration for the different types of Kingdoms. - */ - public enum KingdomType { - ELF, ORC - } - - /** - * The factory method to create KingdomFactory concrete objects. - */ - public static KingdomFactory makeFactory(KingdomType type) { - switch (type) { - case ELF: - return new ElfKingdomFactory(); - case ORC: - return new OrcKingdomFactory(); - default: - throw new IllegalArgumentException("KingdomType not supported."); - } - } - } - - /** - * Program entry point. - * - * @param args - * command line args - */ - public static void main(String[] args) { - - App app = new App(); - - LOGGER.info("Elf Kingdom"); - app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); - LOGGER.info(app.getArmy().getDescription()); - LOGGER.info(app.getCastle().getDescription()); - LOGGER.info(app.getKing().getDescription()); - - LOGGER.info("Orc Kingdom"); - app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); - LOGGER.info(app.getArmy().getDescription()); - LOGGER.info(app.getCastle().getDescription()); - LOGGER.info(app.getKing().getDescription()); + public void createKingdom(final Kingdom.FactoryMaker.KingdomType kingdomType) { + final KingdomFactory kingdomFactory = Kingdom.FactoryMaker.makeFactory(kingdomType); + kingdom.setKing(kingdomFactory.createKing()); + kingdom.setCastle(kingdomFactory.createCastle()); + kingdom.setArmy(kingdomFactory.createArmy()); } -} \ No newline at end of file +} diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java index 3d107dd3479e..78c75323f1c0 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * - * Army interface - * - */ +/** Army interface. */ public interface Army { String getDescription(); diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java index 837952d0d364..ee1e16f3cd3f 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * - * Castle interface - * - */ +/** Castle interface. */ public interface Castle { String getDescription(); diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java index f9687073df29..d7e46c1456f0 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,10 @@ */ package com.iluwatar.abstractfactory; -/** - * - * ElfArmy - * - */ +/** ElfArmy. */ public class ElfArmy implements Army { - static final String DESCRIPTION = "This is the Elven Army!"; + static final String DESCRIPTION = "This is the elven army!"; @Override public String getDescription() { diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java index 108bdc8d315a..136afb11fd23 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,10 @@ */ package com.iluwatar.abstractfactory; -/** - * - * ElfCastle - * - */ +/** ElfCastle. */ public class ElfCastle implements Castle { - static final String DESCRIPTION = "This is the Elven castle!"; + static final String DESCRIPTION = "This is the elven castle!"; @Override public String getDescription() { diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java index f6e400bc0d8c..9b0d3a6f1a77 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,10 @@ */ package com.iluwatar.abstractfactory; -/** - * - * ElfKing - * - */ +/** ElfKing. */ public class ElfKing implements King { - static final String DESCRIPTION = "This is the Elven king!"; + static final String DESCRIPTION = "This is the elven king!"; @Override public String getDescription() { diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java index 31cfddb70ff8..b09a2f47c252 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,23 +24,21 @@ */ package com.iluwatar.abstractfactory; -/** - * - * ElfKingdomFactory concrete factory. - * - */ +/** ElfKingdomFactory concrete factory. */ public class ElfKingdomFactory implements KingdomFactory { + @Override public Castle createCastle() { return new ElfCastle(); } + @Override public King createKing() { return new ElfKing(); } + @Override public Army createArmy() { return new ElfArmy(); } - } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java index bffc994d24cb..9f65ed434577 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * - * King interface - * - */ +/** King interface. */ public interface King { String getDescription(); diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Kingdom.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Kingdom.java new file mode 100644 index 000000000000..d1f85a6a4812 --- /dev/null +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Kingdom.java @@ -0,0 +1,56 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.abstractfactory; + +import lombok.Getter; +import lombok.Setter; + +/** Helper class to manufacture {@link KingdomFactory} beans. */ +@Getter +@Setter +public class Kingdom { + + private King king; + private Castle castle; + private Army army; + + /** The factory of kingdom factories. */ + public static class FactoryMaker { + + /** Enumeration for the different types of Kingdoms. */ + public enum KingdomType { + ELF, + ORC + } + + /** The factory method to create KingdomFactory concrete objects. */ + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + }; + } + } +} diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java index fb3434fae136..199c6697dcaa 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * - * KingdomFactory factory interface. - * - */ +/** KingdomFactory factory interface. */ public interface KingdomFactory { Castle createCastle(); @@ -34,5 +32,4 @@ public interface KingdomFactory { King createKing(); Army createArmy(); - } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java index 31552f4301db..31ed6896d921 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,10 @@ */ package com.iluwatar.abstractfactory; -/** - * - * OrcArmy - * - */ +/** OrcArmy. */ public class OrcArmy implements Army { - static final String DESCRIPTION = "This is the Orc Army!"; + static final String DESCRIPTION = "This is the orc army!"; @Override public String getDescription() { diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java index e72da4a77b50..bdae5709a97c 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,10 @@ */ package com.iluwatar.abstractfactory; -/** - * - * OrcCastle - * - */ +/** OrcCastle. */ public class OrcCastle implements Castle { - static final String DESCRIPTION = "This is the Orc castle!"; + static final String DESCRIPTION = "This is the orc castle!"; @Override public String getDescription() { diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java index f48115f89d3a..7f106d45a01d 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,10 @@ */ package com.iluwatar.abstractfactory; -/** - * - * OrcKing - * - */ +/** OrcKing. */ public class OrcKing implements King { - static final String DESCRIPTION = "This is the Orc king!"; + static final String DESCRIPTION = "This is the orc king!"; @Override public String getDescription() { diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java index 5b2ba3a30fc9..82d258570460 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,20 @@ */ package com.iluwatar.abstractfactory; -/** - * - * OrcKingdomFactory concrete factory. - * - */ +/** OrcKingdomFactory concrete factory. */ public class OrcKingdomFactory implements KingdomFactory { + @Override public Castle createCastle() { return new OrcCastle(); } + @Override public King createKing() { return new OrcKing(); } + @Override public Army createArmy() { return new OrcArmy(); } diff --git a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java index 5940da6c1af3..b5dde940c464 100644 --- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java +++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,63 +27,66 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import com.iluwatar.abstractfactory.App.FactoryMaker; -import com.iluwatar.abstractfactory.App.FactoryMaker.KingdomType; - -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Test for abstract factory - */ -public class AbstractFactoryTest { +/** Tests for abstract factory. */ +class AbstractFactoryTest { - private App app = new App(); - private KingdomFactory elfFactory; - private KingdomFactory orcFactory; - - @BeforeEach - public void setUp() { - elfFactory = FactoryMaker.makeFactory(KingdomType.ELF); - orcFactory = FactoryMaker.makeFactory(KingdomType.ORC); - } + private final App app = new App(); @Test - public void king() { - final King elfKing = app.getKing(elfFactory); + void verifyKingCreation() { + app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); + final var kingdom = app.getKingdom(); + + final var elfKing = kingdom.getKing(); assertTrue(elfKing instanceof ElfKing); assertEquals(ElfKing.DESCRIPTION, elfKing.getDescription()); - final King orcKing = app.getKing(orcFactory); + + app.createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); + final var orcKing = kingdom.getKing(); assertTrue(orcKing instanceof OrcKing); assertEquals(OrcKing.DESCRIPTION, orcKing.getDescription()); } @Test - public void castle() { - final Castle elfCastle = app.getCastle(elfFactory); + void verifyCastleCreation() { + app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); + final var kingdom = app.getKingdom(); + + final var elfCastle = kingdom.getCastle(); assertTrue(elfCastle instanceof ElfCastle); assertEquals(ElfCastle.DESCRIPTION, elfCastle.getDescription()); - final Castle orcCastle = app.getCastle(orcFactory); + + app.createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); + final var orcCastle = kingdom.getCastle(); assertTrue(orcCastle instanceof OrcCastle); assertEquals(OrcCastle.DESCRIPTION, orcCastle.getDescription()); } @Test - public void army() { - final Army elfArmy = app.getArmy(elfFactory); + void verifyArmyCreation() { + app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); + final var kingdom = app.getKingdom(); + + final var elfArmy = kingdom.getArmy(); assertTrue(elfArmy instanceof ElfArmy); assertEquals(ElfArmy.DESCRIPTION, elfArmy.getDescription()); - final Army orcArmy = app.getArmy(orcFactory); + + app.createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); + final var orcArmy = kingdom.getArmy(); assertTrue(orcArmy instanceof OrcArmy); assertEquals(OrcArmy.DESCRIPTION, orcArmy.getDescription()); } @Test - public void createElfKingdom() { - app.createKingdom(elfFactory); - final King king = app.getKing(); - final Castle castle = app.getCastle(); - final Army army = app.getArmy(); + void verifyElfKingdomCreation() { + app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF); + final var kingdom = app.getKingdom(); + + final var king = kingdom.getKing(); + final var castle = kingdom.getCastle(); + final var army = kingdom.getArmy(); assertTrue(king instanceof ElfKing); assertEquals(ElfKing.DESCRIPTION, king.getDescription()); assertTrue(castle instanceof ElfCastle); @@ -91,11 +96,13 @@ public void createElfKingdom() { } @Test - public void createOrcKingdom() { - app.createKingdom(orcFactory); - final King king = app.getKing(); - final Castle castle = app.getCastle(); - final Army army = app.getArmy(); + void verifyOrcKingdomCreation() { + app.createKingdom(Kingdom.FactoryMaker.KingdomType.ORC); + final var kingdom = app.getKingdom(); + + final var king = kingdom.getKing(); + final var castle = kingdom.getCastle(); + final var army = kingdom.getArmy(); assertTrue(king instanceof OrcKing); assertEquals(OrcKing.DESCRIPTION, king.getDescription()); assertTrue(castle instanceof OrcCastle); diff --git a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java index 80c2815dcc00..9f53691a594d 100644 --- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java +++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,16 @@ */ package com.iluwatar.abstractfactory; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -import java.io.IOException; +/** Check whether the execution of the main method in {@link App} throws an exception. */ +class AppTest { -/** - * Tests that Abstract Factory example runs without errors. - */ -public class AppTest { @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/active-object/README.md b/active-object/README.md new file mode 100644 index 000000000000..a804ce9e632b --- /dev/null +++ b/active-object/README.md @@ -0,0 +1,222 @@ +--- +title: "Active Object Pattern in Java: Achieving Efficient Asynchronous Processing" +shortTitle: Active Object +description: "Learn about the Active Object design pattern in Java. This guide covers asynchronous behavior, concurrency, and practical examples to enhance your Java applications' performance." +category: Concurrency +language: en +tag: + - Asynchronous + - Decoupling + - Messaging + - Synchronization + - Thread management +--- + +## Intent of Active Object Design Pattern + +The Active Object pattern provides a reliable method for asynchronous processing in Java, ensuring responsive applications and efficient thread management. It achieves this by encapsulating tasks within objects that have their own thread and message queue. This separation keeps the main thread responsive and avoids issues like direct thread manipulation or shared state access. + +## Detailed Explanation of Active Object Pattern with Real-World Examples + +Real-world example + +> Imagine a busy restaurant where customers place orders with waiters. Instead of the waiters going to the kitchen to prepare the food themselves, they write the orders on slips and hand them to a dispatcher. The dispatcher manages a pool of chefs who prepare the meals asynchronously. Once a chef is free, they pick up the next order from the queue, prepare the dish, and notify the waiter when it's ready for serving. +> +> In this analogy, the waiters represent the client threads, the dispatcher represents the scheduler, and the chefs represent the method execution in separate threads. This setup allows the waiters to continue taking orders without being blocked by the food preparation process, much like the Active Object pattern decouples method invocation from execution to enhance concurrency. + +In plain words + +> The Active Object pattern decouples method execution from method invocation to improve concurrency and responsiveness in multithreaded applications. + +Wikipedia says + +> The active object design pattern decouples method execution from method invocation for objects that each reside in their own thread of control.[1] The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests. +> +> The pattern consists of six elements: +> +> * A proxy, which provides an interface towards clients with publicly accessible methods. +> * An interface which defines the method request on an active object. +> * A list of pending requests from clients. +> * A scheduler, which decides which request to execute next. +> * The implementation of the active object method. +> * A callback or variable for the client to receive the result. + +Sequence diagram + +![Active Object sequence diagram](./etc/active-object-sequence-diagram.png) + + +## Programmatic Example of Active Object in Java + +This section explains how the Active Object design pattern works in Java, highlighting its use in asynchronous task management and concurrency control. + +The Orcs are known for their wildness and untameable soul. It seems like they have their own thread of control based on previous behavior. To implement a creature that has its own thread of control mechanism and expose its API only and not the execution itself, we can use the Active Object pattern. + +```java +public abstract class ActiveCreature { + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!", name()); + logger.info("{} has finished eating!", name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.", name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +We can see that any class that will extend the `ActiveCreature` class will have its own thread of control to invoke and execute methods. + +For example, the `Orc` class: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } +} +``` + +Now, we can create multiple creatures such as orcs, tell them to eat and roam, and they will execute it on their own thread of control: + +```java +public class App implements Runnable { + + private static final Logger logger = LoggerFactory.getLogger(App.class.getName()); + + private static final int NUM_CREATURES = 3; + + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + List creatures = new ArrayList<>(); + try { + for (int i = 0; i < NUM_CREATURES; i++) { + creatures.add(new Orc(Orc.class.getSimpleName() + i)); + creatures.get(i).eat(); + creatures.get(i).roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + Thread.currentThread().interrupt(); + } finally { + for (int i = 0; i < NUM_CREATURES; i++) { + creatures.get(i).kill(0); + } + } + } +} +``` + +Program output: + +``` +09:00:02.501 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 is eating! +09:00:02.501 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 is eating! +09:00:02.501 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 is eating! +09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has finished eating! +09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has finished eating! +09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has started to roam in the wastelands. +09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has finished eating! +09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has started to roam in the wastelands. +09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has started to roam in the wastelands. +``` + +## When to Use the Active Object Pattern in Java + +Use the Active Object pattern in Java when: + +* when you need to handle asynchronous tasks without blocking the main thread, ensuring better performance and responsiveness. +* When you need to interact with external resources asynchronously. +* When you want to improve the responsiveness of your application. +* When you need to manage concurrent tasks in a modular and maintainable way. + +## Active Object Pattern Java Tutorials + +* [Android and Java Concurrency: The Active Object Pattern(Douglas Schmidt)](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) + +## Real-World Applications of Active Object Pattern in Java + +* Real-time trading systems where transaction requests are handled asynchronously. +* GUIs where long-running tasks are executed in the background without freezing the user interface. +* Game programming to handle concurrent updates to game state or AI computations. + +## Benefits and Trade-offs of Active Object Pattern + +Discover the benefits and trade-offs of using the Active Object pattern in Java, including improved thread safety and potential overhead concerns. + +Benefits: + +* Improves responsiveness of the main thread. +* Encapsulates concurrency concerns within objects. +* Promotes better code organization and maintainability. +* Provides thread safety and avoids shared state access problems. + +Trade-offs: + +* Introduces additional overhead due to message passing and thread management. +* May not be suitable for all types of concurrency problems. + +## Related Java Design Patterns + +* [Command](https://java-design-patterns.com/patterns/command/): Encapsulates a request as an object, similarly to how the Active Object pattern encapsulates method calls. +* [Promise](https://java-design-patterns.com/patterns/promise/): Provides a means to retrieve the result of an asynchronous method call, often used in conjunction with Active Object. +* [Proxy](https://java-design-patterns.com/patterns/proxy/): The Active Object pattern can use a proxy to handle method invocations asynchronously. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object Software](https://amzn.to/3HYqrBE) +* [Concurrent Programming in Java: Design Principles and Patterns](https://amzn.to/498SRVq) +* [Java Concurrency in Practice](https://amzn.to/4aRMruW) +* [Learning Concurrent Programming in Scala](https://amzn.to/3UE07nV) +* [Pattern Languages of Program Design 3](https://amzn.to/3OI1j61) +* [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) diff --git a/active-object/etc/active-object-sequence-diagram.png b/active-object/etc/active-object-sequence-diagram.png new file mode 100644 index 000000000000..b725d9b07b6d Binary files /dev/null and b/active-object/etc/active-object-sequence-diagram.png differ diff --git a/active-object/etc/active-object.urm.png b/active-object/etc/active-object.urm.png new file mode 100644 index 000000000000..c14f66144ee2 Binary files /dev/null and b/active-object/etc/active-object.urm.png differ diff --git a/active-object/etc/active-object.urm.puml b/active-object/etc/active-object.urm.puml new file mode 100644 index 000000000000..3fc3c8e1e921 --- /dev/null +++ b/active-object/etc/active-object.urm.puml @@ -0,0 +1,25 @@ +@startuml +package com.iluwatar.activeobject { + abstract class ActiveCreature { + - logger : Logger + - name : String + - requests : BlockingQueue + - thread : Thread + + ActiveCreature(name : String) + + eat() + + name() : String + + roam() + } + class App { + - creatures : Integer + - logger : Logger + + App() + + main(args : String[]) {static} + + run() + } + class Orc { + + Orc(name : String) + } +} +Orc --|> ActiveCreature +@enduml \ No newline at end of file diff --git a/active-object/pom.xml b/active-object/pom.xml new file mode 100644 index 000000000000..aa26dbbe2e48 --- /dev/null +++ b/active-object/pom.xml @@ -0,0 +1,72 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + active-object + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.activeobject.App + + + + + + + + + diff --git a/active-object/src/main/java/com/iluwatar/activeobject/ActiveCreature.java b/active-object/src/main/java/com/iluwatar/activeobject/ActiveCreature.java new file mode 100644 index 000000000000..5a440020c0ac --- /dev/null +++ b/active-object/src/main/java/com/iluwatar/activeobject/ActiveCreature.java @@ -0,0 +1,118 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.activeobject; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** ActiveCreature class is the base of the active object example. */ +public abstract class ActiveCreature { + + private static final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; // Thread of execution. + + private int status; // status of the thread of execution. + + /** Constructor and initialization. */ + protected ActiveCreature(String name) { + this.name = name; + this.status = 0; + this.requests = new LinkedBlockingQueue<>(); + thread = + new Thread( + () -> { + boolean infinite = true; + while (infinite) { + try { + requests.take().run(); + } catch (InterruptedException e) { + if (this.status != 0) { + logger.error("Thread was interrupted. --> {}", e.getMessage()); + } + infinite = false; + Thread.currentThread().interrupt(); + } + } + }); + thread.start(); + } + + /** + * Eats the porridge. + * + * @throws InterruptedException due to firing a new Runnable. + */ + public void eat() throws InterruptedException { + requests.put( + () -> { + logger.info("{} is eating!", name()); + logger.info("{} has finished eating!", name()); + }); + } + + /** + * Roam the wastelands. + * + * @throws InterruptedException due to firing a new Runnable. + */ + public void roam() throws InterruptedException { + requests.put(() -> logger.info("{} has started to roam in the wastelands.", name())); + } + + /** + * Returns the name of the creature. + * + * @return the name of the creature. + */ + public String name() { + return this.name; + } + + /** + * Kills the thread of execution. + * + * @param status of the thread of execution. 0 == OK, the rest is logging an error. + */ + public void kill(int status) { + this.status = status; + this.thread.interrupt(); + } + + /** + * Returns the status of the thread of execution. + * + * @return the status of the thread of execution. + */ + public int getStatus() { + return this.status; + } +} diff --git a/active-object/src/main/java/com/iluwatar/activeobject/App.java b/active-object/src/main/java/com/iluwatar/activeobject/App.java new file mode 100644 index 000000000000..ca3a5526ebb8 --- /dev/null +++ b/active-object/src/main/java/com/iluwatar/activeobject/App.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.activeobject; + +import java.util.ArrayList; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Active Object pattern helps to solve synchronization difficulties without using + * 'synchronized' methods. The active object will contain a thread-safe data structure (such as + * BlockingQueue) and use to synchronize method calls by moving the logic of the method into an + * invocator(usually a Runnable) and store it in the DSA. + * + *

In this example, we fire 20 threads to modify a value in the target class. + */ +public class App implements Runnable { + + private static final Logger logger = LoggerFactory.getLogger(App.class.getName()); + + private static final int NUM_CREATURES = 3; + + /** + * Program entry point. + * + * @param args command line arguments. + */ + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + List creatures = new ArrayList<>(); + try { + for (int i = 0; i < NUM_CREATURES; i++) { + creatures.add(new Orc(Orc.class.getSimpleName() + i)); + creatures.get(i).eat(); + creatures.get(i).roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + Thread.currentThread().interrupt(); + } finally { + for (int i = 0; i < NUM_CREATURES; i++) { + creatures.get(i).kill(0); + } + } + } +} diff --git a/active-object/src/main/java/com/iluwatar/activeobject/Orc.java b/active-object/src/main/java/com/iluwatar/activeobject/Orc.java new file mode 100644 index 000000000000..30adde034de5 --- /dev/null +++ b/active-object/src/main/java/com/iluwatar/activeobject/Orc.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.activeobject; + +/** An implementation of the ActiveCreature class. */ +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } +} diff --git a/active-object/src/test/java/com/iluwatar/activeobject/ActiveCreatureTest.java b/active-object/src/test/java/com/iluwatar/activeobject/ActiveCreatureTest.java new file mode 100644 index 000000000000..be79e2fb5527 --- /dev/null +++ b/active-object/src/test/java/com/iluwatar/activeobject/ActiveCreatureTest.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.activeobject; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class ActiveCreatureTest { + + @Test + void executionTest() throws InterruptedException { + ActiveCreature orc = new Orc("orc1"); + assertEquals("orc1", orc.name()); + assertEquals(0, orc.getStatus()); + orc.eat(); + orc.roam(); + orc.kill(0); + } +} diff --git a/active-object/src/test/java/com/iluwatar/activeobject/AppTest.java b/active-object/src/test/java/com/iluwatar/activeobject/AppTest.java new file mode 100644 index 000000000000..559e2a1f58f1 --- /dev/null +++ b/active-object/src/test/java/com/iluwatar/activeobject/AppTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.activeobject; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/actor-model/README.md b/actor-model/README.md new file mode 100644 index 000000000000..be8065ffefef --- /dev/null +++ b/actor-model/README.md @@ -0,0 +1,201 @@ +--- +title: "Actor Model Pattern in Java: Building Concurrent Systems with Elegance" +shortTitle: Actor Model +description: "Explore the Actor Model pattern in Java with real-world examples and practical implementation. Learn how to build scalable, message-driven systems using actors, messages, and asynchronous communication." +category: Concurrency +language: en +tag: + - Concurrency + - Messaging + - Isolation + - Asynchronous + - Distributed Systems + - Actor Model +--- + +## Also Known As + +- Message-passing concurrency +- Actor-based concurrency + +--- + +## Intent of Actor Model Pattern + +The Actor Model pattern enables the construction of highly concurrent, distributed, and fault-tolerant systems by using isolated components (actors) that interact exclusively through asynchronous message passing. + +--- + +## Detailed Explanation of Actor Model Pattern with Real-World Examples + +### 📦 Real-world Example + +Imagine a customer service system: +- Each **customer support agent** is an **actor**. +- Customers **send questions (messages)** to agents. +- Each agent handles one request at a time and can **respond asynchronously** without interfering with other agents. + +--- + +### 🧠 In Plain Words + +> "Actors are like independent workers that never share memory and only communicate through messages." + +--- + +### 📖 Wikipedia Says + +> [Actor model](https://en.wikipedia.org/wiki/Actor_model) is a mathematical model of concurrent computation that treats "actors" as the universal primitives of concurrent computation. + +--- + +### 🧹 Architecture Diagram + +![UML Class Diagram](./etc/Actor_Model_UML_Class_Diagram.png) + +--- + +## Programmatic Example of Actor Model Pattern in Java + +### Actor.java + +```java +public abstract class Actor implements Runnable { + + @Setter @Getter private String actorId; + private final BlockingQueue mailbox = new LinkedBlockingQueue<>(); + private volatile boolean active = true; + + + public void send(Message message) { + mailbox.add(message); + } + + public void stop() { + active = false; + } + + @Override + public void run() { + + } + + protected abstract void onReceive(Message message); +} + +``` + +### Message.java + +```java + +@AllArgsConstructor +@Getter +@Setter +public class Message { + private final String content; + private final String senderId; +} +``` + +### ActorSystem.java + +```java +public class ActorSystem { + public void startActor(Actor actor) { + String actorId = "actor-" + idCounter.incrementAndGet(); // Generate a new and unique ID + actor.setActorId(actorId); // assign the actor it's ID + actorRegister.put(actorId, actor); // Register and save the actor with it's ID + executor.submit(actor); // Run the actor in a thread + } + public Actor getActorById(String actorId) { + return actorRegister.get(actorId); // Find by Id + } + + public void shutdown() { + executor.shutdownNow(); // Stop all threads + } +} +``` + +### App.java + +```java +public class App { + public static void main(String[] args) { + ActorSystem system = new ActorSystem(); + Actor srijan = new ExampleActor(system); + Actor ansh = new ExampleActor2(system); + + system.startActor(srijan); + system.startActor(ansh); + ansh.send(new Message("Hello ansh", srijan.getActorId())); + srijan.send(new Message("Hello srijan!", ansh.getActorId())); + + Thread.sleep(1000); // Give time for messages to process + + srijan.stop(); // Stop the actor gracefully + ansh.stop(); + system.shutdown(); // Stop the actor system + } +} +``` + +--- + +## When to Use the Actor Model Pattern in Java + +- When building **concurrent or distributed systems** +- When you want **no shared mutable state** +- When you need **asynchronous, message-driven communication** +- When components should be **isolated and loosely coupled** + +--- + +## Actor Model Pattern Java Tutorials + +- [Baeldung – Akka with Java](https://www.baeldung.com/java-akka) +- [Vaughn Vernon – Reactive Messaging Patterns](https://vaughnvernon.co/?p=1143) + +--- + +## Real-World Applications of Actor Model Pattern in Java + +- [Akka Framework](https://akka.io/) +- [Erlang and Elixir concurrency](https://www.erlang.org/) +- [Microsoft Orleans](https://learn.microsoft.com/en-us/dotnet/orleans/) +- JVM-based game engines and simulators + +--- + +## Benefits and Trade-offs of Actor Model Pattern + +### ✅ Benefits +- High concurrency support +- Easy scaling across threads or machines +- Fault isolation and recovery +- Message ordering within actors + +### ⚠️ Trade-offs +- Harder to debug due to asynchronous behavior +- Slight performance overhead due to message queues +- More complex to design than simple method calls + +--- + +## Related Java Design Patterns + +- [Command Pattern](../command) +- [Mediator Pattern](../mediator) +- [Event-Driven Architecture](../event-driven-architecture) +- [Observer Pattern](../observer) + +--- + +## References and Credits + +- *Programming Erlang*, Joe Armstrong +- *Reactive Design Patterns*, Roland Kuhn +- *The Actor Model in 10 Minutes*, [InfoQ Article](https://www.infoq.com/articles/actor-model/) +- [Akka Documentation](https://doc.akka.io/docs/akka/current/index.html) + diff --git a/actor-model/etc/Actor_Model_UML_Class_Diagram.png b/actor-model/etc/Actor_Model_UML_Class_Diagram.png new file mode 100644 index 000000000000..a4c34d7a75fd Binary files /dev/null and b/actor-model/etc/Actor_Model_UML_Class_Diagram.png differ diff --git a/actor-model/etc/actor-model.urm.puml b/actor-model/etc/actor-model.urm.puml new file mode 100644 index 000000000000..020c1fc735a4 --- /dev/null +++ b/actor-model/etc/actor-model.urm.puml @@ -0,0 +1,35 @@ +@startuml actor-model + +title Actor Model - UML Class Diagram + +class ActorSystem { + +actorOf(actor: Actor): Actor + +shutdown(): void +} + +class Actor { + -mailbox: BlockingQueue + -active: boolean + +send(message: Message): void + +stop(): void + +run(): void + #onReceive(message: Message): void +} + +class ExampleActor { + +onReceive(message: Message): void +} + +class Message { + -content: String + -sender: Actor + +getContent(): String + +getSender(): Actor +} + +ActorSystem --> Actor : creates +Actor <|-- ExampleActor : extends +Actor --> Message : processes +ExampleActor --> Message : uses + +@enduml diff --git a/actor-model/pom.xml b/actor-model/pom.xml new file mode 100644 index 000000000000..76c288829b8d --- /dev/null +++ b/actor-model/pom.xml @@ -0,0 +1,114 @@ + + + + + 4.0.0 + + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + actor-model + Actor Model + + + + + + org.junit + junit-bom + 5.11.0 + pom + import + + + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-launcher + test + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.3.0 + + + jar-with-dependencies + + + + com.iluwatar.actormodel.App + + + + + + make-assembly + package + + single + + + + + + + + + diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/Actor.java b/actor-model/src/main/java/com/iluwatar/actormodel/Actor.java new file mode 100644 index 000000000000..6e2aaccd1937 --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/Actor.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.actormodel; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import lombok.Getter; +import lombok.Setter; + +public abstract class Actor implements Runnable { + + @Setter @Getter private String actorId; + private final BlockingQueue mailbox = new LinkedBlockingQueue<>(); + private volatile boolean active = + true; // always read from main memory and written back to main memory, + + // rather than being cached in a thread's local memory. To make it consistent to all Actors + + public void send(Message message) { + mailbox.add(message); // Add message to queue + } + + public void stop() { + active = false; // Stop the actor loop + } + + @Override + public void run() { + while (active) { + try { + Message message = mailbox.take(); // Wait for a message + onReceive(message); // Process it + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + // Child classes must define what to do with a message + protected abstract void onReceive(Message message); +} diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/ActorSystem.java b/actor-model/src/main/java/com/iluwatar/actormodel/ActorSystem.java new file mode 100644 index 000000000000..db7c21cb6088 --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/ActorSystem.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.actormodel; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +public class ActorSystem { + private final ExecutorService executor = Executors.newCachedThreadPool(); + private final ConcurrentHashMap actorRegister = new ConcurrentHashMap<>(); + private final AtomicInteger idCounter = new AtomicInteger(0); + + public void startActor(Actor actor) { + String actorId = "actor-" + idCounter.incrementAndGet(); // Generate a new and unique ID + actor.setActorId(actorId); // assign the actor it's ID + actorRegister.put(actorId, actor); // Register and save the actor with it's ID + executor.submit(actor); // Run the actor in a thread + } + + public Actor getActorById(String actorId) { + return actorRegister.get(actorId); // Find by Id + } + + public void shutdown() { + executor.shutdownNow(); // Stop all threads + } +} diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/App.java b/actor-model/src/main/java/com/iluwatar/actormodel/App.java new file mode 100644 index 000000000000..79fe79e48a6f --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/App.java @@ -0,0 +1,64 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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. + */ + +/** + * The Actor Model is a design pattern used to handle concurrency in a safe, scalable, and + * message-driven way. + * + *

In the Actor Model: - An **Actor** is an independent unit that has its own state and behavior. + * - Actors **communicate only through messages** — they do not share memory. - An **ActorSystem** + * is responsible for creating, starting, and managing the lifecycle of actors. - Messages are + * delivered asynchronously, and each actor processes them one at a time. + * + *

💡 Key benefits: - No shared memory = no need for complex thread-safety - Easy to scale with + * many actors - Suitable for highly concurrent or distributed systems + * + *

🔍 This example demonstrates the Actor Model: - `ActorSystem` starts two actors: `srijan` and + * `ansh`. - `ExampleActor` and `ExampleActor2` extend the `Actor` class and override the + * `onReceive()` method to handle messages. - Actors communicate using `send()` to pass `Message` + * objects that include the message content and sender's ID. - The actors process messages + * **asynchronously in separate threads**, and we allow a short delay (`Thread.sleep`) to let them + * run. - The system is shut down gracefully at the end. + */ +package com.iluwatar.actormodel; + +public class App { + public static void main(String[] args) throws InterruptedException { + ActorSystem system = new ActorSystem(); + Actor srijan = new ExampleActor(system); + Actor ansh = new ExampleActor2(system); + + system.startActor(srijan); + system.startActor(ansh); + ansh.send(new Message("Hello ansh", srijan.getActorId())); + srijan.send(new Message("Hello srijan!", ansh.getActorId())); + + Thread.sleep(1000); // Give time for messages to process + + srijan.stop(); // Stop the actor gracefully + ansh.stop(); + system.shutdown(); // Stop the actor system + } +} diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor.java b/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor.java new file mode 100644 index 000000000000..fd49325f44bd --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.actormodel; + +import java.util.ArrayList; +import java.util.List; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class ExampleActor extends Actor { + private final ActorSystem actorSystem; + @Getter private final List receivedMessages = new ArrayList<>(); + + public ExampleActor(ActorSystem actorSystem) { + this.actorSystem = actorSystem; + } + + // Logger log = Logger.getLogger(getClass().getName()); + + @Override + protected void onReceive(Message message) { + LOGGER.info( + "[{}]Received : {} from : [{}]", getActorId(), message.getContent(), message.getSenderId()); + Actor sender = actorSystem.getActorById(message.getSenderId()); // sender actor id + // Reply of the message + if (sender != null && !message.getSenderId().equals(getActorId())) { + sender.send(new Message("I got your message ", getActorId())); + } + } +} diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor2.java b/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor2.java new file mode 100644 index 000000000000..037f96716558 --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/ExampleActor2.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.actormodel; + +import java.util.ArrayList; +import java.util.List; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class ExampleActor2 extends Actor { + private final ActorSystem actorSystem; + @Getter private final List receivedMessages = new ArrayList<>(); + + public ExampleActor2(ActorSystem actorSystem) { + this.actorSystem = actorSystem; + } + + @Override + protected void onReceive(Message message) { + receivedMessages.add(message.getContent()); + LOGGER.info("[{}]Received : {}", getActorId(), message.getContent()); + } +} diff --git a/actor-model/src/main/java/com/iluwatar/actormodel/Message.java b/actor-model/src/main/java/com/iluwatar/actormodel/Message.java new file mode 100644 index 000000000000..03ca6e02cac0 --- /dev/null +++ b/actor-model/src/main/java/com/iluwatar/actormodel/Message.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.actormodel; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@AllArgsConstructor +@Getter +public class Message { + private final String content; + private final String senderId; +} diff --git a/actor-model/src/test/java/com/iluwatar/actor/ActorModelTest.java b/actor-model/src/test/java/com/iluwatar/actor/ActorModelTest.java new file mode 100644 index 000000000000..a4a0dee569ab --- /dev/null +++ b/actor-model/src/test/java/com/iluwatar/actor/ActorModelTest.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.actor; + +import static org.junit.jupiter.api.Assertions.*; + +import com.iluwatar.actormodel.ActorSystem; +import com.iluwatar.actormodel.App; +import com.iluwatar.actormodel.ExampleActor; +import com.iluwatar.actormodel.ExampleActor2; +import com.iluwatar.actormodel.Message; +import org.junit.jupiter.api.Test; + +public class ActorModelTest { + @Test + void testMainMethod() throws InterruptedException { + App.main(new String[] {}); + } + + @Test + public void testMessagePassing() throws InterruptedException { + ActorSystem system = new ActorSystem(); + + ExampleActor srijan = new ExampleActor(system); + ExampleActor2 ansh = new ExampleActor2(system); + + system.startActor(srijan); + system.startActor(ansh); + + // Ansh recieves a message from Srijan + ansh.send(new Message("Hello ansh", srijan.getActorId())); + + // Wait briefly to allow async processing + Thread.sleep(200); + + // Check that Srijan received the message + assertTrue( + ansh.getReceivedMessages().contains("Hello ansh"), + "ansh should receive the message from Srijan"); + } +} diff --git a/acyclic-visitor/README.md b/acyclic-visitor/README.md new file mode 100644 index 000000000000..fb57d5681fd4 --- /dev/null +++ b/acyclic-visitor/README.md @@ -0,0 +1,186 @@ +--- +title: "Acyclic Visitor Pattern in Java: Streamlining Object Interactions" +shortTitle: Acyclic Visitor +description: "Learn about the Acyclic Visitor pattern in Java. This guide explains how it decouples operations from object hierarchies, providing examples and real-world applications." +category: Behavioral +language: en +tag: + - Decoupling + - Extensibility + - Interface + - Object composition +--- + +## Intent of Acyclic Visitor Design Pattern + +The Acyclic Visitor pattern in Java decouples operations from an object hierarchy, providing a flexible design for various applications. + +## Detailed Explanation of Acyclic Visitor Pattern with Real-World Examples + +Real-world example + +> An analogous real-world example of the Acyclic Visitor pattern in Java is a museum guide system, demonstrating the practical application of this design pattern. Imagine a museum with various exhibits like paintings, sculptures, and historical artifacts. The museum has different types of guides (audio guide, human guide, virtual reality guide) that provide information about each exhibit. Instead of modifying the exhibits every time a new guide type is introduced, each guide implements an interface to visit different exhibit types. This way, the museum can add new types of guides without altering the existing exhibits, ensuring that the system remains extensible and maintainable without forming any dependency cycles. + +In plain words + +> Acyclic Visitor allows functions to be added to existing class hierarchies without modifying the hierarchies. + +[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) says + +> The Acyclic Visitor pattern allows new functions to be added to existing class hierarchies without affecting those hierarchies, and without creating the dependency cycles that are inherent to the GangOfFour VisitorPattern. + +Sequence diagram + +![Acyclic Visitor sequence diagram](./etc/acyclic-visitor-sequence-diagram.png "Acyclic Visitor sequence diagram") + + +## Programmatic Example of Acyclic Visitor in Java + +In this Java example, we have a hierarchy of modem classes illustrating the Acyclic Visitor pattern. The modems in this hierarchy need to be visited by an external algorithm based on filtering criteria (is it Unix or DOS compatible modem). + +Here's the `Modem` hierarchy. + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + + // Other properties and methods... + + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + + // Other properties and methods... + + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + +Next, we introduce the `ModemVisitor` hierarchy. + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + + // Other properties and methods... + + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + + // Other properties and methods... + + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +Finally, here are the visitors in action. + +```java +public static void main(String[] args) { + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + + var zoom = new Zoom(); + var hayes = new Hayes(); + + hayes.accept(conDos); // Hayes modem with Dos configurator + zoom.accept(conDos); // Zoom modem with Dos configurator + hayes.accept(conUnix); // Hayes modem with Unix configurator + zoom.accept(conUnix); // Zoom modem with Unix configurator +} +``` + +Program output: + +``` +09:15:11.125 [main] INFO com.iluwatar.acyclicvisitor.ConfigureForDosVisitor -- Hayes modem used with Dos configurator. +09:15:11.127 [main] INFO com.iluwatar.acyclicvisitor.ConfigureForDosVisitor -- Zoom modem used with Dos configurator. +09:15:11.127 [main] INFO com.iluwatar.acyclicvisitor.Hayes -- Only HayesVisitor is allowed to visit Hayes modem +09:15:11.127 [main] INFO com.iluwatar.acyclicvisitor.ConfigureForUnixVisitor -- Zoom modem used with Unix configurator. +``` + +## When to Use the Acyclic Visitor Pattern in Java + +This pattern can be used: + +* When you need to add a new function to an existing hierarchy without the need to alter or affect that hierarchy. +* When there are functions that operate upon a hierarchy, but which do not belong in the hierarchy itself. e.g. the ConfigureForDOS / ConfigureForUnix / ConfigureForX issue. +* When you need to perform very different operations on an object depending upon its type. +* When the visited class hierarchy will be frequently extended with new derivatives of the Element class. +* When the recompilation, relinking, retesting or redistribution of the derivatives of Element is very expensive. + +## Acyclic Visitor Pattern Java Tutorials + +* [The Acyclic Visitor Pattern (Code Crafter)](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) + +## Benefits and Trade-offs of Acyclic Visitor Pattern + +Benefits: + +* Extensible: New operations can be added easily without changing the object structure. +* Decoupled: Reduces coupling between the objects and the operations on them. +* No dependency cycles: Ensures acyclic dependencies, improving maintainability and reducing complexity. + +Trade-offs: + +* Increased complexity: Can introduce additional complexity with the need for multiple visitor interfaces. +* Maintenance overhead: Modifying the object hierarchy requires updating all visitors. + +## Related Java Design Patterns + +* [Composite](https://java-design-patterns.com/patterns/composite/): Often used in conjunction with Acyclic Visitor to allow treating individual objects and compositions uniformly. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used alongside to add responsibilities to objects dynamically. +* [Visitor](https://java-design-patterns.com/patterns/visitor/): The Acyclic Visitor pattern is a variation of the Visitor pattern that avoids cyclic dependencies. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) +* [Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML](https://amzn.to/4bOtzwF) +* [Acyclic Visitor (Robert C. Martin)](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor (WikiWikiWeb)](https://wiki.c2.com/?AcyclicVisitor) diff --git a/acyclic-visitor/etc/acyclic-visitor-sequence-diagram.png b/acyclic-visitor/etc/acyclic-visitor-sequence-diagram.png new file mode 100644 index 000000000000..a3c2ba56b89f Binary files /dev/null and b/acyclic-visitor/etc/acyclic-visitor-sequence-diagram.png differ diff --git a/acyclic-visitor/etc/acyclic-visitor.png b/acyclic-visitor/etc/acyclic-visitor.png new file mode 100644 index 000000000000..7b4df13d80f8 Binary files /dev/null and b/acyclic-visitor/etc/acyclic-visitor.png differ diff --git a/acyclic-visitor/etc/acyclic-visitor.urm.puml b/acyclic-visitor/etc/acyclic-visitor.urm.puml new file mode 100644 index 000000000000..e67bbde4407c --- /dev/null +++ b/acyclic-visitor/etc/acyclic-visitor.urm.puml @@ -0,0 +1,53 @@ +@startuml +package com.iluwatar.acyclicvisitor { + interface AllModemVisitor { + } + class App { + + App() + + main(args : String[]) {static} + } + class ConfigureForDosVisitor { + - LOGGER : Logger {static} + + ConfigureForDosVisitor() + + visit(hayes : Hayes) + + visit(zoom : Zoom) + } + class ConfigureForUnixVisitor { + - LOGGER : Logger {static} + + ConfigureForUnixVisitor() + + visit(zoom : Zoom) + } + class Hayes { + - LOGGER : Logger {static} + + Hayes() + + accept(modemVisitor : ModemVisitor) + + toString() : String + } + interface HayesVisitor { + + visit(Hayes) {abstract} + } + abstract class Modem { + + Modem() + + accept(ModemVisitor) {abstract} + } + interface ModemVisitor { + } + class Zoom { + - LOGGER : Logger {static} + + Zoom() + + accept(modemVisitor : ModemVisitor) + + toString() : String + } + interface ZoomVisitor { + + visit(Zoom) {abstract} + } +} +AllModemVisitor --|> ZoomVisitor +AllModemVisitor --|> HayesVisitor +ConfigureForDosVisitor ..|> AllModemVisitor +ConfigureForUnixVisitor ..|> ZoomVisitor +Hayes --|> Modem +HayesVisitor --|> ModemVisitor +Zoom --|> Modem +ZoomVisitor --|> ModemVisitor +@enduml \ No newline at end of file diff --git a/acyclic-visitor/pom.xml b/acyclic-visitor/pom.xml new file mode 100644 index 000000000000..b4f5646b71c0 --- /dev/null +++ b/acyclic-visitor/pom.xml @@ -0,0 +1,77 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + acyclic-visitor + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.acyclicvisitor.App + + + + + + + + + diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java new file mode 100644 index 000000000000..a3b1679a2d9f --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +/** + * All ModemVisitor interface extends all visitor interfaces. This interface provides ease of use + * when a visitor needs to visit all modem types. + */ +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor {} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java new file mode 100644 index 000000000000..3b7c6cd61e4b --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +/** + * The Acyclic Visitor pattern allows new functions to be added to existing class hierarchies + * without affecting those hierarchies, and without creating the dependency cycles that are inherent + * to the GoF Visitor pattern, by making the Visitor base class degenerate + * + *

In this example the visitor base class is {@link ModemVisitor}. The base class of the visited + * hierarchy is {@link Modem} and has two children {@link Hayes} and {@link Zoom} each one having + * its own visitor interface {@link HayesVisitor} and {@link ZoomVisitor} respectively. {@link + * ConfigureForUnixVisitor} and {@link ConfigureForDosVisitor} implement each derivative's visit + * method only if it is required + */ +public class App { + + /** Program's entry point. */ + public static void main(String[] args) { + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + + var zoom = new Zoom(); + var hayes = new Hayes(); + + hayes.accept(conDos); // Hayes modem with Dos configurator + zoom.accept(conDos); // Zoom modem with Dos configurator + hayes.accept(conUnix); // Hayes modem with Unix configurator + zoom.accept(conUnix); // Zoom modem with Unix configurator + } +} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitor.java new file mode 100644 index 000000000000..267a8d66ac45 --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitor.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +import lombok.extern.slf4j.Slf4j; + +/** + * ConfigureForDosVisitor class implements both zoom's and hayes' visit method for Dos manufacturer. + */ +@Slf4j +public class ConfigureForDosVisitor implements AllModemVisitor { + + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java new file mode 100644 index 000000000000..d9fd14f69435 --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +import lombok.extern.slf4j.Slf4j; + +/** + * ConfigureForUnixVisitor class implements zoom's visit method for Unix manufacturer, unlike + * traditional visitor pattern, this class may selectively implement visit for other modems. + */ +@Slf4j +public class ConfigureForUnixVisitor implements ZoomVisitor { + + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java new file mode 100644 index 000000000000..e0b2fcc2b530 --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +import lombok.extern.slf4j.Slf4j; + +/** Hayes class implements its accept method. */ +@Slf4j +public class Hayes implements Modem { + + /** Accepts all visitors but honors only HayesVisitor. */ + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } + + /** Hayes' modem's toString method. */ + @Override + public String toString() { + return "Hayes modem"; + } +} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/HayesVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/HayesVisitor.java new file mode 100644 index 000000000000..aad9b970994f --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/HayesVisitor.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +/** HayesVisitor interface. */ +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Modem.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Modem.java new file mode 100644 index 000000000000..8552574453e5 --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Modem.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +/** //Modem abstract class. converted to an interface */ +public interface Modem { + void accept(ModemVisitor modemVisitor); +} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ModemVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ModemVisitor.java new file mode 100644 index 000000000000..9391a980cd29 --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ModemVisitor.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +/** + * ModemVisitor interface does not contain any visit methods so that it does not depend on the + * visited hierarchy. Each derivative's visit method is declared in its own visitor interface + */ +public interface ModemVisitor { + // Visitor is a degenerate base class for all visitors. +} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java new file mode 100644 index 000000000000..59b50a54a12f --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +import lombok.extern.slf4j.Slf4j; + +/** Zoom class implements its accept method. */ +@Slf4j +public class Zoom implements Modem { + + /** Accepts all visitors but honors only ZoomVisitor. */ + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } + + /** Zoom modem's toString method. */ + @Override + public String toString() { + return "Zoom modem"; + } +} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java new file mode 100644 index 000000000000..5388ded6f735 --- /dev/null +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +/** ZoomVisitor interface. */ +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} diff --git a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/AppTest.java b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/AppTest.java new file mode 100644 index 000000000000..7a21498a63ea --- /dev/null +++ b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/AppTest.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Tests that the Acyclic Visitor example runs without errors. */ +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. + * + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/HayesTest.java b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/HayesTest.java new file mode 100644 index 000000000000..a989d9287921 --- /dev/null +++ b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/HayesTest.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +import org.junit.jupiter.api.Test; + +/** Hayes test class */ +class HayesTest { + + @Test + void testAcceptForDos() { + var hayes = new Hayes(); + var mockVisitor = mock(ConfigureForDosVisitor.class); + + hayes.accept(mockVisitor); + verify((HayesVisitor) mockVisitor).visit(eq(hayes)); + } + + @Test + void testAcceptForUnix() { + var hayes = new Hayes(); + var mockVisitor = mock(ConfigureForUnixVisitor.class); + + hayes.accept(mockVisitor); + + verifyNoMoreInteractions(mockVisitor); + } +} diff --git a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ZoomTest.java b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ZoomTest.java new file mode 100644 index 000000000000..d5fe79965d47 --- /dev/null +++ b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ZoomTest.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.acyclicvisitor; + +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.Test; + +/** Zoom test class */ +class ZoomTest { + + @Test + void testAcceptForDos() { + var zoom = new Zoom(); + var mockVisitor = mock(ConfigureForDosVisitor.class); + + zoom.accept(mockVisitor); + verify((ZoomVisitor) mockVisitor).visit(eq(zoom)); + } + + @Test + void testAcceptForUnix() { + var zoom = new Zoom(); + var mockVisitor = mock(ConfigureForUnixVisitor.class); + + zoom.accept(mockVisitor); + verify((ZoomVisitor) mockVisitor).visit(eq(zoom)); + } +} diff --git a/adapter/README.md b/adapter/README.md index e943baba52fd..489742494709 100644 --- a/adapter/README.md +++ b/adapter/README.md @@ -1,30 +1,31 @@ --- -layout: pattern -title: Adapter -folder: adapter -permalink: /patterns/adapter/ -categories: Structural -tags: - - Java - - Gang Of Four - - Difficulty-Beginner +title: "Adapter Pattern in Java: Seamless Integration of Incompatible Systems" +shortTitle: Adapter +description: "Learn how the Adapter Design Pattern works in Java with detailed examples and use cases. Understand how it enables compatibility between incompatible interfaces." +category: Structural +language: en +tag: + - Compatibility + - Decoupling + - Gang of Four + - Interface + - Object composition + - Wrapping --- ## Also known as -Wrapper -## Intent -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. +* Wrapper -## Explanation +## Intent of Adapter Design Pattern -Real world example +The Adapter Design Pattern in Java converts the interface of a class into another interface that clients expect, enabling compatibility. -> 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 +## Detailed Explanation of Adapter Pattern with Real-World Examples + +Real-world example + +> Consider that you have some pictures on your memory card and you need to transfer them to your computer. To transfer them, you need some kind of adapter that is compatible with your computer ports so that you can attach a 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 outlets. Yet another example would be a translator translating words spoken by one person to another In plain words @@ -34,100 +35,120 @@ 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** +Sequence diagram + +![Adapter sequence diagram](./etc/adapter-sequence-diagram.png "Adapter sequence diagram") + +## Programmatic Example of Adapter Pattern in Java -Consider a captain that can only use rowing boats and cannot sail at all. +The Adapter Pattern example in Java shows how a class with an incompatible interface can be adapted to work with another class. -First we have interfaces `RowingBoat` and `FishingBoat` +Consider a wannabe captain that can only use rowing boats but can't sail at all. + +First, we have interfaces `RowingBoat` and `FishingBoat` ```java public interface RowingBoat { - void row(); + void row(); } +@Slf4j public class FishingBoat { - private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoat.class); - public void sail() { - LOGGER.info("The fishing boat is sailing"); - } + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } } ``` -And captain expects an implementation of `RowingBoat` interface to be able to move +The captain expects an implementation of `RowingBoat` interface to be able to move. ```java -public class Captain implements RowingBoat { +public class Captain { - private RowingBoat rowingBoat; + private final RowingBoat rowingBoat; - public Captain(RowingBoat rowingBoat) { - this.rowingBoat = rowingBoat; - } + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } - @Override - public void row() { - rowingBoat.row(); - } + 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. +Now, let's say the pirates are coming and our captain needs to escape but there is only a fishing boat available. We need to create an adapter that allows the captain to operate the fishing boat with his rowing boat skills. ```java +@Slf4j public class FishingBoatAdapter implements RowingBoat { - private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoatAdapter.class); - - private FishingBoat boat; + private final FishingBoat boat; - public FishingBoatAdapter() { - boat = new FishingBoat(); - } + public FishingBoatAdapter() { + boat = new FishingBoat(); + } - @Override - public void row() { - boat.sail(); - } + @Override + public void row() { + boat.sail(); + } } ``` -And now the `Captain` can use the `FishingBoat` to escape the pirates. +Now the `Captain` can use the `FishingBoat` to escape the pirates. ```java -Captain captain = new Captain(new FishingBoatAdapter()); -captain.row(); + public static void main(final String[] args) { + // The captain can only operate rowing boats but with adapter he is able to + // use fishing boats as well + var captain = new Captain(new FishingBoatAdapter()); + captain.row(); +} ``` -## Applicability -Use the Adapter pattern when +The program outputs: -* 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. +``` +10:25:08.074 [main] INFO com.iluwatar.adapter.FishingBoat -- The fishing boat is sailing +``` + +## When to Use the Adapter Pattern in Java -## Consequences: -Class and object adapters have different trade-offs. A class adapter +Use the Adapter pattern in Java when -* adapts Adaptee to Target by committing to a concrete Adaptee class. As a consequence, a class adapter won’t work when we want to adapt a class and all its subclasses. -* let’s Adapter override some of Adaptee’s behavior, since Adapter is a subclass of Adaptee. -* introduces only one object, and no additional pointer indirection is needed to get to the adaptee. +* 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 everyone. 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. -An object adapter +## Adapter Pattern Java Tutorials -* let’s a single Adapter work with many Adaptees—that is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once. -* makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself. +* [Using the Adapter Design Pattern in Java (Dzone)](https://dzone.com/articles/adapter-design-pattern-in-java) +* [Adapter in Java (Refactoring Guru)](https://refactoring.guru/design-patterns/adapter/java/example) +* [The Adapter Pattern in Java (Baeldung)](https://www.baeldung.com/java-adapter-pattern) +* [Adapter Design Pattern (GeeksForGeeks)](https://www.geeksforgeeks.org/adapter-pattern/) +## Benefits and Trade-offs of Adapter Pattern -## Real world examples +Class and object adapters offer different benefits and drawbacks. A class adapter adapts the Adaptee to the Target by binding to a specific Adaptee class, which means it cannot adapt a class and all its subclasses. This type of adapter allows the Adapter to override some of the Adaptee’s behavior because the Adapter is a subclass of the Adaptee. Additionally, it introduces only one object without needing extra pointer indirection to reach the Adaptee. +On the other hand, an object adapter allows a single Adapter to work with multiple Adaptees, including the Adaptee and all its subclasses. This type of adapter can add functionality to all Adaptees simultaneously. However, it makes overriding the Adaptee’s behavior more difficult, as it requires subclassing the Adaptee and having the Adapter refer to this subclass instead of the Adaptee itself. + +## Real-World Applications of Adapter Pattern in Java + +* `java.io.InputStreamReader` and `java.io.OutputStreamWriter` in the Java IO library. +* GUI component libraries that allow for plug-ins or adapters to convert between different GUI component interfaces. * [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) * [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) * [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) * [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) +## References and Credits -## Credits - -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) -* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/adapter/etc/adapter-sequence-diagram.png b/adapter/etc/adapter-sequence-diagram.png new file mode 100644 index 000000000000..a9bb557ea61e Binary files /dev/null and b/adapter/etc/adapter-sequence-diagram.png differ diff --git a/adapter/etc/adapter.urm.png b/adapter/etc/adapter.urm.png new file mode 100644 index 000000000000..341ad67699d9 Binary files /dev/null and b/adapter/etc/adapter.urm.png differ diff --git a/adapter/etc/adapter.urm.puml b/adapter/etc/adapter.urm.puml new file mode 100644 index 000000000000..1277cbb87125 --- /dev/null +++ b/adapter/etc/adapter.urm.puml @@ -0,0 +1,31 @@ +@startuml +package com.iluwatar.adapter { + class App { + - App() + + main(args : String[]) {static} + } + class Captain { + - rowingBoat : RowingBoat + + Captain() + + Captain(boat : RowingBoat) + ~ row() + ~ setRowingBoat(boat : RowingBoat) + } + ~class FishingBoat { + - LOGGER : Logger {static} + ~ FishingBoat() + ~ sail() + } + class FishingBoatAdapter { + - boat : FishingBoat + + FishingBoatAdapter() + + row() + } + interface RowingBoat { + + row() {abstract} + } +} +FishingBoatAdapter --> "-boat" FishingBoat +Captain --> "-rowingBoat" RowingBoat +FishingBoatAdapter ..|> RowingBoat +@enduml \ No newline at end of file diff --git a/adapter/pom.xml b/adapter/pom.xml index 95ccee3a9d0f..6e7f45a515b5 100644 --- a/adapter/pom.xml +++ b/adapter/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT adapter - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,25 @@ test + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.adapter.App + + + + + + + + diff --git a/adapter/src/main/java/com/iluwatar/adapter/App.java b/adapter/src/main/java/com/iluwatar/adapter/App.java index a624cc38f264..a4fa74274f74 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/App.java +++ b/adapter/src/main/java/com/iluwatar/adapter/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -28,33 +30,32 @@ * The Adapter design pattern allows otherwise incompatible classes to work together by converting * the interface of one class into an interface expected by the clients. * - *

- * There are two variations of the Adapter pattern: The class adapter implements the adaptee's + *

There are two variations of the Adapter pattern: The class adapter implements the adaptee's * interface whereas the object adapter uses composition to contain the adaptee in the adapter * object. This example uses the object adapter approach. * - *

- * The Adapter ({@link FishingBoatAdapter}) converts the interface of the adaptee class ( - * {@link FishingBoat}) into a suitable one expected by the client ( {@link RowingBoat} ). + *

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

The story of this implementation is this.
* 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 rowing boat which he can operate. The spec is in {@link RowingBoat}. We will - * use the Adapter pattern to reuse {@link FishingBoat}. - * + * 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}. */ -public class App { +public final class App { + + private App() {} /** * Program entry point. * * @param args command line args */ - public static void main(String[] args) { - // 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()); + public static void main(final String[] args) { + // The captain can only operate rowing boats but with adapter he is able to + // use fishing boats as well + var captain = new Captain(new FishingBoatAdapter()); captain.row(); } } diff --git a/adapter/src/main/java/com/iluwatar/adapter/Captain.java b/adapter/src/main/java/com/iluwatar/adapter/Captain.java index 8593ca321975..3b771e9d833e 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/Captain.java +++ b/adapter/src/main/java/com/iluwatar/adapter/Captain.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,26 +24,22 @@ */ package com.iluwatar.adapter; +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; +import lombok.Setter; + /** * The Captain uses {@link RowingBoat} to sail.
* This is the client in the pattern. */ -public class Captain { +@Setter +@NoArgsConstructor +@AllArgsConstructor +public final class Captain { private RowingBoat rowingBoat; - public Captain() {} - - public Captain(RowingBoat rowingBoat) { - this.rowingBoat = rowingBoat; - } - - public void setRowingBoat(RowingBoat rowingBoat) { - this.rowingBoat = rowingBoat; - } - - public void row() { + 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 c46814d18f16..dd39f88f1ce0 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java +++ b/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,16 @@ */ package com.iluwatar.adapter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * - * Device class (adaptee in the pattern). We want to reuse this class. - * Fishing boat moves by sailing. - * + * Device class (adaptee in the pattern). We want to reuse this class. Fishing boat moves by + * sailing. */ -public class FishingBoat { - - private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoat.class); +@Slf4j +final class FishingBoat { - public void sail() { + void sail() { LOGGER.info("The fishing boat is sailing"); } - } diff --git a/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java b/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java index 1e758e917040..8c7e9e88e220 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java +++ b/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,21 +25,14 @@ package com.iluwatar.adapter; /** - * * Adapter class. Adapts the interface of the device ({@link FishingBoat}) into {@link RowingBoat} * interface expected by the client ({@link Captain}). - * */ public class FishingBoatAdapter implements RowingBoat { - private FishingBoat boat; - - public FishingBoatAdapter() { - boat = new FishingBoat(); - } + private final FishingBoat boat = new FishingBoat(); - @Override - public void row() { + public final void row() { boat.sail(); } } diff --git a/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java b/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java index a9ca9ad39717..55eeeaf4bd42 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java +++ b/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,10 +27,8 @@ /** * The interface expected by the client.
* A rowing boat is rowed to move. - * */ public interface RowingBoat { void row(); - } diff --git a/adapter/src/main/java/com/iluwatar/adapter/package-info.java b/adapter/src/main/java/com/iluwatar/adapter/package-info.java new file mode 100644 index 000000000000..c42f2ac86ceb --- /dev/null +++ b/adapter/src/main/java/com/iluwatar/adapter/package-info.java @@ -0,0 +1,25 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; diff --git a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java index 82a951e30bdc..bc4984da3d6f 100644 --- a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java +++ b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,16 @@ */ package com.iluwatar.adapter; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -/** - * Test class - * - */ -public class AdapterPatternTest { +/** Tests for the adapter pattern. */ +class AdapterPatternTest { private Map beans; @@ -43,36 +41,34 @@ public class AdapterPatternTest { private static final String ROWING_BEAN = "captain"; - /** - * This method runs before the test execution and sets the bean objects in the beans Map. - */ + /** This method runs before the test execution and sets the bean objects in the beans Map. */ @BeforeEach - public void setup() { + void setup() { beans = new HashMap<>(); - FishingBoatAdapter fishingBoatAdapter = spy(new FishingBoatAdapter()); + var fishingBoatAdapter = spy(new FishingBoatAdapter()); beans.put(FISHING_BEAN, fishingBoatAdapter); - Captain captain = new Captain(); + var captain = new Captain(); captain.setRowingBoat((FishingBoatAdapter) beans.get(FISHING_BEAN)); beans.put(ROWING_BEAN, captain); } /** - * 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} ). + * 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() { - Captain captain = (Captain) beans.get(ROWING_BEAN); + void testAdapter() { + var captain = (Captain) beans.get(ROWING_BEAN); // when captain moves captain.row(); // the captain internally calls the battleship object to move - RowingBoat adapter = (RowingBoat) beans.get(FISHING_BEAN); + var adapter = (RowingBoat) beans.get(FISHING_BEAN); verify(adapter).row(); } } diff --git a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java b/adapter/src/test/java/com/iluwatar/adapter/AppTest.java index ca2c103c35e5..a2cc4c22bcaa 100644 --- a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java +++ b/adapter/src/test/java/com/iluwatar/adapter/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,17 @@ */ package com.iluwatar.adapter; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -import java.io.IOException; +/** Tests that Adapter example runs without errors. */ +class AppTest { -/** - * Tests that Adapter example runs without errors. - */ -public class AppTest { + /** Check whether the execution of the main method in {@link App} throws an exception. */ @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/aggregator-microservices/README.md b/aggregator-microservices/README.md deleted file mode 100644 index e65f26d9a38a..000000000000 --- a/aggregator-microservices/README.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -layout: pattern -title: Aggregator Microservices -folder: aggregator-microservices -permalink: /patterns/aggregator-microservices/ -categories: Architectural -tags: -- Java -- Spring ---- - -## Intent - -The user makes a single call to the Aggregator, and the aggregator then calls each relevant microservice and collects -the data, apply business logic to it, and further publish is as a REST Endpoint. -More variations of the aggregator are: -- Proxy Microservice Design Pattern: A different microservice is called upon the business need. -- Chained Microservice Design Pattern: In this case each microservice is dependent/ chained to a series -of other microservices. - -![alt text](./etc/aggregator-microservice.png "Aggregator Microservice") - -## Applicability - -Use the Aggregator Microservices pattern when you need a unified API for various microservices, regardless the client device. - -## Credits - -* [Microservice Design Patterns](http://blog.arungupta.me/microservice-design-patterns/) diff --git a/aggregator-microservices/aggregator-service/pom.xml b/aggregator-microservices/aggregator-service/pom.xml deleted file mode 100644 index fb26ff954f8c..000000000000 --- a/aggregator-microservices/aggregator-service/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - aggregator-microservices - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - - aggregator-service - jar - - - - - org.springframework.boot - spring-boot-dependencies - - - - - - org.springframework - spring-webmvc - - - org.springframework.boot - spring-boot-starter-web - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.mockito - mockito-core - test - - - org.apache.httpcomponents - httpclient - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - - - repackage - - - - - - - \ No newline at end of file diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java deleted file mode 100644 index 9f1e4f4daeb8..000000000000 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java +++ /dev/null @@ -1,58 +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.aggregator.microservices; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Resource; - -/** - * The aggregator aggregates calls on various micro-services, collects - * data and further publishes them under a REST endpoint. - */ -@RestController -public class Aggregator { - - - @Resource - private ProductInformationClient informationClient; - - @Resource - private ProductInventoryClient inventoryClient; - - - /** - * Retrieves product data. - * - * @return a Product. - */ - @RequestMapping("/product") - public Product getProduct() { - Product product = new Product(); - product.setTitle(informationClient.getProductTitle()); - product.setProductInventories(inventoryClient.getProductInventories()); - return product; - } - -} diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java deleted file mode 100644 index c43112c2e00a..000000000000 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java +++ /dev/null @@ -1,42 +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.aggregator.microservices; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * Spring Boot EntryPoint Class - */ -@SpringBootApplication -public class App { - - /** - * Program entry point - * - * @param args command line args - */ - public static void main(String[] args) { - SpringApplication.run(App.class, args); - } -} diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Product.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Product.java deleted file mode 100644 index 1ded980f90ea..000000000000 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Product.java +++ /dev/null @@ -1,57 +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.aggregator.microservices; - -/** - * Encapsulates all the data for a Product that clients will request. - */ -public class Product { - - /** - * The title of the product. - */ - private String title; - - - /** - * The inventories of the product. - */ - private int productInventories; - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getProductInventories() { - return productInventories; - } - - public void setProductInventories(int productInventories) { - this.productInventories = productInventories; - } - -} diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java deleted file mode 100644 index 16849d529386..000000000000 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java +++ /dev/null @@ -1,57 +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.aggregator.microservices; - -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import java.io.IOException; - -/** - * An adapter to communicate with information micro-service. - */ -@Component -public class ProductInformationClientImpl implements ProductInformationClient { - - private static final Logger LOGGER = LoggerFactory.getLogger(ProductInformationClientImpl.class); - - @Override - public String getProductTitle() { - String response = null; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet("http://localhost:51515/information"); - try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { - response = EntityUtils.toString(httpResponse.getEntity()); - } - } catch (IOException e) { - LOGGER.error("Exception caught.", e); - } - return response; - } -} diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java deleted file mode 100644 index 89f1a25e0580..000000000000 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java +++ /dev/null @@ -1,57 +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.aggregator.microservices; - -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import java.io.IOException; - -/** - * An adapter to communicate with inventory micro-service. - */ -@Component -public class ProductInventoryClientImpl implements ProductInventoryClient { - - private static final Logger LOGGER = LoggerFactory.getLogger(ProductInventoryClientImpl.class); - - @Override - public int getProductInventories() { - String response = "0"; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet("http://localhost:51516/inventories"); - try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { - response = EntityUtils.toString(httpResponse.getEntity()); - } - } catch (IOException e) { - LOGGER.error("Exception caught.", e); - } - return Integer.parseInt(response); - } -} diff --git a/aggregator-microservices/aggregator-service/src/main/resources/application.properties b/aggregator-microservices/aggregator-service/src/main/resources/application.properties deleted file mode 100644 index ae91c5eb5625..000000000000 --- a/aggregator-microservices/aggregator-service/src/main/resources/application.properties +++ /dev/null @@ -1,24 +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. -# - -server.port=50004 \ No newline at end of file diff --git a/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java b/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java deleted file mode 100644 index bc07ccc2117b..000000000000 --- a/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java +++ /dev/null @@ -1,70 +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.aggregator.microservices; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - -/** - * Test Aggregation of domain objects - */ -public class AggregatorTest { - - @InjectMocks - private Aggregator aggregator; - - @Mock - private ProductInformationClient informationClient; - - @Mock - private ProductInventoryClient inventoryClient; - - @BeforeEach - public void setup() { - MockitoAnnotations.initMocks(this); - } - - /** - * Tests getting the data for a desktop client - */ - @Test - public void testGetProduct() { - String title = "The Product Title."; - int inventories = 5; - - when(informationClient.getProductTitle()).thenReturn(title); - when(inventoryClient.getProductInventories()).thenReturn(inventories); - - Product testProduct = aggregator.getProduct(); - - assertEquals(title, testProduct.getTitle()); - assertEquals(inventories, testProduct.getProductInventories()); - } - -} diff --git a/aggregator-microservices/etc/aggregator-microservice.png b/aggregator-microservices/etc/aggregator-microservice.png deleted file mode 100644 index ad344a7e1e0f..000000000000 Binary files a/aggregator-microservices/etc/aggregator-microservice.png and /dev/null differ diff --git a/aggregator-microservices/information-microservice/pom.xml b/aggregator-microservices/information-microservice/pom.xml deleted file mode 100644 index 7afce1e9be8f..000000000000 --- a/aggregator-microservices/information-microservice/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - aggregator-microservices - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - - information-microservice - jar - - - - - org.springframework.boot - spring-boot-dependencies - - - - - - org.springframework - spring-webmvc - - - org.springframework.boot - spring-boot-starter-web - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - - - repackage - - - - - - - diff --git a/aggregator-microservices/information-microservice/src/main/resources/application.properties b/aggregator-microservices/information-microservice/src/main/resources/application.properties deleted file mode 100644 index a921ea0fd100..000000000000 --- a/aggregator-microservices/information-microservice/src/main/resources/application.properties +++ /dev/null @@ -1,24 +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. -# - -server.port=51515 \ No newline at end of file diff --git a/aggregator-microservices/inventory-microservice/pom.xml b/aggregator-microservices/inventory-microservice/pom.xml deleted file mode 100644 index 0d44b037ecf0..000000000000 --- a/aggregator-microservices/inventory-microservice/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - aggregator-microservices - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - - inventory-microservice - jar - - - - - org.springframework.boot - spring-boot-dependencies - - - - - - org.springframework - spring-webmvc - - - org.springframework.boot - spring-boot-starter-web - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - - - repackage - - - - - - - \ No newline at end of file diff --git a/aggregator-microservices/inventory-microservice/src/main/resources/application.properties b/aggregator-microservices/inventory-microservice/src/main/resources/application.properties deleted file mode 100644 index 46b49a8a1464..000000000000 --- a/aggregator-microservices/inventory-microservice/src/main/resources/application.properties +++ /dev/null @@ -1,24 +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. -# - -server.port=51516 \ No newline at end of file diff --git a/aggregator-microservices/pom.xml b/aggregator-microservices/pom.xml deleted file mode 100644 index ed48768f207f..000000000000 --- a/aggregator-microservices/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - java-design-patterns - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - aggregator-microservices - pom - - information-microservice - aggregator-service - inventory-microservice - - diff --git a/ambassador/README.md b/ambassador/README.md new file mode 100644 index 000000000000..fa08223feb75 --- /dev/null +++ b/ambassador/README.md @@ -0,0 +1,236 @@ +--- +title: "Ambassador Pattern in Java: Simplifying Remote Resource Management" +shortTitle: Ambassador +description: "Explore the Ambassador Pattern in Java, its benefits, use cases, and practical examples. Learn how to decouple and offload common functionalities to improve system performance and maintainability." +category: Integration +language: en +tag: + - API design + - Decoupling + - Fault tolerance + - Proxy + - Resilience + - Scalability +--- + +## Intent of Ambassador Design Pattern + +The Ambassador Pattern in Java helps offload common functionalities such as monitoring, logging, and routing from a shared resource to a helper service instance, enhancing performance and maintainability in distributed systems. + +## Detailed Explanation of Ambassador Pattern with Real-World Examples + +Real-world example + +> Imagine a busy hotel where guests frequently request restaurant reservations, event tickets, or transportation arrangements. Instead of each guest individually contacting these services, the hotel provides a concierge. The concierge handles these tasks on behalf of the guests, ensuring that reservations are made smoothly, tickets are booked on time, and transportation is scheduled efficiently. +> +> In this analogy, the guests are the client services, the external providers (restaurants, ticket vendors, transportation) are the remote services, and the concierge represents the ambassador service. This setup allows the guests to focus on enjoying their stay while the concierge manages the complexities of external interactions, providing a seamless and enhanced experience. + +In plain words + +> With the Ambassador pattern, we can implement less-frequent polling from clients along with latency checks and logging. + +Microsoft documentation states + +> An ambassador service can be thought of as an out-of-process proxy which is co-located with the client. This pattern can be useful for offloading common client connectivity tasks such as monitoring, logging, routing, security (such as TLS), and resiliency patterns in a language agnostic way. It is often used with legacy applications, or other applications that are difficult to modify, in order to extend their networking capabilities. It can also enable a specialized team to implement those features. + +Sequence diagram + +![Ambassador sequence diagram](./etc/ambassador-sequence-diagram.png "Ambassador sequence diagram") + +## Programmatic Example of Ambassador Pattern in Java + +In this example of the Ambassador Pattern in Java, we demonstrate how to implement latency checks, logging, and retry mechanisms to improve system reliability. + +A remote service has many clients accessing a function it provides. The service is a legacy application and is impossible to update. Large numbers of requests from users are causing connectivity issues. New rules for request frequency should be implemented along with latency checks and client-side logging. + +With the above introduction in mind we will imitate the functionality in this example. We have an interface implemented by the remote service as well as the ambassador service. + +```java +interface RemoteServiceInterface { + long doRemoteFunction(int value) throws Exception; +} +``` + +A remote services represented as a singleton. + +```java + +@Slf4j +public class RemoteService implements RemoteServiceInterface { + private static RemoteService service = null; + + static synchronized RemoteService getRemoteService() { + if (service == null) { + service = new RemoteService(); + } + return service; + } + + private RemoteService() { + } + + @Override + public long doRemoteFunction(int value) { + long waitTime = (long) Math.floor(Math.random() * 1000); + + try { + sleep(waitTime); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep interrupted", e); + } + + return waitTime >= 200 ? value * 10 : -1; + } +} +``` + +A service ambassador adds additional features such as logging and latency checks. + +```java + +@Slf4j +public class ServiceAmbassador implements RemoteServiceInterface { + private static final int RETRIES = 3; + private static final int DELAY_MS = 3000; + + ServiceAmbassador() { + } + + @Override + public long doRemoteFunction(int value) { + return safeCall(value); + } + + private long checkLatency(int value) { + var startTime = System.currentTimeMillis(); + var result = RemoteService.getRemoteService().doRemoteFunction(value); + var timeTaken = System.currentTimeMillis() - startTime; + + LOGGER.info("Time taken (ms): " + timeTaken); + return result; + } + + private long safeCall(int value) { + var retries = 0; + var result = (long) FAILURE; + + for (int i = 0; i < RETRIES; i++) { + if (retries >= RETRIES) { + return FAILURE; + } + + if ((result = checkLatency(value)) == FAILURE) { + LOGGER.info("Failed to reach remote: (" + (i + 1) + ")"); + retries++; + try { + sleep(DELAY_MS); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep state interrupted", e); + } + } else { + break; + } + } + return result; + } +} +``` + +A client has a local service ambassador used to interact with the remote service. + +```java + +@Slf4j +public class Client { + private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador(); + + long useService(int value) { + var result = serviceAmbassador.doRemoteFunction(value); + LOGGER.info("Service result: " + result); + return result; + } +} +``` + +Here are two clients using the service. + +```java +public class App { + public static void main(String[] args) { + var host1 = new Client(); + var host2 = new Client(); + host1.useService(12); + host2.useService(73); + } +} +``` + +Here's the output for running the example: + +```java +Time taken(ms):111 +Service result:120 +Time taken(ms):931 +Failed to reach remote:(1) +Time taken(ms):665 +Failed to reach remote:(2) +Time taken(ms):538 +Failed to reach remote:(3) +Service result:-1 +``` + +## When to Use the Ambassador Pattern in Java + +* The Ambassador Pattern is particularly beneficial for Cloud Native and Microservices Architectures in Java. It helps in monitoring, logging, and securing inter-service communication, making it ideal for distributed systems. +* Legacy System Integration: Facilitates communication with newer services by handling necessary but non-core functionalities. +* Performance Enhancement: Can be used to cache results or compress data to improve communication efficiency. + +Typical use cases include: + +* Control access to another object +* Implement logging +* Implement circuit breaking +* Offload remote service tasks +* Facilitate network connection + +## Benefits and Trade-offs of Ambassador Pattern + +Benefits: + +* Separation of Concerns: Offloads cross-cutting concerns from the service logic, leading to cleaner, more maintainable code. +* Reusable Infrastructure Logic: The ambassador pattern allows the same logic (e.g., logging, monitoring) to be reused across multiple services. +* Improved Security: Centralizes security features like SSL termination or authentication, reducing the risk of misconfiguration. +* Flexibility: Makes it easier to update or replace infrastructure concerns without modifying the service code. + +Trade-offs: + +* Increased Complexity: Adds another layer to the architecture, which can complicate the system design and debugging. +* Potential Performance Overhead: The additional network hop can introduce latency and overhead, particularly if not optimized. +* Deployment Overhead: Requires additional resources and management for deploying and scaling ambassador services. + +## Real-World Applications of Ambassador Pattern in Java + +* Service Mesh Implementations: In a service mesh architecture, like Istio or Linkerd, the Ambassador pattern is often employed as a sidecar proxy that handles inter-service communications. This includes tasks such as service discovery, routing, load balancing, telemetry (metrics and tracing), and security (authentication and authorization). +* API Gateways: API gateways can use the Ambassador pattern to encapsulate common functionalities like rate limiting, caching, request shaping, and authentication. This allows backend services to focus on their core business logic without being burdened by these cross-cutting concerns. +* Logging and Monitoring: An Ambassador can aggregate logs and metrics from various services and forward them to centralized monitoring tools like Prometheus or ELK Stack (Elasticsearch, Logstash, Kibana). This simplifies the logging and monitoring setup for each service and provides a unified view of the system's health. +* Security: Security-related functionalities such as SSL/TLS termination, identity verification, and encryption can be managed by an Ambassador. This ensures consistent security practices across services and reduces the likelihood of security breaches due to misconfigurations. +* Resilience: The Ambassador can implement resilience patterns like circuit breakers, retries, and timeouts. For instance, Netflix's Hystrix library can be used within an Ambassador to prevent cascading failures in a microservices ecosystem. +* Database Proxy: Ambassadors can act as proxies for database connections, providing functionalities like connection pooling, read/write splitting for replicas, and query caching. This offloads significant complexity from the application services. +* Legacy System Integration: In scenarios where modern microservices need to communicate with legacy systems, an Ambassador can serve as an intermediary that translates protocols, handles necessary transformations, and implements modern security practices, easing the integration process. +* Network Optimization: For services deployed across different geographical locations or cloud regions, Ambassadors can optimize communication by compressing data, batching requests, or even implementing smart routing to reduce latency and costs. +* [Kubernetes-native API gateway for microservices](https://github.com/datawire/ambassador) + +## Related Java Design Patterns + +* [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Often used in conjunction to manage fault tolerance by stopping calls to an unresponsive service. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): The decorator pattern is used to add functionality to an object dynamically, while the ambassador pattern is used to offload functionality to a separate object. +* [Proxy](https://java-design-patterns.com/patterns/proxy/): Shares similarities with the proxy pattern, but the ambassador pattern specifically focuses on offloading ancillary functionalities. +* Sidecar: A similar pattern used in the context of containerized applications, where a sidecar container provides additional functionality to the main application container. + +## References and Credits + +* [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/43aGpSR) +* [Cloud Native Patterns: Designing Change-tolerant Software](https://amzn.to/3wUAl4O) +* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://amzn.to/3T9g9Uj) +* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O) +* [Ambassador pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador) diff --git a/ambassador/etc/ambassador-sequence-diagram.png b/ambassador/etc/ambassador-sequence-diagram.png new file mode 100644 index 000000000000..71e6a947c5dd Binary files /dev/null and b/ambassador/etc/ambassador-sequence-diagram.png differ diff --git a/ambassador/etc/ambassador.urm.png b/ambassador/etc/ambassador.urm.png new file mode 100644 index 000000000000..9b50a02ad356 Binary files /dev/null and b/ambassador/etc/ambassador.urm.png differ diff --git a/ambassador/etc/ambassador.urm.puml b/ambassador/etc/ambassador.urm.puml new file mode 100644 index 000000000000..517b0bf51d07 --- /dev/null +++ b/ambassador/etc/ambassador.urm.puml @@ -0,0 +1,47 @@ +@startuml +package com.iluwatar.ambassador.util { + interface RandomProvider { + + random() : double {abstract} + } +} +package com.iluwatar.ambassador { + class App { + + App() + + main(args : String[]) {static} + } + class Client { + - LOGGER : Logger {static} + - serviceAmbassador : ServiceAmbassador + + Client() + ~ useService(value : int) : long + } + class RemoteService { + - LOGGER : Logger {static} + - THRESHOLD : int {static} + - randomProvider : RandomProvider + - service : RemoteService {static} + - RemoteService() + ~ RemoteService(randomProvider : RandomProvider) + + doRemoteFunction(value : int) : long + ~ getRemoteService() : RemoteService {static} + } + ~interface RemoteServiceInterface { + + FAILURE : int {static} + + doRemoteFunction(int) : long {abstract} + } + class ServiceAmbassador { + - DELAY_MS : int {static} + - LOGGER : Logger {static} + - RETRIES : int {static} + ~ ServiceAmbassador() + - checkLatency(value : int) : long + + doRemoteFunction(value : int) : long + - safeCall(value : int) : long + } +} +RemoteService --> "-service" RemoteService +Client --> "-serviceAmbassador" ServiceAmbassador +RemoteService --> "-randomProvider" RandomProvider +RemoteService ..|> RemoteServiceInterface +ServiceAmbassador ..|> RemoteServiceInterface +@enduml \ No newline at end of file diff --git a/ambassador/pom.xml b/ambassador/pom.xml new file mode 100644 index 000000000000..15e4a07f0dc3 --- /dev/null +++ b/ambassador/pom.xml @@ -0,0 +1,70 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + ambassador + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.ambassador.App + + + + + + + + + diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/App.java b/ambassador/src/main/java/com/iluwatar/ambassador/App.java new file mode 100644 index 000000000000..8de149fe0813 --- /dev/null +++ b/ambassador/src/main/java/com/iluwatar/ambassador/App.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador; + +/** + * The ambassador pattern creates a helper service that sends network requests on behalf of a + * client. It is often used in cloud-based applications to offload features of a remote service. + * + *

An ambassador service can be thought of as an out-of-process proxy that is co-located with the + * client. Similar to the proxy design pattern, the ambassador service provides an interface for + * another remote service. In addition to the interface, the ambassador provides extra functionality + * and features, specifically offloaded common connectivity tasks. This usually consists of + * monitoring, logging, routing, security etc. This is extremely useful in legacy applications where + * the codebase is difficult to modify and allows for improvements in the application's networking + * capabilities. + * + *

In this example, we will the ({@link ServiceAmbassador}) class represents the ambassador while + * the ({@link RemoteService}) class represents a remote application. + */ +public class App { + + /** Entry point. */ + public static void main(String[] args) { + var host1 = new Client(); + var host2 = new Client(); + host1.useService(12); + host2.useService(73); + } +} diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/Client.java b/ambassador/src/main/java/com/iluwatar/ambassador/Client.java new file mode 100644 index 000000000000..0baabf4ffc06 --- /dev/null +++ b/ambassador/src/main/java/com/iluwatar/ambassador/Client.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador; + +import lombok.extern.slf4j.Slf4j; + +/** A simple Client. */ +@Slf4j +public class Client { + + private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador(); + + long useService(int value) { + var result = serviceAmbassador.doRemoteFunction(value); + LOGGER.info("Service result: {}", result); + return result; + } +} diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java new file mode 100644 index 000000000000..d99348040cfe --- /dev/null +++ b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java @@ -0,0 +1,78 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador; + +import static java.lang.Thread.sleep; + +import com.iluwatar.ambassador.util.RandomProvider; +import lombok.extern.slf4j.Slf4j; + +/** A remote legacy application represented by a Singleton implementation. */ +@Slf4j +public class RemoteService implements RemoteServiceInterface { + private static final int THRESHOLD = 200; + private static RemoteService service = null; + private final RandomProvider randomProvider; + + static synchronized RemoteService getRemoteService() { + if (service == null) { + service = new RemoteService(); + } + return service; + } + + private RemoteService() { + this(Math::random); + } + + /** This constructor is used for testing purposes only. */ + RemoteService(RandomProvider randomProvider) { + this.randomProvider = randomProvider; + } + + /** + * Remote function takes a value and multiplies it by 10 taking a random amount of time. Will + * sometimes return -1. This imitates connectivity issues a client might have to account for. + * + * @param value integer value to be multiplied. + * @return if waitTime is less than {@link RemoteService#THRESHOLD}, it returns value * 10, + * otherwise {@link RemoteServiceStatus#FAILURE}. + */ + @Override + public long doRemoteFunction(int value) { + + long waitTime = (long) Math.floor(randomProvider.random() * 1000); + + try { + sleep(waitTime); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep state interrupted", e); + Thread.currentThread().interrupt(); + } + return waitTime <= THRESHOLD + ? value * 10 + : RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue(); + } +} diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java new file mode 100644 index 000000000000..aa6012bae33f --- /dev/null +++ b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador; + +/** Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}). */ +interface RemoteServiceInterface { + + long doRemoteFunction(int value); +} diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceStatus.java b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceStatus.java new file mode 100644 index 000000000000..8549ed7247f3 --- /dev/null +++ b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceStatus.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador; + +import lombok.Getter; + +/** + * Holds information regarding the status of the Remote Service. + * + *

This Enum replaces the integer value previously stored in {@link RemoteServiceInterface} as + * SonarCloud was identifying it as an issue. All test cases have been checked after changes, + * without failures. + */ +public enum RemoteServiceStatus { + FAILURE(-1); + + @Getter private final long remoteServiceStatusValue; + + RemoteServiceStatus(long remoteServiceStatusValue) { + this.remoteServiceStatusValue = remoteServiceStatusValue; + } +} diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java b/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java new file mode 100644 index 000000000000..4d310169770b --- /dev/null +++ b/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java @@ -0,0 +1,83 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador; + +import static com.iluwatar.ambassador.RemoteServiceStatus.FAILURE; +import static java.lang.Thread.sleep; + +import lombok.extern.slf4j.Slf4j; + +/** + * ServiceAmbassador provides an interface for a ({@link Client}) to access ({@link RemoteService}). + * The interface adds logging, latency testing and usage of the service in a safe way that will not + * add stress to the remote service when connectivity issues occur. + */ +@Slf4j +public class ServiceAmbassador implements RemoteServiceInterface { + + private static final int RETRIES = 3; + private static final int DELAY_MS = 3000; + + ServiceAmbassador() {} + + @Override + public long doRemoteFunction(int value) { + return safeCall(value); + } + + private long checkLatency(int value) { + var startTime = System.currentTimeMillis(); + var result = RemoteService.getRemoteService().doRemoteFunction(value); + var timeTaken = System.currentTimeMillis() - startTime; + + LOGGER.info("Time taken (ms): {}", timeTaken); + return result; + } + + private long safeCall(int value) { + var retries = 0; + var result = FAILURE.getRemoteServiceStatusValue(); + + for (int i = 0; i < RETRIES; i++) { + if (retries >= RETRIES) { + return FAILURE.getRemoteServiceStatusValue(); + } + + if ((result = checkLatency(value)) == FAILURE.getRemoteServiceStatusValue()) { + LOGGER.info("Failed to reach remote: ({})", i + 1); + retries++; + try { + sleep(DELAY_MS); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep state interrupted", e); + Thread.currentThread().interrupt(); + } + } else { + break; + } + } + return result; + } +} diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/util/RandomProvider.java b/ambassador/src/main/java/com/iluwatar/ambassador/util/RandomProvider.java new file mode 100644 index 000000000000..4eba2fada7fa --- /dev/null +++ b/ambassador/src/main/java/com/iluwatar/ambassador/util/RandomProvider.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador.util; + +/** An interface for randomness. Useful for testing purposes. */ +public interface RandomProvider { + double random(); +} diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java new file mode 100644 index 000000000000..ddb2d6eff411 --- /dev/null +++ b/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application test */ +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. + * + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java new file mode 100644 index 000000000000..24603efff9d4 --- /dev/null +++ b/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** Test for {@link Client} */ +class ClientTest { + + @Test + void test() { + Client client = new Client(); + var result = client.useService(10); + + assertTrue( + result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue()); + } +} diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java new file mode 100644 index 000000000000..81e4f744128f --- /dev/null +++ b/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.iluwatar.ambassador.util.RandomProvider; +import org.junit.jupiter.api.Test; + +/** Test for {@link RemoteService} */ +class RemoteServiceTest { + + @Test + void testFailedCall() { + var remoteService = new RemoteService(new StaticRandomProvider(0.21)); + var result = remoteService.doRemoteFunction(10); + assertEquals(RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue(), result); + } + + @Test + void testSuccessfulCall() { + var remoteService = new RemoteService(new StaticRandomProvider(0.2)); + var result = remoteService.doRemoteFunction(10); + assertEquals(100, result); + } + + private static class StaticRandomProvider implements RandomProvider { + private final double value; + + StaticRandomProvider(double value) { + this.value = value; + } + + @Override + public double random() { + return value; + } + } +} diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java new file mode 100644 index 000000000000..0543b2e7e370 --- /dev/null +++ b/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.ambassador; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** Test for {@link ServiceAmbassador} */ +class ServiceAmbassadorTest { + + @Test + void test() { + long result = new ServiceAmbassador().doRemoteFunction(10); + assertTrue( + result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue()); + } +} diff --git a/anti-corruption-layer/README.md b/anti-corruption-layer/README.md new file mode 100644 index 000000000000..9b6042850eba --- /dev/null +++ b/anti-corruption-layer/README.md @@ -0,0 +1,185 @@ +--- +title: "Anti-Corruption Layer Pattern in Java: Ensuring System Integrity Amidst Legacy Systems" +shortTitle: Anti-Corruption Layer +description: "Learn how the Anti-Corruption Layer design pattern helps in decoupling subsystems, preventing data corruption, and facilitating seamless integration in Java applications." +category: Integration +language: en +tag: + - Architecture + - Decoupling + - Integration + - Isolation + - Layered architecture + - Migration + - Modernization + - Refactoring + - Wrapping +--- + +## Also known as + +* ACL +* Interface layer +* Translation layer + +## Intent of Anti-Corruption Layer Design Pattern + +The Anti-Corruption Layer (ACL) is a crucial design pattern in Java development, particularly for system integration and maintaining data integrity. Implement a façade or adapter layer between different subsystems that don't share the same semantics. It translates between different data formats and systems, ensuring that the integration between systems does not lead to corruption of business logic or data integrity. + +## Detailed Explanation of Anti-Corruption Layer Pattern with Real-World Examples + +Real-world example + +> This example demonstrates how the Anti-Corruption Layer ensures seamless integration between legacy systems and modern platforms, crucial for maintaining business logic integrity during system migration. +> +> Imagine a large retail company transitioning its inventory management system from an old legacy software to a new modern platform. The legacy system has been in use for decades and contains complex business rules and data formats that are incompatible with the new system. Instead of directly connecting the new system to the legacy one, the company implements an Anti-Corruption Layer (ACL). +> +> The ACL acts as a mediator, translating and adapting data between the two systems. When the new system requests inventory data, the ACL translates the request into a format the legacy system understands, retrieves the data, and then translates it back into a format suitable for the new system. This approach ensures that the new system remains unaffected by the intricacies of the legacy system, preventing corruption of data and business logic while facilitating a smooth transition. + +In plain words + +> The Anti-Corruption Layer design pattern protects a system from the complexities and changes of external systems by providing an intermediary translation layer. + +[Microsoft's documentation](https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer) says + +> Implement a façade or adapter layer between different subsystems that don't share the same semantics. This layer translates requests that one subsystem makes to the other subsystem. Use this pattern to ensure that an application's design is not limited by dependencies on outside subsystems. This pattern was first described by Eric Evans in Domain-Driven Design. + +Sequence diagram + +![Anti-Corruption Layer sequence diagram](./etc/anti-corruption-layer-sequence-diagram.png "Anti-Corruption Layer sequence diagram") + +## Programmatic Example of Anti-Corruption Layer Pattern in Java + +The ACL design pattern in Java provides an intermediary layer that translates data formats, ensuring that integration between different systems does not lead to data corruption. + +Here are 2 shop-ordering systems: `Legacy` and `Modern`. + +The aforementioned systems have different domain models and have to operate simultaneously. Since they work independently the orders can come either from the `Legacy` or `Modern` system. Therefore, the system that receives the legacyOrder needs to check if the legacyOrder is valid and not present in the other system. Then it can place the legacyOrder in its own system. + +But for that, the system needs to know the domain model of the other system and to avoid that, the anti-corruption layer(ACL) is introduced. The ACL is a layer that translates the domain model of the `Legacy` system to the domain model of the `Modern` system and vice versa. Also, it hides all other operations with the other system, uncoupling the systems. + +Domain model of the `Legacy` system: + +```java +public class LegacyOrder { + private String id; + private String customer; + private String item; + private String qty; + private String price; +} +``` + +Domain model of the `Modern` system: + +```java +public class ModernOrder { + private String id; + private Customer customer; + + private Shipment shipment; + + private String extra; +} + +public class Customer { + private String address; +} + +public class Shipment { + private String item; + private String qty; + private String price; +} +``` + +Anti-corruption layer: + +```java +public class AntiCorruptionLayer { + + @Autowired + private ModernShop modernShop; + + @Autowired + private LegacyShop legacyShop; + + public Optional findOrderInModernSystem(String id) { + return modernShop.findOrder(id).map(o -> /* map to legacyOrder*/); + } + + public Optional findOrderInLegacySystem(String id) { + return legacyShop.findOrder(id).map(o -> /* map to modernOrder*/); + } + +} +``` + +The connection between the systems. Wherever the `Legacy` or `Modern` system needs to communicate with the counterpart the ACL needs to be used to avoid corrupting the current domain model. The example below shows how the `Legacy` system places an order with a validation from the `Modern` system. + +```java +public class LegacyShop { + @Autowired + private AntiCorruptionLayer acl; + + public void placeOrder(LegacyOrder legacyOrder) throws ShopException { + + String id = legacyOrder.getId(); + + Optional orderInModernSystem = acl.findOrderInModernSystem(id); + + if (orderInModernSystem.isPresent()) { + // order is already in the modern system + } else { + // place order in the current system + } + } +} +``` + +## When to Use the Anti-Corruption Layer Pattern in Java + +Use this pattern when: + +* A migration is planned to happen over multiple stages, but integration between new and legacy systems needs to be maintained +* Two or more subsystems have different semantics, but still need to communicate +* When integrating with legacy systems or external systems where direct integration might pollute the domain model of the new system +* In scenarios where different subsystems within a larger system use different data formats or structures +* When there is a need to ensure loose coupling between different subsystems or external services to facilitate easier maintenance and scalability + +## Anti-Corruption Layer Pattern Java Tutorials + +* [Anti-Corruption Layer (Microsoft)](https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer) +* [Anti-Corruption Layer Pattern (Amazon)](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/acl.html) + +## Real-World Applications of Anti-Corruption Layer Pattern in Java + +* Microservices architectures where individual services must communicate without being tightly coupled to each other’s data schemas +* Enterprise systems integration, especially when integrating modern systems with legacy systems +* In bounded contexts within Domain-Driven Design (DDD) to maintain the integrity of a domain model when interacting with external systems or subsystems + +## Benefits and Trade-offs of Anti-Corruption Layer Pattern + +Benefits: + +* Protects the integrity of the domain model by providing a clear boundary +* Promotes loose coupling between systems, making the system more resilient to changes in external systems +* Facilitates cleaner and more maintainable code by isolating integration code from business logic + +Trade-offs: + +* Introduces additional complexity and potential performance overhead due to the translation process +* Requires extra effort in design and implementation to ensure the layer is effective without becoming a bottleneck +* Can lead to duplication of models if not carefully managed + +## Related Java Design Patterns + +* [Adapter](https://java-design-patterns.com/patterns/adapter/): The Anti-Corruption Layer can be implemented using the Adapter pattern to translate between different data formats or structures +* [Facade](https://java-design-patterns.com/patterns/facade/): The Anti-Corruption Layer can be seen as a specialized form of the Facade pattern that is used to isolate different subsystems +* [Gateway](https://java-design-patterns.com/patterns/gateway/): The Anti-Corruption Layer can be used as a Gateway to external systems to provide a unified interface + +## References and Credits + +* [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3vptcJz) +* [Implementing Domain-Driven Design](https://amzn.to/3ISOSRA) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/anti-corruption-layer/etc/anti-corruption-layer-sequence-diagram.png b/anti-corruption-layer/etc/anti-corruption-layer-sequence-diagram.png new file mode 100644 index 000000000000..835ff4e84a0f Binary files /dev/null and b/anti-corruption-layer/etc/anti-corruption-layer-sequence-diagram.png differ diff --git a/anti-corruption-layer/etc/anti-corruption-layer.urm.png b/anti-corruption-layer/etc/anti-corruption-layer.urm.png new file mode 100644 index 000000000000..96e432121e7e Binary files /dev/null and b/anti-corruption-layer/etc/anti-corruption-layer.urm.png differ diff --git a/anti-corruption-layer/etc/anti-corruption-layer.urm.puml b/anti-corruption-layer/etc/anti-corruption-layer.urm.puml new file mode 100644 index 000000000000..6b1d1cdb9b81 --- /dev/null +++ b/anti-corruption-layer/etc/anti-corruption-layer.urm.puml @@ -0,0 +1,25 @@ +@startuml +package com.iluwatar.corruption { +class LegacyShop { + private Store store; + private AntiCorruptionLayer acl; +} + +class ModernShop { + private Store store; + private AntiCorruptionLayer acl; +} + +class AntiCorruptionLayer{ + private LegacyShop legacyShop; + private ModernShop modernShop; + + + } +LegacyShop ---> "findOrderInModernSystem" AntiCorruptionLayer +ModernShop ---> "findOrderInLegacySystem" AntiCorruptionLayer +AntiCorruptionLayer ..|> ModernShop +AntiCorruptionLayer ..|> LegacyShop +} + +@enduml \ No newline at end of file diff --git a/anti-corruption-layer/pom.xml b/anti-corruption-layer/pom.xml new file mode 100644 index 000000000000..2fddfd3ecc46 --- /dev/null +++ b/anti-corruption-layer/pom.xml @@ -0,0 +1,72 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + anti-corruption-layer + jar + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.corruption.App + + + + + + + + + diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/App.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/App.java new file mode 100644 index 000000000000..f7cf8f075f83 --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/App.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * This layer translates communications between the two systems, allowing one system to remain + * unchanged while the other can avoid compromising its design and technological approach. + */ +@SpringBootApplication +public class App { + + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } +} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/package-info.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/package-info.java new file mode 100644 index 000000000000..880d98c7d5b0 --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/package-info.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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. + */ +/** + * Context and problem Most applications rely on other systems for some data or functionality. For + * example, when a legacy application is migrated to a modern system, it may still need existing + * legacy resources. New features must be able to call the legacy system. This is especially true of + * gradual migrations, where different features of a larger application are moved to a modern system + * over time. + * + *

Often these legacy systems suffer from quality issues such as convoluted data schemas or + * obsolete APIs. The features and technologies used in legacy systems can vary widely from more + * modern systems. To interoperate with the legacy system, the new application may need to support + * outdated infrastructure, protocols, data models, APIs, or other features that you wouldn't + * otherwise put into a modern application. + * + *

Maintaining access between new and legacy systems can force the new system to adhere to at + * least some of the legacy system's APIs or other semantics. When these legacy features have + * quality issues, supporting them "corrupts" what might otherwise be a cleanly designed modern + * application. Similar issues can arise with any external system that your development team doesn't + * control, not just legacy systems. + * + *

Solution Isolate the different subsystems by placing an anti-corruption layer between them. + * This layer translates communications between the two systems, allowing one system to remain + * unchanged while the other can avoid compromising its design and technological approach. + */ +package com.iluwatar.corruption; diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/AntiCorruptionLayer.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/AntiCorruptionLayer.java new file mode 100644 index 000000000000..4e8a17fa5d2a --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/AntiCorruptionLayer.java @@ -0,0 +1,66 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system; + +import com.iluwatar.corruption.system.legacy.LegacyShop; +import com.iluwatar.corruption.system.modern.Customer; +import com.iluwatar.corruption.system.modern.ModernOrder; +import com.iluwatar.corruption.system.modern.Shipment; +import java.util.Optional; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * The class represents an anti-corruption layer. The main purpose of the class is to provide a + * layer between the modern and legacy systems. The class is responsible for converting the data + * from one system to another decoupling the systems to each other + * + *

It allows using one system a domain model of the other system without changing the domain + * model of the system. + */ +@Service +public class AntiCorruptionLayer { + + @Autowired private LegacyShop legacyShop; + + /** + * The method converts the order from the legacy system to the modern system. + * + * @param id the id of the order + * @return the order in the modern system + */ + public Optional findOrderInLegacySystem(String id) { + + return legacyShop + .findOrder(id) + .map( + o -> + new ModernOrder( + o.getId(), + new Customer(o.getCustomer()), + new Shipment(o.getItem(), o.getQty(), o.getPrice()), + "")); + } +} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/DataStore.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/DataStore.java new file mode 100644 index 000000000000..e84578528be7 --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/DataStore.java @@ -0,0 +1,49 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system; + +import java.util.HashMap; +import java.util.Optional; + +/** + * The class represents a data store for the modern system. + * + * @param the type of the value stored in the data store + */ +public abstract class DataStore { + private final HashMap inner; + + public DataStore() { + inner = new HashMap<>(); + } + + public Optional get(String key) { + return Optional.ofNullable(inner.get(key)); + } + + public Optional put(String key, V value) { + return Optional.ofNullable(inner.put(key, value)); + } +} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/ShopException.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/ShopException.java new file mode 100644 index 000000000000..c0acd288ed0c --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/ShopException.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system; + +/** The class represents a general exception for the shop. */ +public class ShopException extends Exception { + public ShopException(String message) { + super(message); + } + + /** + * Throws an exception that the order is already placed but has an incorrect data. + * + * @param lhs the incoming order + * @param rhs the existing order + * @return the exception + * @throws ShopException the exception + */ + public static ShopException throwIncorrectData(String lhs, String rhs) throws ShopException { + throw new ShopException( + "The order is already placed but has an incorrect data:\n" + + "Incoming order: " + + lhs + + "\n" + + "Existing order: " + + rhs); + } +} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyOrder.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyOrder.java new file mode 100644 index 000000000000..45faa06cb26c --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyOrder.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system.legacy; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * The class represents an order in the legacy system. The class is used by the legacy system to + * store the data. + */ +@Data +@AllArgsConstructor +public class LegacyOrder { + private String id; + private String customer; + + private String item; + private int qty; + private int price; +} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyShop.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyShop.java new file mode 100644 index 000000000000..b74eb1c29718 --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyShop.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system.legacy; + +import java.util.Optional; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * The class represents a legacy shop system. The main purpose is to place the order from the + * customers. + */ +@Service +public class LegacyShop { + @Autowired private LegacyStore store; + + /** + * Places the order in the legacy system. If the order is already present in the modern system, + * then the order is placed only if the data is the same. If the order is not present in the + * modern system, then the order is placed in the legacy system. + */ + public void placeOrder(LegacyOrder legacyOrder) { + store.put(legacyOrder.getId(), legacyOrder); + } + + /** Finds the order in the legacy system. */ + public Optional findOrder(String orderId) { + return store.get(orderId); + } +} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyStore.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyStore.java new file mode 100644 index 000000000000..ec1d613a7235 --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyStore.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system.legacy; + +import com.iluwatar.corruption.system.DataStore; +import org.springframework.stereotype.Service; + +/** + * The class represents a data store for the legacy system. The class is used by the legacy system + * to store the data. + */ +@Service +public class LegacyStore extends DataStore {} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Customer.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Customer.java new file mode 100644 index 000000000000..130f36d39674 --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Customer.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system.modern; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** The class represents a customer in the modern system. */ +@Data +@AllArgsConstructor +public class Customer { + private String address; +} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernOrder.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernOrder.java new file mode 100644 index 000000000000..7b62985015d6 --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernOrder.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system.modern; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** The class represents an order in the modern system. */ +@Data +@AllArgsConstructor +public class ModernOrder { + private String id; + private Customer customer; + + private Shipment shipment; + + private String extra; +} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernShop.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernShop.java new file mode 100644 index 000000000000..24080abe1533 --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernShop.java @@ -0,0 +1,67 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system.modern; + +import com.iluwatar.corruption.system.AntiCorruptionLayer; +import com.iluwatar.corruption.system.ShopException; +import java.util.Optional; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * The class represents a modern shop system. The main purpose of the class is to place orders and + * find orders. + */ +@Service +public class ModernShop { + @Autowired private ModernStore store; + + @Autowired private AntiCorruptionLayer acl; + + /** + * Places the order in the modern system. If the order is already present in the legacy system, + * then no need to place it again. + */ + public void placeOrder(ModernOrder order) throws ShopException { + + String id = order.getId(); + // check if the order is already present in the legacy system + Optional orderInObsoleteSystem = acl.findOrderInLegacySystem(id); + + if (orderInObsoleteSystem.isPresent()) { + var legacyOrder = orderInObsoleteSystem.get(); + if (!order.equals(legacyOrder)) { + throw ShopException.throwIncorrectData(legacyOrder.toString(), order.toString()); + } + } else { + store.put(id, order); + } + } + + /** Finds the order in the modern system. */ + public Optional findOrder(String orderId) { + return store.get(orderId); + } +} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernStore.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernStore.java new file mode 100644 index 000000000000..4fb3952fae5e --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernStore.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system.modern; + +import com.iluwatar.corruption.system.DataStore; +import org.springframework.stereotype.Service; + +/** The class represents a data store for the modern system. */ +@Service +public class ModernStore extends DataStore {} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Shipment.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Shipment.java new file mode 100644 index 000000000000..085a3921ceeb --- /dev/null +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Shipment.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system.modern; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * The class represents a shipment in the modern system. The class is used by the modern system to + * store the data. + */ +@Data +@AllArgsConstructor +public class Shipment { + private String item; + private int qty; + private int price; +} diff --git a/anti-corruption-layer/src/main/resources/application.properties b/anti-corruption-layer/src/main/resources/application.properties new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/anti-corruption-layer/src/test/java/com/iluwatar/corruption/system/AntiCorruptionLayerTest.java b/anti-corruption-layer/src/test/java/com/iluwatar/corruption/system/AntiCorruptionLayerTest.java new file mode 100644 index 000000000000..ee46d124eee6 --- /dev/null +++ b/anti-corruption-layer/src/test/java/com/iluwatar/corruption/system/AntiCorruptionLayerTest.java @@ -0,0 +1,96 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.corruption.system; + +import static org.junit.jupiter.api.Assertions.*; + +import com.iluwatar.corruption.system.legacy.LegacyOrder; +import com.iluwatar.corruption.system.legacy.LegacyShop; +import com.iluwatar.corruption.system.modern.Customer; +import com.iluwatar.corruption.system.modern.ModernOrder; +import com.iluwatar.corruption.system.modern.ModernShop; +import com.iluwatar.corruption.system.modern.Shipment; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@SpringBootTest +public class AntiCorruptionLayerTest { + + @Autowired private LegacyShop legacyShop; + + @Autowired private ModernShop modernShop; + + /** + * Test the anti-corruption layer. Main intention is to demonstrate how the anti-corruption layer + * works. The 2 shops (modern and legacy) should operate independently and in the same time + * synchronize the data. + */ + @Test + public void antiCorruptionLayerTest() throws ShopException { + // a new order comes to the legacy shop. + LegacyOrder legacyOrder = new LegacyOrder("1", "addr1", "item1", 1, 1); + // place the order in the legacy shop. + legacyShop.placeOrder(legacyOrder); + // the order is placed as usual since there is no other orders with the id in the both systems. + Optional legacyOrderWithIdOne = legacyShop.findOrder("1"); + assertEquals(Optional.of(legacyOrder), legacyOrderWithIdOne); + + // a new order (or maybe just the same order) appears in the modern shop + ModernOrder modernOrder = + new ModernOrder("1", new Customer("addr1"), new Shipment("item1", 1, 1), ""); + // the system places it, but it checks if there is an order with the same id in the legacy shop. + modernShop.placeOrder(modernOrder); + + Optional modernOrderWithIdOne = modernShop.findOrder("1"); + // there is no new order placed since there is already an order with the same id in the legacy + // shop. + assertTrue(modernOrderWithIdOne.isEmpty()); + } + + /** + * Test the anti-corruption layer when a conflict occurs between systems. This test ensures that + * an exception is thrown when conflicting orders are placed. + */ + @Test + public void antiCorruptionLayerWithExTest() throws ShopException { + // a new order comes to the legacy shop. + LegacyOrder legacyOrder = new LegacyOrder("1", "addr1", "item1", 1, 1); + // place the order in the legacy shop. + legacyShop.placeOrder(legacyOrder); + // the order is placed as usual since there is no other orders with the id in the both systems. + Optional legacyOrderWithIdOne = legacyShop.findOrder("1"); + assertEquals(Optional.of(legacyOrder), legacyOrderWithIdOne); + // a new order but with the same id and different data appears in the modern shop + ModernOrder modernOrder = + new ModernOrder("1", new Customer("addr1"), new Shipment("item1", 10, 1), ""); + // the system rejects the order since there are 2 orders with contradiction there. + assertThrows(ShopException.class, () -> modernShop.placeOrder(modernOrder)); + } +} diff --git a/api-gateway/README.md b/api-gateway/README.md deleted file mode 100644 index 23014ae0b8af..000000000000 --- a/api-gateway/README.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -layout: pattern -title: API Gateway -folder: api-gateway -permalink: /patterns/api-gateway/ -categories: Architectural -tags: -- Java -- Difficulty-Intermediate -- Spring ---- - -## Intent - -Aggregate calls to microservices in a single location: the API Gateway. The user makes a single -call to the API Gateway, and the API Gateway then calls each relevant microservice. - -![alt text](./etc/api-gateway.png "API Gateway") - -## Applicability - -Use the API Gateway pattern when - -* you're also using the Microservices pattern and need a single point of aggregation for your -microservice calls - -## Credits - -* [microservices.io - API Gateway](http://microservices.io/patterns/apigateway.html) -* [NGINX - Building Microservices: Using an API Gateway](https://www.nginx.com/blog/building-microservices-using-an-api-gateway/) diff --git a/api-gateway/api-gateway-service/pom.xml b/api-gateway/api-gateway-service/pom.xml deleted file mode 100644 index 609fca88d24b..000000000000 --- a/api-gateway/api-gateway-service/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - api-gateway - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - api-gateway-service - jar - - - - - org.springframework.boot - spring-boot-dependencies - - - - - - org.springframework - spring-webmvc - - - org.springframework.boot - spring-boot-starter-web - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.mockito - mockito-core - test - - - org.apache.httpcomponents - httpclient - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - - - repackage - - - - - - - \ No newline at end of file diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java deleted file mode 100644 index aab1247963a7..000000000000 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java +++ /dev/null @@ -1,64 +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.api.gateway; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Resource; - -/** - * The ApiGateway aggregates calls to microservices based on the needs of the individual clients. - */ -@RestController -public class ApiGateway { - - @Resource - private ImageClient imageClient; - - @Resource - private PriceClient priceClient; - - /** - * Retrieves product information that desktop clients need - * @return Product information for clients on a desktop - */ - @RequestMapping("/desktop") - public DesktopProduct getProductDesktop() { - DesktopProduct desktopProduct = new DesktopProduct(); - desktopProduct.setImagePath(imageClient.getImagePath()); - desktopProduct.setPrice(priceClient.getPrice()); - return desktopProduct; - } - - /** - * Retrieves product information that mobile clients need - * @return Product information for clients on a mobile device - */ - @RequestMapping("/mobile") - public MobileProduct getProductMobile() { - MobileProduct mobileProduct = new MobileProduct(); - mobileProduct.setPrice(priceClient.getPrice()); - return mobileProduct; - } -} diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java deleted file mode 100644 index 3b529aa5fe96..000000000000 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java +++ /dev/null @@ -1,66 +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.api.gateway; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * With the Microservices pattern, a client may need data from multiple different microservices. - * If the client called each microservice directly, that could contribute to longer load times, - * since the client would have to make a network request for each microservice called. Moreover, - * having the client call each microservice directly ties the client to that microservice - if the - * internal implementations of the microservices change (for example, if two microservices are - * combined sometime in the future) or if the location (host and port) of a microservice changes, - * then every client that makes use of those microservices must be updated. - * - *

- * The intent of the API Gateway pattern is to alleviate some of these issues. In the API Gateway - * pattern, an additional entity (the API Gateway) is placed between the client and the - * microservices. The job of the API Gateway is to aggregate the calls to the microservices. - * Rather than the client calling each microservice individually, the client calls the API Gateway - * a single time. The API Gateway then calls each of the microservices that the client needs. - * - *

- * This implementation shows what the API Gateway pattern could look like for an e-commerce site. - * The {@link ApiGateway} makes calls to the Image and Price microservices using the - * {@link ImageClientImpl} and {@link PriceClientImpl} respectively. Customers viewing the site on a - * desktop device can see both price information and an image of a product, so the {@link ApiGateway} - * calls both of the microservices and aggregates the data in the {@link DesktopProduct} model. - * However, mobile users only see price information; they do not see a product image. For mobile - * users, the {@link ApiGateway} only retrieves price information, which it uses to populate the - * {@link MobileProduct}. - */ -@SpringBootApplication -public class App { - - /** - * Program entry point - * - * @param args - * command line args - */ - public static void main(String[] args) { - SpringApplication.run(App.class, args); - } -} diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java deleted file mode 100644 index e72b98e73c40..000000000000 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java +++ /dev/null @@ -1,54 +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.api.gateway; - -/** - * Encapsulates all of the information that a desktop client needs to display a product. - */ -public class DesktopProduct { - /** - * The price of the product - */ - private String price; - - /** - * The path to the image of the product - */ - private String imagePath; - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getImagePath() { - return imagePath; - } - - public void setImagePath(String imagePath) { - this.imagePath = imagePath; - } -} diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java deleted file mode 100644 index ebabfe839b69..000000000000 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.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.api.gateway; - -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.springframework.stereotype.Component; - -import java.io.IOException; - -/** - * An adapter to communicate with the Image microservice - */ -@Component -public class ImageClientImpl implements ImageClient { - /** - * Makes a simple HTTP Get request to the Image microservice - * @return The path to the image - */ - @Override - public String getImagePath() { - String response = null; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet("http://localhost:50005/image-path"); - try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { - response = EntityUtils.toString(httpResponse.getEntity()); - } - } catch (IOException e) { - e.printStackTrace(); - } - return response; - } -} diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java deleted file mode 100644 index 87f44761c649..000000000000 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.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.api.gateway; - -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.springframework.stereotype.Component; - -import java.io.IOException; - -/** - * An adapter to communicate with the Price microservice - */ -@Component -public class PriceClientImpl implements PriceClient { - /** - * Makes a simple HTTP Get request to the Price microservice - * @return The price of the product - */ - @Override - public String getPrice() { - String response = null; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet("http://localhost:50006/price"); - try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { - response = EntityUtils.toString(httpResponse.getEntity()); - } - } catch (IOException e) { - e.printStackTrace(); - } - return response; - } -} diff --git a/api-gateway/api-gateway-service/src/main/resources/application.properties b/api-gateway/api-gateway-service/src/main/resources/application.properties deleted file mode 100644 index ae91c5eb5625..000000000000 --- a/api-gateway/api-gateway-service/src/main/resources/application.properties +++ /dev/null @@ -1,24 +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. -# - -server.port=50004 \ No newline at end of file diff --git a/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java b/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java deleted file mode 100644 index a86d991c8eda..000000000000 --- a/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java +++ /dev/null @@ -1,81 +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.api.gateway; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - -/** - * Test API Gateway Pattern - */ -public class ApiGatewayTest { - - @InjectMocks - private ApiGateway apiGateway; - - @Mock - private ImageClient imageClient; - - @Mock - private PriceClient priceClient; - - @BeforeEach - public void setup() { - MockitoAnnotations.initMocks(this); - } - - /** - * Tests getting the data for a desktop client - */ - @Test - public void testGetProductDesktop() { - String imagePath = "/product-image.png"; - String price = "20"; - when(imageClient.getImagePath()).thenReturn(imagePath); - when(priceClient.getPrice()).thenReturn(price); - - DesktopProduct desktopProduct = apiGateway.getProductDesktop(); - - assertEquals(price, desktopProduct.getPrice()); - assertEquals(imagePath, desktopProduct.getImagePath()); - } - - /** - * Tests getting the data for a mobile client - */ - @Test - public void testGetProductMobile() { - String price = "20"; - when(priceClient.getPrice()).thenReturn(price); - - MobileProduct mobileProduct = apiGateway.getProductMobile(); - - assertEquals(price, mobileProduct.getPrice()); - } -} diff --git a/api-gateway/image-microservice/pom.xml b/api-gateway/image-microservice/pom.xml deleted file mode 100644 index e90747eb90e5..000000000000 --- a/api-gateway/image-microservice/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - api-gateway - com.iluwatar - 1.20.0-SNAPSHOT - - - 4.0.0 - image-microservice - jar - - - - - org.springframework.boot - spring-boot-dependencies - - - - - - org.springframework - spring-webmvc - - - org.springframework.boot - spring-boot-starter-web - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - - - repackage - - - - - - - \ No newline at end of file diff --git a/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java b/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java deleted file mode 100644 index 18d0d400806c..000000000000 --- a/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java +++ /dev/null @@ -1,43 +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.image.microservice; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -/** - * Exposes the Image microservice's endpoints - */ -@RestController -public class ImageController { - - /** - * An endpoint for a user to retrieve an image path - * @return An image path - */ - @RequestMapping(value = "/image-path", method = RequestMethod.GET) - public String getImagePath() { - return "/product-image.png"; - } -} diff --git a/api-gateway/image-microservice/src/main/resources/application.properties b/api-gateway/image-microservice/src/main/resources/application.properties deleted file mode 100644 index 5830a3c95c55..000000000000 --- a/api-gateway/image-microservice/src/main/resources/application.properties +++ /dev/null @@ -1,24 +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. -# - -server.port=50005 \ No newline at end of file diff --git a/api-gateway/pom.xml b/api-gateway/pom.xml deleted file mode 100644 index 72468c7ebf8d..000000000000 --- a/api-gateway/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - java-design-patterns - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - api-gateway - pom - - image-microservice - price-microservice - api-gateway-service - - diff --git a/api-gateway/price-microservice/pom.xml b/api-gateway/price-microservice/pom.xml deleted file mode 100644 index deb0627f4b12..000000000000 --- a/api-gateway/price-microservice/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - api-gateway - com.iluwatar - 1.20.0-SNAPSHOT - - - 4.0.0 - price-microservice - jar - - - - - org.springframework.boot - spring-boot-dependencies - - - - - - org.springframework - spring-webmvc - - - org.springframework.boot - spring-boot-starter-web - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - - - repackage - - - - - - - \ No newline at end of file diff --git a/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java b/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java deleted file mode 100644 index 906b55c88d14..000000000000 --- a/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java +++ /dev/null @@ -1,43 +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.price.microservice; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -/** - * Exposes the Price microservice's endpoints - */ -@RestController -public class PriceController { - - /** - * An endpoint for a user to retrieve a product's price - * @return A product's price - */ - @RequestMapping(value = "/price", method = RequestMethod.GET) - public String getPrice() { - return "20"; - } -} diff --git a/api-gateway/price-microservice/src/main/resources/application.properties b/api-gateway/price-microservice/src/main/resources/application.properties deleted file mode 100644 index d7b443b268e7..000000000000 --- a/api-gateway/price-microservice/src/main/resources/application.properties +++ /dev/null @@ -1,24 +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. -# - -server.port=50006 \ No newline at end of file diff --git a/arrange-act-assert/README.md b/arrange-act-assert/README.md new file mode 100644 index 000000000000..584d8601a23e --- /dev/null +++ b/arrange-act-assert/README.md @@ -0,0 +1,167 @@ +--- +title: "Arrange/Act/Assert Pattern in Java: Enhance Testing Clarity and Simplicity" +shortTitle: Arrange/Act/Assert +description: "Learn how to use the Arrange/Act/Assert pattern to structure your unit tests in Java. Improve readability and maintainability of your code with clear testing phases." +category: Testing +language: en +tag: + - Code simplification + - Isolation + - Testing +--- + +## Also known as + +* Given/When/Then + +## Intent of Arrange/Act/Assert Design Pattern + +The Arrange/Act/Assert pattern is essential in unit testing in Java. This testing method structures unit tests clearly by dividing them into three distinct sections: setup (Arrange), execution (Act), and verification (Assert). + +## Detailed Explanation of Arrange/Act/Assert Pattern with Real-World Examples + +Real-world example + +> Imagine you are organizing a small event. To ensure everything runs smoothly, you follow a pattern similar to Arrange/Act/Assert: +> +> 1. **Arrange**: You set up the venue, prepare the guest list, arrange seating, and organize the catering. +> 2. **Act**: You conduct the event according to the plan, welcoming guests, serving food, and following the schedule. +> 3. **Assert**: After the event, you evaluate its success by checking guest feedback, ensuring all tasks were completed, and reviewing if everything went as planned. +> +> This clear separation of preparation, execution, and evaluation helps ensure the event is well-organized and successful, mirroring the structured approach of the Arrange/Act/Assert pattern in software testing. + +In plain words + +> Arrange/Act/Assert is a testing pattern that organizes tests into three clear steps for easy maintenance. + +WikiWikiWeb says + +> Arrange/Act/Assert is a pattern for arranging and formatting code in UnitTest methods. + +Flowchart + +![Arrange/Act/Assert flowchart](./etc/arrange-act-assert-flowchart.png "Arrange/Act/Assert flowchart") + +## Programmatic Example of Arrange/Act/Assert Pattern in Java + +We need to write comprehensive and clear unit test suite for a class. Using the Arrange/Act/Assert pattern in Java testing ensures clarity. + +Let's first introduce our `Cash` class to be unit tested. + +```java +public class Cash { + + private int amount; + + Cash(int amount) { + this.amount = amount; + } + + void plus(int addend) { + amount += addend; + } + + boolean minus(int subtrahend) { + if (amount >= subtrahend) { + amount -= subtrahend; + return true; + } else { + return false; + } + } + + int count() { + return amount; + } +} +``` + +Then we write our unit tests according to Arrange/Act/Assert pattern. Notice the clearly separated steps for each unit test. + +```java +class CashAAATest { + + @Test + void testPlus() { + //Arrange + var cash = new Cash(3); + //Act + cash.plus(4); + //Assert + assertEquals(7, cash.count()); + } + + @Test + void testMinus() { + //Arrange + var cash = new Cash(8); + //Act + var result = cash.minus(5); + //Assert + assertTrue(result); + assertEquals(3, cash.count()); + } + + @Test + void testInsufficientMinus() { + //Arrange + var cash = new Cash(1); + //Act + var result = cash.minus(6); + //Assert + assertFalse(result); + assertEquals(1, cash.count()); + } + + @Test + void testUpdate() { + //Arrange + var cash = new Cash(5); + //Act + cash.plus(6); + var result = cash.minus(3); + //Assert + assertTrue(result); + assertEquals(8, cash.count()); + } +} +``` + +## When to Use the Arrange/Act/Assert Pattern in Java + +Use Arrange/Act/Assert pattern when + +* Unit testing, especially within the context of TDD and BDD +* Anywhere clarity and structure are needed in test cases + +## Real-World Applications of Arrange/Act/Assert Pattern in Java + +* This pattern is particularly useful when practicing TDD and/or BDD methodologies in Java. +* Utilized in various programming languages and testing frameworks, such as JUnit (Java), NUnit (.NET), and xUnit frameworks. + +## Benefits and Trade-offs of Arrange/Act/Assert Pattern + +Benefits: + +* Improved readability of tests by clearly separating the setup, action, and verification steps. +* Easier maintenance and understanding of tests, as each test is structured in a predictable way. +* Facilitates debugging by isolating test failures to specific phases within the test. + +Trade-offs: + +* May introduce redundancy in tests, as similar arrangements may be repeated across tests. +* Some complex tests might not fit neatly into this structure, requiring additional context or setup outside these three phases. + +## Related Java Design Patterns + +* [Page Object](https://java-design-patterns.com/patterns/page-object/): A pattern for organizing UI tests that can be used in conjunction with Arrange/Act/Assert. + +## References and Credits + +* [The Art of Unit Testing: with examples in C#](https://amzn.to/49IbdwO) +* [Test Driven Development: By Example](https://amzn.to/3wEwKbF) +* [Unit Testing Principles, Practices, and Patterns: Effective testing styles, patterns, and reliable automation for unit testing, mocking, and integration testing with examples in C#](https://amzn.to/4ayjpiM) +* [xUnit Test Patterns: Refactoring Test Code](https://amzn.to/4dHGDpm) +* [Arrange, Act, Assert: What is AAA Testing?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx) +* [Bill Wake: 3A – Arrange, Act, Assert (NCrunch)](https://xp123.com/articles/3a-arrange-act-assert/) +* [GivenWhenThen (Martin Fowler)](https://martinfowler.com/bliki/GivenWhenThen.html) diff --git a/arrange-act-assert/etc/arrange-act-assert-flowchart.png b/arrange-act-assert/etc/arrange-act-assert-flowchart.png new file mode 100644 index 000000000000..8b7615352523 Binary files /dev/null and b/arrange-act-assert/etc/arrange-act-assert-flowchart.png differ diff --git a/arrange-act-assert/etc/arrange-act-assert.urm.puml b/arrange-act-assert/etc/arrange-act-assert.urm.puml new file mode 100644 index 000000000000..4b22d2a4e4bb --- /dev/null +++ b/arrange-act-assert/etc/arrange-act-assert.urm.puml @@ -0,0 +1,11 @@ +@startuml +package com.iluwatar.arrangeactassert { + class Cash { + - amount : int + ~ Cash(amount : int) + ~ count() : int + ~ minus(subtrahend : int) : boolean + ~ plus(addend : int) + } +} +@enduml \ No newline at end of file diff --git a/arrange-act-assert/pom.xml b/arrange-act-assert/pom.xml new file mode 100644 index 000000000000..6b8ba1b2d490 --- /dev/null +++ b/arrange-act-assert/pom.xml @@ -0,0 +1,43 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + arrange-act-assert + + + org.junit.jupiter + junit-jupiter-engine + test + + + diff --git a/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java b/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java new file mode 100644 index 000000000000..0c31b1f89f44 --- /dev/null +++ b/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.arrangeactassert; + +import lombok.AllArgsConstructor; + +/** + * Arrange/Act/Assert (AAA) is a unit test pattern. In this simple example, we have a ({@link Cash}) + * object for plus, minus and counting amount. + */ +@AllArgsConstructor +public class Cash { + + private int amount; + + // plus + void plus(int addend) { + amount += addend; + } + + // minus + boolean minus(int subtrahend) { + if (amount >= subtrahend) { + amount -= subtrahend; + return true; + } else { + return false; + } + } + + // count + int count() { + return amount; + } +} diff --git a/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java new file mode 100644 index 000000000000..ebb261277080 --- /dev/null +++ b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java @@ -0,0 +1,103 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.arrangeactassert; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * Arrange/Act/Assert (AAA) is a pattern for organizing unit tests. It is a way to structure your + * tests, so they're easier to read, maintain and enhance. + * + *

It breaks tests down into three clear and distinct steps: + * + *

1. Arrange: Perform the setup and initialization required for the test. + * + *

2. Act: Take action(s) required for the test. + * + *

3. Assert: Verify the outcome(s) of the test. + * + *

This pattern has several significant benefits. It creates a clear separation between a test's + * setup, operations, and results. This structure makes the code easier to read and understand. If + * you place the steps in order and format your code to separate them, you can scan a test and + * quickly comprehend what it does. + * + *

It also enforces a certain degree of discipline when you write your tests. You have to think + * clearly about the three steps your test will perform. But it makes tests more natural to write at + * the same time since you already have an outline. + * + *

In ({@link CashAAATest}) we have four test methods. Each of them has only one reason to change + * and one reason to fail. In a large and complicated code base, tests that honor the single + * responsibility principle are much easier to troubleshoot. + */ +class CashAAATest { + + @Test + void testPlus() { + // Arrange + var cash = new Cash(3); + // Act + cash.plus(4); + // Assert + assertEquals(7, cash.count()); + } + + @Test + void testMinus() { + // Arrange + var cash = new Cash(8); + // Act + var result = cash.minus(5); + // Assert + assertTrue(result); + assertEquals(3, cash.count()); + } + + @Test + void testInsufficientMinus() { + // Arrange + var cash = new Cash(1); + // Act + var result = cash.minus(6); + // Assert + assertFalse(result); + assertEquals(1, cash.count()); + } + + @Test + void testUpdate() { + // Arrange + var cash = new Cash(5); + // Act + cash.plus(6); + var result = cash.minus(3); + // Assert + assertTrue(result); + assertEquals(8, cash.count()); + } +} diff --git a/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java new file mode 100644 index 000000000000..5756822516b8 --- /dev/null +++ b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java @@ -0,0 +1,60 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.arrangeactassert; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * ({@link CashAAATest}) is an anti-example of AAA pattern. This test is functionally correct, but + * with the addition of a new feature, it needs refactoring. There are an awful lot of steps in that + * test method, but it verifies the class' important behavior in just eleven lines. It violates the + * single responsibility principle. If this test method failed after a small code change, it might + * take some digging to discover why. + */ +class CashAntiAAATest { + + @Test + void testCash() { + // initialize + var cash = new Cash(3); + // test plus + cash.plus(4); + assertEquals(7, cash.count()); + // test minus + cash = new Cash(8); + assertTrue(cash.minus(5)); + assertEquals(3, cash.count()); + assertFalse(cash.minus(6)); + assertEquals(3, cash.count()); + // test update + cash.plus(5); + assertTrue(cash.minus(5)); + assertEquals(3, cash.count()); + } +} diff --git a/async-method-invocation/README.md b/async-method-invocation/README.md index 2d99820c5d82..519152e1268c 100644 --- a/async-method-invocation/README.md +++ b/async-method-invocation/README.md @@ -1,33 +1,217 @@ --- -layout: pattern -title: Async Method Invocation -folder: async-method-invocation -permalink: /patterns/async-method-invocation/ -categories: Concurrency -tags: - - Java - - Difficulty-Intermediate - - Functional - - Reactive +title: "Async Method Invocation Pattern in Java: Elevate Performance with Asynchronous Programming" +shortTitle: Async Method Invocation +description: "Learn about the Async Method Invocation pattern in Java for asynchronous method calls, enhancing concurrency, scalability, and responsiveness in your applications. Explore real-world examples and code implementations." +category: Concurrency +language: en +tag: + - Asynchronous + - Decoupling + - Reactive + - Scalability + - Thread management --- -## Intent -Asynchronous method invocation is pattern where the calling thread -is not blocked while waiting results of tasks. The pattern provides parallel -processing of multiple independent tasks and retrieving the results via -callbacks or waiting until everything is done. +## Also known as -![alt text](./etc/async-method-invocation.png "Async Method Invocation") +* Asynchronous Procedure Call -## Applicability -Use async method invocation pattern when +## Intent of Async Method Invocation Design Pattern -* you have multiple independent tasks that can run in parallel -* you need to improve the performance of a group of sequential tasks -* you have limited amount of processing capacity or long running tasks and the - caller should not wait the tasks to be ready +The Async Method Invocation pattern is designed to enhance concurrency by allowing methods to be called asynchronously. This pattern helps in executing parallel tasks, reducing wait times, and improving system throughput. -## Real world examples +## Detailed Explanation of Async Method Invocation Pattern with Real-World Examples -* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html), [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) and [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) (Java) -* [Task-based Asynchronous Pattern](https://msdn.microsoft.com/en-us/library/hh873175.aspx) (.NET) +Real-world example + +> Asynchronous method invocation enables non-blocking operations, allowing multiple processes to run concurrently. This pattern is particularly useful in applications requiring high scalability and performance, such as web servers and microservices. +> +> In the context of space rockets, an analogous example of the Async Method Invocation pattern can be seen in the communication between the mission control center and the onboard systems of the rocket. When mission control sends a command to the rocket to adjust its trajectory or perform a system check, they do not wait idly for the rocket to complete the task and report back. Instead, mission control continues to monitor other aspects of the mission and manage different tasks. The rocket executes the command asynchronously and sends a status update or result back to mission control once the operation is complete. This allows mission control to efficiently manage multiple concurrent operations without being blocked by any single task, similar to how asynchronous method invocation works in software systems. + +In plain words + +> Asynchronous method invocation starts task processing and returns immediately before the task is ready. The results of the task processing are returned to the caller later. + +Wikipedia says + +> In multithreaded computer programming, asynchronous method invocation (AMI), also known as asynchronous method calls or the asynchronous pattern is a design pattern in which the call site is not blocked while waiting for the called code to finish. Instead, the calling thread is notified when the reply arrives. Polling for a reply is an undesired option. + +Sequence diagram + +![Async Method Invocation sequence diagram](./etc/async-method-invocation-sequence-diagram.png "Async Method Invocation sequence diagram") + +## Programmatic Example of Async Method Invocation Pattern in Java + +Consider a scenario where multiple tasks need to be executed simultaneously. Using the Async Method Invocation pattern, you can initiate these tasks without waiting for each to complete, thus optimizing resource usage and reducing latency. + +In this example, we are launching space rockets and deploying lunar rovers. + +The application demonstrates the async method invocation pattern. The key parts of the pattern are`AsyncResult` which is an intermediate container for an asynchronously evaluated value, `AsyncCallback` which can be provided to be executed on task completion and `AsyncExecutor` that manages the execution of the async tasks. + +```java +public interface AsyncResult { + boolean isCompleted(); + + T getValue() throws ExecutionException; + + void await() throws InterruptedException; +} +``` + +```java +public interface AsyncCallback { + void onComplete(T value); + + void onError(Exception ex); +} +``` + +```java +public interface AsyncExecutor { + AsyncResult startProcess(Callable task); + + AsyncResult startProcess(Callable task, AsyncCallback callback); + + T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException; +} +``` + +`ThreadAsyncExecutor` is an implementation of `AsyncExecutor`. Some of its key parts are highlighted next. + +```java +public class ThreadAsyncExecutor implements AsyncExecutor { + + @Override + public AsyncResult startProcess(Callable task) { + return startProcess(task, null); + } + + @Override + public AsyncResult startProcess(Callable task, AsyncCallback callback) { + var result = new CompletableResult<>(callback); + new Thread( + () -> { + try { + result.setValue(task.call()); + } catch (Exception ex) { + result.setException(ex); + } + }, + "executor-" + idx.incrementAndGet()) + .start(); + return result; + } + + @Override + public T endProcess(AsyncResult asyncResult) + throws ExecutionException, InterruptedException { + if (!asyncResult.isCompleted()) { + asyncResult.await(); + } + return asyncResult.getValue(); + } +} +``` + +Then we are ready to launch some rockets to see how everything works together. + +```java + public static void main(String[] args) throws Exception { + // construct a new executor that will run async tasks + var executor = new ThreadAsyncExecutor(); + + // start few async tasks with varying processing times, two last with callback handlers + final var asyncResult1 = executor.startProcess(lazyval(10, 500)); + final var asyncResult2 = executor.startProcess(lazyval("test", 300)); + final var asyncResult3 = executor.startProcess(lazyval(50L, 700)); + final var asyncResult4 = executor.startProcess(lazyval(20, 400), + callback("Deploying lunar rover")); + final var asyncResult5 = + executor.startProcess(lazyval("callback", 600), callback("Deploying lunar rover")); + + // emulate processing in the current thread while async tasks are running in their own threads + Thread.sleep(350); // Oh boy, we are working hard here + log("Mission command is sipping coffee"); + + // wait for completion of the tasks + final var result1 = executor.endProcess(asyncResult1); + final var result2 = executor.endProcess(asyncResult2); + final var result3 = executor.endProcess(asyncResult3); + asyncResult4.await(); + asyncResult5.await(); + + // log the results of the tasks, callbacks log immediately when complete + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result1)); + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result2)); + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result3)); +} +``` + +Here's the program console output. + +``` +21:47:08.227[executor-2]INFO com.iluwatar.async.method.invocation.App-Space rocket launched successfully +21:47:08.269[main]INFO com.iluwatar.async.method.invocation.App-Mission command is sipping coffee +21:47:08.318[executor-4]INFO com.iluwatar.async.method.invocation.App-Space rocket<20>launched successfully +21:47:08.335[executor-4]INFO com.iluwatar.async.method.invocation.App-Deploying lunar rover<20> +21:47:08.414[executor-1]INFO com.iluwatar.async.method.invocation.App-Space rocket<10>launched successfully +21:47:08.519[executor-5]INFO com.iluwatar.async.method.invocation.App-Space rocket launched successfully +21:47:08.519[executor-5]INFO com.iluwatar.async.method.invocation.App-Deploying lunar rover +21:47:08.616[executor-3]INFO com.iluwatar.async.method.invocation.App-Space rocket<50>launched successfully +21:47:08.617[main]INFO com.iluwatar.async.method.invocation.App-Space rocket<10>launch complete +21:47:08.617[main]INFO com.iluwatar.async.method.invocation.App-Space rocket launch complete +21:47:08.618[main]INFO com.iluwatar.async.method.invocation.App-Space rocket<50>launch complete +``` + +## When to Use the Async Method Invocation Pattern in Java + +This pattern is ideal for applications needing to manage multiple parallel tasks efficiently. It is commonly used in scenarios such as handling background processes, improving user interface responsiveness, and managing asynchronous data processing. + +Use the async method invocation pattern when + +* When operations do not need to complete before proceeding with the next steps in a program. +* For tasks that are resource-intensive or time-consuming, such as IO operations, network requests, or complex computations, where making the operation synchronous would significantly impact performance or user experience. +* In GUI applications to prevent freezing or unresponsiveness during long-running tasks. +* In web applications for non-blocking IO operations. + +## Real-World Applications of Async Method Invocation Pattern in Java + +Many modern applications leverage the Async Method Invocation pattern, including web servers handling concurrent requests, microservices architectures, and systems requiring intensive background processing. + +* Web servers handling HTTP requests asynchronously to improve throughput and reduce latency. +* Desktop and mobile applications using background threads to perform time-consuming operations without blocking the user interface. +* Microservices architectures where services perform asynchronous communications via messaging queues or event streams. +* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html) +* [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) +* [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) +* [Task-based Asynchronous Pattern](https://msdn.microsoft.com/en-us/library/hh873175.aspx) + +## Benefits and Trade-offs of Async Method Invocation Pattern + +While this pattern offers significant performance benefits, it also introduces complexity in error handling and resource management. Proper implementation is essential to avoid potential pitfalls such as race conditions and deadlocks. + +Benefits: + +* Improved Responsiveness: The main thread or application flow remains unblocked, improving the user experience in GUI applications and overall responsiveness. +* Better Resource Utilization: By enabling parallel execution, system resources (like CPU and IO) are utilized more efficiently, potentially improving the application's throughput. +* Scalability: Easier to scale applications, as tasks can be distributed across available resources more effectively. + +Trade-offs: + +* Complexity: Introducing asynchronous operations can complicate the codebase, making it more challenging to understand, debug, and maintain. +* Resource Management: Requires careful management of threads or execution contexts, which can introduce overhead and potential resource exhaustion issues. +* Error Handling: Asynchronous operations can make error handling more complex, as exceptions may occur in different threads or at different times. + +## Related Java Design Patterns + +The Async Method Invocation pattern often works well with other design patterns like the Command Pattern for encapsulating requests, the Observer Pattern for event handling, and the Promise Pattern for managing asynchronous results. + +* [Command](https://java-design-patterns.com/patterns/command/): Asynchronous method invocation can be used to implement the Command pattern, where commands are executed asynchronously. +* [Observer](https://java-design-patterns.com/patterns/observer/): Asynchronous method invocation can be used to notify observers asynchronously when a subject's state changes. +* [Promise](https://java-design-patterns.com/patterns/promise/): The AsyncResult interface can be considered a form of Promise, representing a value that may not be available yet. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3Ti1N4f) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Java Concurrency in Practice](https://amzn.to/4ab97VU) diff --git a/async-method-invocation/etc/async-method-invocation-sequence-diagram.png b/async-method-invocation/etc/async-method-invocation-sequence-diagram.png new file mode 100644 index 000000000000..28420d783379 Binary files /dev/null and b/async-method-invocation/etc/async-method-invocation-sequence-diagram.png differ diff --git a/async-method-invocation/etc/async-method-invocation.ucls b/async-method-invocation/etc/async-method-invocation.ucls deleted file mode 100644 index f2e189eaeae0..000000000000 --- a/async-method-invocation/etc/async-method-invocation.ucls +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/async-method-invocation/etc/async-method-invocation.urm.png b/async-method-invocation/etc/async-method-invocation.urm.png new file mode 100644 index 000000000000..898c1e199bda Binary files /dev/null and b/async-method-invocation/etc/async-method-invocation.urm.png differ diff --git a/async-method-invocation/etc/async-method-invocation.urm.puml b/async-method-invocation/etc/async-method-invocation.urm.puml new file mode 100644 index 000000000000..d44665081856 --- /dev/null +++ b/async-method-invocation/etc/async-method-invocation.urm.puml @@ -0,0 +1,55 @@ +@startuml +package com.iluwatar.async.method.invocation { + class App { + - LOGGER : Logger {static} + + App() + - callback(name : String) : AsyncCallback {static} + - lazyval(value : T, delayMillis : long) : Callable {static} + - log(msg : String) {static} + + main(args : String[]) {static} + } + interface AsyncCallback { + + onComplete(T) {abstract} + + onError(Exception) {abstract} + } + interface AsyncExecutor { + + endProcess(AsyncResult) : T {abstract} + + startProcess(Callable) : AsyncResult {abstract} + + startProcess(Callable, AsyncCallback) : AsyncResult {abstract} + } + interface AsyncResult { + + await() {abstract} + + getValue() : T {abstract} + + isCompleted() : boolean {abstract} + } + class ThreadAsyncExecutor { + - idx : AtomicInteger + + ThreadAsyncExecutor() + + endProcess(asyncResult : AsyncResult) : T + + startProcess(task : Callable) : AsyncResult + + startProcess(task : Callable, callback : AsyncCallback) : AsyncResult + } + -class CompletableResult { + ~ COMPLETED : int {static} + ~ FAILED : int {static} + ~ RUNNING : int {static} + ~ callback : AsyncCallback + ~ exception : Exception + ~ lock : Object + ~ state : int + ~ value : T + ~ CompletableResult(callback : AsyncCallback) + + await() + + getValue() : T + ~ hasCallback() : boolean + + isCompleted() : boolean + ~ setException(exception : Exception) + ~ setValue(value : T) + } +} +ThreadAsyncExecutor ..|> AsyncCallback +ThreadAsyncExecutor ..|> AsyncResult +ThreadAsyncExecutor ..|> AsyncExecutor +CompletableResult ..+ ThreadAsyncExecutor +CompletableResult ..|> AsyncResult +@enduml diff --git a/async-method-invocation/pom.xml b/async-method-invocation/pom.xml index c290626304fc..d9ddd918c8e9 100644 --- a/async-method-invocation/pom.xml +++ b/async-method-invocation/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT async-method-invocation - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.async.method.invocation.App + + + + + + + + diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java index 0a387d58296a..ec3beed3be4d 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,87 +24,86 @@ */ package com.iluwatar.async.method.invocation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.concurrent.Callable; +import lombok.extern.slf4j.Slf4j; /** - * This application demonstrates the async method invocation pattern. Key parts of the pattern are - * AsyncResult which is an intermediate container for an asynchronously evaluated value, - * AsyncCallback which can be provided to be executed on task completion and AsyncExecutor - * that manages the execution of the async tasks. - *

- * The main method shows example flow of async invocations. The main thread starts multiple tasks with variable - * durations and then continues its own work. When the main thread has done it's job it collects the results of the - * async tasks. Two of the tasks are handled with callbacks, meaning the callbacks are executed immediately when the - * tasks complete. - *

- * Noteworthy difference of thread usage between the async results and callbacks is that the async results are collected - * in the main thread but the callbacks are executed within the worker threads. This should be noted when working with - * thread pools. - *

- * Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture and - * ExecutorService are the real world implementations of this pattern. But due to the nature of parallel programming, - * the implementations are not trivial. This example does not take all possible scenarios into account but rather - * provides a simple version that helps to understand the pattern. + * In this example, we are launching space rockets and deploying lunar rovers. + * + *

The application demonstrates the async method invocation pattern. The key parts of the pattern + * are AsyncResult which is an intermediate container for an asynchronously evaluated + * value, AsyncCallback which can be provided to be executed on task completion and + * AsyncExecutor that manages the execution of the async tasks. + * + *

The main method shows example flow of async invocations. The main thread starts multiple tasks + * with variable durations and then continues its own work. When the main thread has done it's job + * it collects the results of the async tasks. Two of the tasks are handled with callbacks, meaning + * the callbacks are executed immediately when the tasks complete. + * + *

Noteworthy difference of thread usage between the async results and callbacks is that the + * async results are collected in the main thread but the callbacks are executed within the worker + * threads. This should be noted when working with thread pools. + * + *

Java provides its own implementations of async method invocation pattern. FutureTask, + * CompletableFuture and ExecutorService are the real world implementations of this pattern. But due + * to the nature of parallel programming, the implementations are not trivial. This example does not + * take all possible scenarios into account but rather provides a simple version that helps to + * understand the pattern. * * @see AsyncResult * @see AsyncCallback * @see AsyncExecutor - * * @see java.util.concurrent.FutureTask * @see java.util.concurrent.CompletableFuture * @see java.util.concurrent.ExecutorService */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + private static final String ROCKET_LAUNCH_LOG_PATTERN = "Space rocket <%s> launched successfully"; - /** - * Program entry point - */ + /** Program entry point. */ public static void main(String[] args) throws Exception { // construct a new executor that will run async tasks - AsyncExecutor executor = new ThreadAsyncExecutor(); + var executor = new ThreadAsyncExecutor(); // start few async tasks with varying processing times, two last with callback handlers - AsyncResult asyncResult1 = executor.startProcess(lazyval(10, 500)); - AsyncResult asyncResult2 = executor.startProcess(lazyval("test", 300)); - AsyncResult asyncResult3 = executor.startProcess(lazyval(50L, 700)); - AsyncResult asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Callback result 4")); - AsyncResult asyncResult5 = executor.startProcess(lazyval("callback", 600), callback("Callback result 5")); + final var asyncResult1 = executor.startProcess(lazyval(10, 500)); + final var asyncResult2 = executor.startProcess(lazyval("test", 300)); + final var asyncResult3 = executor.startProcess(lazyval(50L, 700)); + final var asyncResult4 = + executor.startProcess(lazyval(20, 400), callback("Deploying lunar rover")); + final var asyncResult5 = + executor.startProcess(lazyval("callback", 600), callback("Deploying lunar rover")); // emulate processing in the current thread while async tasks are running in their own threads - Thread.sleep(350); // Oh boy I'm working hard here - log("Some hard work done"); + Thread.sleep(350); // Oh boy, we are working hard here + log("Mission command is sipping coffee"); // wait for completion of the tasks - Integer result1 = executor.endProcess(asyncResult1); - String result2 = executor.endProcess(asyncResult2); - Long result3 = executor.endProcess(asyncResult3); + final var result1 = executor.endProcess(asyncResult1); + final var result2 = executor.endProcess(asyncResult2); + final var result3 = executor.endProcess(asyncResult3); asyncResult4.await(); asyncResult5.await(); // log the results of the tasks, callbacks log immediately when complete - log("Result 1: " + result1); - log("Result 2: " + result2); - log("Result 3: " + result3); + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result1)); + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result2)); + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result3)); } /** * Creates a callable that lazily evaluates to given value with artificial delay. * - * @param value - * value to evaluate - * @param delayMillis - * artificial delay in milliseconds + * @param value value to evaluate + * @param delayMillis artificial delay in milliseconds * @return new callable for lazy evaluation */ private static Callable lazyval(T value, long delayMillis) { return () -> { Thread.sleep(delayMillis); - log("Task completed with: " + value); + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, value)); return value; }; } @@ -110,16 +111,19 @@ private static Callable lazyval(T value, long delayMillis) { /** * Creates a simple callback that logs the complete status of the async result. * - * @param name - * callback name + * @param name callback name * @return new async callback */ private static AsyncCallback callback(String name) { - return (value, ex) -> { - if (ex.isPresent()) { - log(name + " failed: " + ex.map(Exception::getMessage).orElse("")); - } else { - log(name + ": " + value); + return new AsyncCallback<>() { + @Override + public void onComplete(T value) { + log(name + " <" + value + ">"); + } + + @Override + public void onError(Exception ex) { + log(name + " failed: " + ex.getMessage()); } }; } diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncCallback.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncCallback.java index 5a291f996d9a..2dfbaf9a188a 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncCallback.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncCallback.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,22 +24,24 @@ */ package com.iluwatar.async.method.invocation; -import java.util.Optional; - /** - * - * AsyncCallback interface + * AsyncCallback interface. * - * @param - * + * @param Type of Result */ public interface AsyncCallback { /** - * Complete handler which is executed when async task is completed or fails execution. + * Complete handler which is executed when async task is completed. + * + * @param value the evaluated value from async task + */ + void onComplete(T value); + + /** + * Error handler which is executed when async task fails execution. * - * @param value the evaluated value from async task, undefined when execution fails - * @param ex empty value if execution succeeds, some exception if executions fails + * @param ex exception which was thrown during async task execution(non-null) */ - void onComplete(T value, Optional ex); + void onError(Exception ex); } diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java index 800bc2728fad..3bae90830098 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,11 +27,7 @@ import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; -/** - * - * AsyncExecutor interface - * - */ +/** AsyncExecutor interface. */ public interface AsyncExecutor { /** diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java index f7fd9ab61e30..3eebdc4e773d 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,7 +27,8 @@ import java.util.concurrent.ExecutionException; /** - * AsyncResult interface + * AsyncResult interface. + * * @param parameter returned when getValue is invoked */ public interface AsyncResult { 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 d12ebbe19297..a1261f34184c 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,19 +24,14 @@ */ package com.iluwatar.async.method.invocation; -import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; -/** - * - * Implementation of async executor that creates a new thread for every task. - * - */ +/** Implementation of async executor that creates a new thread for every task. */ public class ThreadAsyncExecutor implements AsyncExecutor { - /** Index for thread naming */ + /** Index for thread naming. */ private final AtomicInteger idx = new AtomicInteger(0); @Override @@ -44,19 +41,23 @@ public AsyncResult startProcess(Callable task) { @Override public AsyncResult startProcess(Callable task, AsyncCallback callback) { - CompletableResult result = new CompletableResult<>(callback); - new Thread(() -> { - try { - result.setValue(task.call()); - } catch (Exception ex) { - result.setException(ex); - } - } , "executor-" + idx.incrementAndGet()).start(); + var result = new CompletableResult<>(callback); + new Thread( + () -> { + try { + result.setValue(task.call()); + } catch (Exception ex) { + result.setException(ex); + } + }, + "executor-" + idx.incrementAndGet()) + .start(); return result; } @Override - public T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException { + public T endProcess(AsyncResult asyncResult) + throws ExecutionException, InterruptedException { if (!asyncResult.isCompleted()) { asyncResult.await(); } @@ -64,8 +65,9 @@ public T endProcess(AsyncResult asyncResult) throws ExecutionException, I } /** - * Simple implementation of async result that allows completing it successfully with a value or exceptionally with an - * exception. A really simplified version from its real life cousins FutureTask and CompletableFuture. + * Simple implementation of async result that allows completing it successfully with a value or + * exceptionally with an exception. A really simplified version from its real life cousins + * FutureTask and CompletableFuture. * * @see java.util.concurrent.FutureTask * @see java.util.concurrent.CompletableFuture @@ -77,7 +79,7 @@ private static class CompletableResult implements AsyncResult { static final int COMPLETED = 3; final Object lock; - final Optional> callback; + final AsyncCallback callback; volatile int state = RUNNING; T value; @@ -85,36 +87,42 @@ private static class CompletableResult implements AsyncResult { CompletableResult(AsyncCallback callback) { this.lock = new Object(); - this.callback = Optional.ofNullable(callback); + this.callback = callback; + } + + boolean hasCallback() { + return callback != null; } /** - * Sets the value from successful execution and executes callback if available. Notifies any thread waiting for - * completion. + * Sets the value from successful execution and executes callback if available. Notifies any + * thread waiting for completion. * - * @param value - * value of the evaluated task + * @param value value of the evaluated task */ void setValue(T value) { this.value = value; this.state = COMPLETED; - this.callback.ifPresent(ac -> ac.onComplete(value, Optional.empty())); + if (hasCallback()) { + callback.onComplete(value); + } synchronized (lock) { lock.notifyAll(); } } /** - * Sets the exception from failed execution and executes callback if available. Notifies any thread waiting for - * completion. + * Sets the exception from failed execution and executes callback if available. Notifies any + * thread waiting for completion. * - * @param exception - * exception of the failed task + * @param exception exception of the failed task */ void setException(Exception exception) { this.exception = exception; this.state = FAILED; - this.callback.ifPresent(ac -> ac.onComplete(null, Optional.of(exception))); + if (hasCallback()) { + callback.onError(exception); + } synchronized (lock) { lock.notifyAll(); } diff --git a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java index a2744306e1a6..d58a3f6b5c30 100644 --- a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java +++ b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,22 @@ */ package com.iluwatar.async.method.invocation; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ @Test - public void test() throws Exception { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java index b5c4fff674de..d6540ce77309 100644 --- a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java +++ b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,322 +24,326 @@ */ package com.iluwatar.async.method.invocation; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Matchers; - -import java.util.Optional; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; - import static java.time.Duration.ofMillis; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTimeout; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; -/** - * Date: 12/6/15 - 10:49 AM - * - * @author Jeroen Meulemeester - */ -public class ThreadAsyncExecutorTest { +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; - /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} - */ +/** ThreadAsyncExecutorTest */ +class ThreadAsyncExecutorTest { + + @Captor private ArgumentCaptor exceptionCaptor; + + @Mock private Callable task; + + @Mock private AsyncCallback callback; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + /** Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} */ @Test - public void testSuccessfulTaskWithoutCallback() throws Exception { - assertTimeout(ofMillis(3000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - - final Object result = new Object(); - final Callable task = mock(Callable.class); - when(task.call()).thenReturn(result); - - final AsyncResult asyncResult = executor.startProcess(task); - assertNotNull(asyncResult); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); - - // Our task should only execute once ... - verify(task, times(1)).call(); - - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); - }); + void testSuccessfulTaskWithoutCallback() { + assertTimeout( + ofMillis(3000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + + final var result = new Object(); + when(task.call()).thenReturn(result); + + final var asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + // Our task should only execute once ... + verify(task, times(1)).call(); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); } /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, + * AsyncCallback)} */ @Test - public void testSuccessfulTaskWithCallback() throws Exception { - assertTimeout(ofMillis(3000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - - final Object result = new Object(); - final Callable task = mock(Callable.class); - when(task.call()).thenReturn(result); - - final AsyncCallback callback = mock(AsyncCallback.class); - final AsyncResult asyncResult = executor.startProcess(task, callback); - assertNotNull(asyncResult); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); - - // Our task should only execute once ... - verify(task, times(1)).call(); - - // ... same for the callback, we expect our object - final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); - verify(callback, times(1)).onComplete(eq(result), optionalCaptor.capture()); - - final Optional optionalException = optionalCaptor.getValue(); - assertNotNull(optionalException); - assertFalse(optionalException.isPresent()); - - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); - }); + void testSuccessfulTaskWithCallback() { + assertTimeout( + ofMillis(3000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + + final var result = new Object(); + when(task.call()).thenReturn(result); + + final var asyncResult = executor.startProcess(task, callback); + assertNotNull(asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + // Our task should only execute once ... + verify(task, times(1)).call(); + + // ... same for the callback, we expect our object + verify(callback, times(1)).onComplete(eq(result)); + verify(callback, times(0)).onError(exceptionCaptor.capture()); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); } /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while - * to execute + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a + * task takes a while to execute */ @Test - public void testLongRunningTaskWithoutCallback() throws Exception { - assertTimeout(ofMillis(5000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - - final Object result = new Object(); - final Callable task = mock(Callable.class); - when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; - }); - - final AsyncResult asyncResult = executor.startProcess(task); - assertNotNull(asyncResult); - assertFalse(asyncResult.isCompleted()); - - try { - asyncResult.getValue(); - fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); - } catch (IllegalStateException e) { - assertNotNull(e.getMessage()); - } - - // Our task should only execute once, but it can take a while ... - verify(task, timeout(3000).times(1)).call(); - - // Prevent timing issues, and wait until the result is available - asyncResult.await(); - assertTrue(asyncResult.isCompleted()); - verifyNoMoreInteractions(task); - - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); - }); + void testLongRunningTaskWithoutCallback() { + assertTimeout( + ofMillis(5000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + + final var result = new Object(); + when(task.call()) + .thenAnswer( + i -> { + Thread.sleep(1500); + return result; + }); + + final var asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail( + "Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + // Our task should only execute once, but it can take a while ... + verify(task, timeout(3000).times(1)).call(); + + // Prevent timing issues, and wait until the result is available + asyncResult.await(); + assertTrue(asyncResult.isCompleted()); + verifyNoMoreInteractions(task); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); } /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when a task - * takes a while to execute + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, + * AsyncCallback)} when a task takes a while to execute */ @Test - public void testLongRunningTaskWithCallback() throws Exception { - assertTimeout(ofMillis(5000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - - final Object result = new Object(); - final Callable task = mock(Callable.class); - when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; - }); - - final AsyncCallback callback = mock(AsyncCallback.class); - final AsyncResult asyncResult = executor.startProcess(task, callback); - assertNotNull(asyncResult); - assertFalse(asyncResult.isCompleted()); - - verifyZeroInteractions(callback); - - try { - asyncResult.getValue(); - fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); - } catch (IllegalStateException e) { - assertNotNull(e.getMessage()); - } - - // Our task should only execute once, but it can take a while ... - verify(task, timeout(3000).times(1)).call(); - - final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); - verify(callback, timeout(3000).times(1)).onComplete(eq(result), optionalCaptor.capture()); - - final Optional optionalException = optionalCaptor.getValue(); - assertNotNull(optionalException); - assertFalse(optionalException.isPresent()); - - // Prevent timing issues, and wait until the result is available - asyncResult.await(); - assertTrue(asyncResult.isCompleted()); - verifyNoMoreInteractions(task, callback); - - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); - }); + void testLongRunningTaskWithCallback() { + assertTimeout( + ofMillis(5000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + + final var result = new Object(); + when(task.call()) + .thenAnswer( + i -> { + Thread.sleep(1500); + return result; + }); + + final var asyncResult = executor.startProcess(task, callback); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + verifyNoMoreInteractions(callback); + + try { + asyncResult.getValue(); + fail( + "Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + // Our task should only execute once, but it can take a while ... + verify(task, timeout(3000).times(1)).call(); + verify(callback, timeout(3000).times(1)).onComplete(eq(result)); + verify(callback, times(0)).onError(isA(Exception.class)); + + // Prevent timing issues, and wait until the result is available + asyncResult.await(); + assertTrue(asyncResult.isCompleted()); + verifyNoMoreInteractions(task, callback); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); } /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while - * to execute, while waiting on the result using {@link ThreadAsyncExecutor#endProcess(AsyncResult)} + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a + * task takes a while to execute, while waiting on the result using {@link + * ThreadAsyncExecutor#endProcess(AsyncResult)} */ @Test - public void testEndProcess() throws Exception { - assertTimeout(ofMillis(5000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - - final Object result = new Object(); - final Callable task = mock(Callable.class); - when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; - }); - - final AsyncResult asyncResult = executor.startProcess(task); - assertNotNull(asyncResult); - assertFalse(asyncResult.isCompleted()); - - try { - asyncResult.getValue(); - fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); - } catch (IllegalStateException e) { - assertNotNull(e.getMessage()); - } - - assertSame(result, executor.endProcess(asyncResult)); - verify(task, times(1)).call(); - assertTrue(asyncResult.isCompleted()); - - // Calling end process a second time while already finished should give the same result - assertSame(result, executor.endProcess(asyncResult)); - verifyNoMoreInteractions(task); - }); + void testEndProcess() { + assertTimeout( + ofMillis(5000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + + final var result = new Object(); + when(task.call()) + .thenAnswer( + i -> { + Thread.sleep(1500); + return result; + }); + + final var asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail( + "Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + assertSame(result, executor.endProcess(asyncResult)); + verify(task, times(1)).call(); + assertTrue(asyncResult.isCompleted()); + + // Calling end process a second time while already finished should give the same result + assertSame(result, executor.endProcess(asyncResult)); + verifyNoMoreInteractions(task); + }); } /** - * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when the callable is 'null' + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when + * the callable is 'null' */ @Test - public void testNullTask() throws Exception { - assertTimeout(ofMillis(3000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final AsyncResult asyncResult = executor.startProcess(null); - - assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'."); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); - - try { - asyncResult.getValue(); - fail("Expected ExecutionException with NPE as cause"); - } catch (final ExecutionException e) { - assertNotNull(e.getMessage()); - assertNotNull(e.getCause()); - assertEquals(NullPointerException.class, e.getCause().getClass()); - } - }); - + void testNullTask() { + assertTimeout( + ofMillis(3000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + final var asyncResult = executor.startProcess(null); + + assertNotNull( + asyncResult, + "The AsyncResult should not be 'null', even though the task was 'null'."); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); } /** - * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when the - * callable is 'null', but the asynchronous callback is provided + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, + * AsyncCallback)} when the callable is 'null', but the asynchronous callback is provided */ @Test - public void testNullTaskWithCallback() throws Exception { - assertTimeout(ofMillis(3000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final AsyncCallback callback = mock(AsyncCallback.class); - final AsyncResult asyncResult = executor.startProcess(null, callback); - - assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'."); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); - - final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); - verify(callback, times(1)).onComplete(Matchers.isNull(), optionalCaptor.capture()); - - final Optional optionalException = optionalCaptor.getValue(); - assertNotNull(optionalException); - assertTrue(optionalException.isPresent()); - - final Exception exception = optionalException.get(); - assertNotNull(exception); - assertEquals(NullPointerException.class, exception.getClass()); - - try { - asyncResult.getValue(); - fail("Expected ExecutionException with NPE as cause"); - } catch (final ExecutionException e) { - assertNotNull(e.getMessage()); - assertNotNull(e.getCause()); - assertEquals(NullPointerException.class, e.getCause().getClass()); - } - }); - + void testNullTaskWithCallback() { + assertTimeout( + ofMillis(3000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + final var asyncResult = executor.startProcess(null, callback); + + assertNotNull( + asyncResult, + "The AsyncResult should not be 'null', even though the task was 'null'."); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + verify(callback, times(0)).onComplete(any()); + verify(callback, times(1)).onError(exceptionCaptor.capture()); + + final var exception = exceptionCaptor.getValue(); + assertNotNull(exception); + + assertEquals(NullPointerException.class, exception.getClass()); + + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); } /** - * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when both - * the callable and the asynchronous callback are 'null' + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, + * AsyncCallback)} when both the callable and the asynchronous callback are 'null' */ @Test - public void testNullTaskWithNullCallback() throws Exception { - assertTimeout(ofMillis(3000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); - final AsyncResult asyncResult = executor.startProcess(null, null); - - assertNotNull( - asyncResult, - "The AsyncResult should not be 'null', even though the task and callback were 'null'." - ); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); - - try { - asyncResult.getValue(); - fail("Expected ExecutionException with NPE as cause"); - } catch (final ExecutionException e) { - assertNotNull(e.getMessage()); - assertNotNull(e.getCause()); - assertEquals(NullPointerException.class, e.getCause().getClass()); - } - }); - + void testNullTaskWithNullCallback() { + assertTimeout( + ofMillis(3000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + final var asyncResult = executor.startProcess(null, null); + + assertNotNull( + asyncResult, + "The AsyncResult should not be 'null', even though the task and callback were 'null'."); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); } - -} \ No newline at end of file +} diff --git a/backpressure/README.md b/backpressure/README.md new file mode 100644 index 000000000000..d0734ad1f934 --- /dev/null +++ b/backpressure/README.md @@ -0,0 +1,156 @@ +--- +title: "Backpressure Pattern in Java: Gracefully regulate producer-to-consumer data flow to prevent overload." +shortTitle: Backpressure +description: "Dive into the Backpressure design pattern in Java through practical examples, discovering how it prevents overload while ensuring stability and peak performance by aligning data flow with consumer capacity." +category: Concurrency +language: en +tag: + - Asynchronous + - Event-driven + - Reactive + - Resilience +--- + +## Also known as + +* Flow Control +* Rate Limiting Mechanism + +## Intent of the Backpressure Design Pattern + +Control the rate of data production so downstream consumers are not overwhelmed by excessive load. + +## Detailed Explanation of Backpressure Pattern with Real-World Examples + +Real-world example + +> Imagine a busy coffee shop where multiple baristas brew drinks (producers), and a single barista is responsible for carefully crafting latte art (consumer). If drinks are brewed faster than the latte-art barista can decorate them, they pile up, risking quality issues or discarded drinks. By introducing a pacing system—only sending new cups once the latte-art barista is ready—everyone stays synchronized, ensuring minimal waste and a consistently enjoyable customer experience. + +In plain words + +> The Backpressure design pattern is a flow control mechanism that prevents overwhelming a system by regulating data production based on the consumer’s processing capacity. + +Wikipedia says + +> Back pressure (or backpressure) is the term for a resistance to the desired flow of fluid through pipes. Obstructions or tight bends create backpressure via friction loss and pressure drop. In distributed systems in particular event-driven architecture, back pressure is a technique to regulate flow of data, ensuring that components do not become overwhelmed. + +Sequence diagram + +![Backpressure sequence diagram](./etc/backpressure-sequence-diagram.png) + +## Programmatic Example of Backpressure Pattern in Java + +This example demonstrates how backpressure can be implemented using Project Reactor. We begin by creating a simple publisher that emits a stream of integers, introducing a small delay to mimic a slower production rate: + +```java +public class Publisher { + public static Flux publish(int start, int count, int delay) { + return Flux.range(start, count).delayElements(Duration.ofMillis(delay)).log(); + } +} +``` + +Next, we define a custom subscriber by extending Reactor’s BaseSubscriber. It simulates slow processing by sleeping for 500ms per item. Initially, the subscriber requests ten items; for every five items processed, it requests five more: + +```java +public class Subscriber extends BaseSubscriber { + + private static final Logger logger = LoggerFactory.getLogger(Subscriber.class); + + @Override + protected void hookOnSubscribe(@NonNull Subscription subscription) { + logger.info("subscribe()"); + request(10); //request 10 items initially + } + + @Override + protected void hookOnNext(@NonNull Integer value) { + processItem(); + logger.info("process({})", value); + if (value % 5 == 0) { + // request for the next 5 items after processing first 5 + request(5); + } + } + + @Override + protected void hookOnComplete() { + //completed processing. + } + + private void processItem() { + try { + Thread.sleep(500); // simulate slow processing + } catch (InterruptedException e) { + logger.error(e.getMessage(), e); + } + } +} +``` + +Finally, in the `main` method, we publish a range of integers and subscribe using the custom subscriber. A short sleep in the main thread allows the emission, backpressure requests, and processing to be fully observed: + +```java +public static void main(String[] args) throws InterruptedException { + Subscriber sub = new Subscriber(); + Publisher.publish(1, 8, 200).subscribe(sub); + Thread.sleep(5000); //wait for execution + +} +``` + +Below is an example of the program’s output. It shows the subscriber’s log entries, including when it requests more data and when each integer is processed: + +``` +23:09:55.746 [main] DEBUG reactor.util.Loggers -- Using Slf4j logging framework +23:09:55.762 [main] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onSubscribe(FluxConcatMapNoPrefetch.FluxConcatMapNoPrefetchSubscriber) +23:09:55.762 [main] INFO com.iluwatar.backpressure.Subscriber -- subscribe() +23:09:55.763 [main] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- request(10) +23:09:55.969 [parallel-1] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(1) +23:09:56.475 [parallel-1] INFO com.iluwatar.backpressure.Subscriber -- process(1) +23:09:56.680 [parallel-2] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(2) +23:09:57.185 [parallel-2] INFO com.iluwatar.backpressure.Subscriber -- process(2) +23:09:57.389 [parallel-3] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(3) +23:09:57.894 [parallel-3] INFO com.iluwatar.backpressure.Subscriber -- process(3) +23:09:58.099 [parallel-4] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(4) +23:09:58.599 [parallel-4] INFO com.iluwatar.backpressure.Subscriber -- process(4) +23:09:58.805 [parallel-5] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(5) +23:09:59.311 [parallel-5] INFO com.iluwatar.backpressure.Subscriber -- process(5) +23:09:59.311 [parallel-5] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- request(5) +23:09:59.516 [parallel-6] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(6) +23:10:00.018 [parallel-6] INFO com.iluwatar.backpressure.Subscriber -- process(6) +23:10:00.223 [parallel-7] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(7) +23:10:00.729 [parallel-7] INFO com.iluwatar.backpressure.Subscriber -- process(7) +23:10:00.930 [parallel-8] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(8) +23:10:01.436 [parallel-8] INFO com.iluwatar.backpressure.Subscriber -- process(8) +23:10:01.437 [parallel-8] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onComplete() +``` + +## When to Use the Backpressure Pattern In Java + +* Use in Java systems where data is produced at high velocity and consumers risk overload. +* Applicable in reactive or event-driven architectures to maintain stability under varying load conditions. + +## Benefits and Trade-offs of Backpressure Pattern + +Benefits: + +* Protects consumers from saturation and resource exhaustion. + +Trade-offs: + +* Introduces possible delays if production must slow down to match consumer capacity. +* Requires careful orchestration in complex systems with multiple concurrent data sources. + +## Related Java Design Patterns + +* [Observer Pattern](https://java-design-patterns.com/patterns/observer/): Both patterns involve a producer notifying consumers. Observer is synchronous and tightly coupled (observers know the subject). +* [Publish-Subscribe Pattern](https://java-design-patterns.com/patterns/publish-subscribe/): Both patterns deal with asynchronous data flow and can work together to manage message distribution and consumption effectively. + +## References and Credits + +* [Backpressure Explained (RedHat Developers Blog)](https://developers.redhat.com/articles/backpressure-explained) +* [Hands-On Reactive Programming in Spring 5](https://amzn.to/3YuYfyO) +* [Reactive Programming with RxJava: Creating Asynchronous, Event-Based Applications](https://amzn.to/42negbf) +* [Reactive Streams in Java](https://amzn.to/3RJjUzA) +* [Reactive Streams Specification](https://www.reactive-streams.org/) diff --git a/backpressure/etc/backpressure-sequence-diagram.png b/backpressure/etc/backpressure-sequence-diagram.png new file mode 100644 index 000000000000..b74a5d2a5362 Binary files /dev/null and b/backpressure/etc/backpressure-sequence-diagram.png differ diff --git a/backpressure/etc/backpressure.png b/backpressure/etc/backpressure.png new file mode 100644 index 000000000000..0de9ff54b673 Binary files /dev/null and b/backpressure/etc/backpressure.png differ diff --git a/backpressure/pom.xml b/backpressure/pom.xml new file mode 100644 index 000000000000..fcc15892fb8a --- /dev/null +++ b/backpressure/pom.xml @@ -0,0 +1,81 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + backpressure + + + + io.projectreactor + reactor-core + 3.8.0-M1 + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + io.projectreactor + reactor-test + 3.8.0-M1 + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.backpressure.App + + + + + + + + + \ No newline at end of file diff --git a/backpressure/src/main/java/com/iluwatar/backpressure/App.java b/backpressure/src/main/java/com/iluwatar/backpressure/App.java new file mode 100644 index 000000000000..4632c42a467f --- /dev/null +++ b/backpressure/src/main/java/com/iluwatar/backpressure/App.java @@ -0,0 +1,76 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.backpressure; + +import java.util.concurrent.CountDownLatch; + +/** + * The Backpressure pattern is a flow control mechanism. It allows a consumer to signal to a + * producer to slow down or stop sending data when it's overwhelmed. + *
  • Prevents memory overflow, CPU thrashing, and resource exhaustion. + *
  • Ensures fair usage of resources in distributed systems. + *
  • Avoids buffer bloat and latency spikes. Key concepts of this design paradigm involves + *
  • Publisher/Producer: Generates data. + *
  • Subscriber/Consumer: Receives and processes data. + * + *

    In this example we will create a {@link Publisher} and a {@link Subscriber}. Publisher + * will emit a stream of integer values with a predefined delay. Subscriber takes 500 ms to + * process one integer. Since the subscriber can't process the items fast enough we apply + * backpressure to the publisher so that it will request 10 items first, process 5 items and + * request for the next 5 again. After processing 5 items subscriber will keep requesting for + * another 5 until the stream ends. + */ +public class App { + + protected static CountDownLatch latch; + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) throws InterruptedException { + + /* + * This custom subscriber applies backpressure: + * - Has a processing delay of 0.5 milliseconds + * - Requests 10 items initially + * - Process 5 items and request for the next 5 items + */ + Subscriber sub = new Subscriber(); + // slow publisher emit 15 numbers with a delay of 200 milliseconds + Publisher.publish(1, 17, 200).subscribe(sub); + + latch = new CountDownLatch(1); + latch.await(); + + sub = new Subscriber(); + // fast publisher emit 15 numbers with a delay of 1 millisecond + Publisher.publish(1, 17, 1).subscribe(sub); + + latch = new CountDownLatch(1); + latch.await(); + } +} diff --git a/backpressure/src/main/java/com/iluwatar/backpressure/Publisher.java b/backpressure/src/main/java/com/iluwatar/backpressure/Publisher.java new file mode 100644 index 000000000000..1d39a070ae57 --- /dev/null +++ b/backpressure/src/main/java/com/iluwatar/backpressure/Publisher.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.backpressure; + +import java.time.Duration; +import reactor.core.publisher.Flux; + +/** This class is the publisher that generates the data stream. */ +public class Publisher { + + private Publisher() {} + + /** + * On message method will trigger when the subscribed event is published. + * + * @param start starting integer + * @param count how many integers to emit + * @param delay delay between each item in milliseconds + * @return a flux stream of integers + */ + public static Flux publish(int start, int count, int delay) { + return Flux.range(start, count).delayElements(Duration.ofMillis(delay)).log(); + } +} diff --git a/backpressure/src/main/java/com/iluwatar/backpressure/Subscriber.java b/backpressure/src/main/java/com/iluwatar/backpressure/Subscriber.java new file mode 100644 index 000000000000..40ff5aebc814 --- /dev/null +++ b/backpressure/src/main/java/com/iluwatar/backpressure/Subscriber.java @@ -0,0 +1,64 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.backpressure; + +import lombok.NonNull; +import lombok.extern.slf4j.Slf4j; +import org.reactivestreams.Subscription; +import reactor.core.publisher.BaseSubscriber; + +/** This class is the custom subscriber that subscribes to the data stream. */ +@Slf4j +public class Subscriber extends BaseSubscriber { + + @Override + protected void hookOnSubscribe(@NonNull Subscription subscription) { + request(10); // request 10 items initially + } + + @Override + protected void hookOnNext(@NonNull Integer value) { + processItem(); + LOGGER.info("process({})", value); + if (value % 5 == 0) { + // request for the next 5 items after processing first 5 + request(5); + } + } + + @Override + protected void hookOnComplete() { + App.latch.countDown(); + } + + private void processItem() { + try { + Thread.sleep(500); // simulate slow processing + } catch (InterruptedException e) { + LOGGER.error(e.getMessage(), e); + Thread.currentThread().interrupt(); + } + } +} diff --git a/backpressure/src/test/java/com/iluwatar/backpressure/AppTest.java b/backpressure/src/test/java/com/iluwatar/backpressure/AppTest.java new file mode 100644 index 000000000000..8fe2245a97b7 --- /dev/null +++ b/backpressure/src/test/java/com/iluwatar/backpressure/AppTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.backpressure; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +public class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/backpressure/src/test/java/com/iluwatar/backpressure/LoggerExtension.java b/backpressure/src/test/java/com/iluwatar/backpressure/LoggerExtension.java new file mode 100644 index 000000000000..e99926e00a1a --- /dev/null +++ b/backpressure/src/test/java/com/iluwatar/backpressure/LoggerExtension.java @@ -0,0 +1,60 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.backpressure; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.slf4j.LoggerFactory; + +public class LoggerExtension implements BeforeEachCallback, AfterEachCallback { + + private final ListAppender listAppender = new ListAppender<>(); + private final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + @Override + public void afterEach(ExtensionContext extensionContext) { + listAppender.stop(); + listAppender.list.clear(); + logger.detachAppender(listAppender); + } + + @Override + public void beforeEach(ExtensionContext extensionContext) { + logger.addAppender(listAppender); + listAppender.start(); + } + + public List getFormattedMessages() { + return listAppender.list.stream() + .map(ILoggingEvent::getFormattedMessage) + .collect(Collectors.toList()); + } +} diff --git a/backpressure/src/test/java/com/iluwatar/backpressure/PublisherTest.java b/backpressure/src/test/java/com/iluwatar/backpressure/PublisherTest.java new file mode 100644 index 000000000000..010a80e83959 --- /dev/null +++ b/backpressure/src/test/java/com/iluwatar/backpressure/PublisherTest.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.backpressure; + +import static com.iluwatar.backpressure.Publisher.publish; + +import java.time.Duration; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +public class PublisherTest { + + @Test + public void testPublish() { + + Flux flux = publish(1, 3, 200); + + StepVerifier.withVirtualTime(() -> flux) + .expectSubscription() + .expectNoEvent(Duration.ofMillis(200)) + .expectNext(1) + .expectNoEvent(Duration.ofSeconds(200)) + .expectNext(2) + .expectNoEvent(Duration.ofSeconds(200)) + .expectNext(3) + .verifyComplete(); + } +} diff --git a/backpressure/src/test/java/com/iluwatar/backpressure/SubscriberTest.java b/backpressure/src/test/java/com/iluwatar/backpressure/SubscriberTest.java new file mode 100644 index 000000000000..7f7676612d02 --- /dev/null +++ b/backpressure/src/test/java/com/iluwatar/backpressure/SubscriberTest.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.backpressure; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.CountDownLatch; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +public class SubscriberTest { + + @RegisterExtension public LoggerExtension loggerExtension = new LoggerExtension(); + + @Test + public void testSubscribe() throws InterruptedException { + + Subscriber sub = new Subscriber(); + Publisher.publish(1, 8, 100).subscribe(sub); + + App.latch = new CountDownLatch(1); + App.latch.await(); + + String result = String.join(",", loggerExtension.getFormattedMessages()); + assertTrue( + result.endsWith( + "onSubscribe(FluxConcatMapNoPrefetch." + + "FluxConcatMapNoPrefetchSubscriber),request(10),onNext(1),process(1),onNext(2)," + + "process(2),onNext(3),process(3),onNext(4),process(4),onNext(5),process(5),request(5)," + + "onNext(6),process(6),onNext(7),process(7),onNext(8),process(8),onComplete()")); + } +} diff --git a/balking/README.md b/balking/README.md index fb5c83d5b412..cdd09cf5b7d1 100644 --- a/balking/README.md +++ b/balking/README.md @@ -1,27 +1,161 @@ --- -layout: pattern -title: Balking -folder: balking -permalink: /patterns/balking/ -categories: Concurrency -tags: - - Java - - Difficulty-Beginner +title: "Balking Pattern in Java: Smart Control Over Java Execution" +shortTitle: Balking +description: "Learn the Balking design pattern in Java, a concurrency pattern that prevents code execution in inappropriate states. Discover examples, use cases, and benefits." +category: Concurrency +language: en +tag: + - Concurrency + - Decoupling + - Fault tolerance + - Synchronization --- -## Intent -Balking Pattern is used to prevent an object from executing certain code if it is an -incomplete or inappropriate state +## Intent of Balking Design Pattern -![alt text](./etc/balking.png "Balking") +The Balking Pattern in Java is a concurrency design pattern that prevents an object from executing certain code if it is in an incomplete or inappropriate state. This pattern is crucial for managing state and concurrency in multithreaded Java applications. + +## Detailed Explanation of Balking Pattern with Real-World Examples + +Real-world example + +> A real-world analogy of the Balking design pattern can be seen in a laundry service. Imagine a washing machine at a laundromat that only starts washing clothes if the door is properly closed and locked. If a user tries to start the machine while the door is open, the machine balks and does nothing. This ensures that the washing process only begins when it is safe to do so, preventing water spillage and potential damage to the machine. Similarly, the Balking pattern in software design ensures that operations are only executed when the object is in an appropriate state, preventing erroneous actions and maintaining system stability. + +In plain words + +> Using the balking pattern, a certain code executes only if the object is in particular state. + +Wikipedia says + +> The balking pattern is a software design pattern that only executes an action on an object when the object is in a particular state. For example, if an object reads ZIP files and a calling method invokes a get method on the object when the ZIP file is not open, the object would "balk" at the request. + +Flowchart + +![Balking flowchart](./etc/balking-flowchart.png) + +## Programmatic Example of Balking Pattern in Java + +This example demonstrates the Balking Pattern in a multithreaded Java application, highlighting state management and concurrency control. The Balking Pattern is exemplified by a washing machine's start button that initiates washing only if the machine is idle. This ensures state management and prevents concurrent issues. + +There's a start-button in a washing machine to initiate the laundry washing. When the washing machine is inactive the button works as expected, but if it's already washing the button does nothing. + +In this example implementation, `WashingMachine` is an object that has two states in which it can be: ENABLED and WASHING. If the machine is ENABLED, the state changes to WASHING using a thread-safe method. On the other hand, if it already has been washing and any other thread executes `wash`it won't do that and returns without doing anything. + +Here are the relevant parts of the `WashingMachine` class. + +```java + +@Slf4j +public class WashingMachine { + + private final DelayProvider delayProvider; + private WashingMachineState washingMachineState; + + public WashingMachine(DelayProvider delayProvider) { + this.delayProvider = delayProvider; + this.washingMachineState = WashingMachineState.ENABLED; + } + + public WashingMachineState getWashingMachineState() { + return washingMachineState; + } + + public void wash() { + synchronized (this) { + var machineState = getWashingMachineState(); + LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState); + if (this.washingMachineState == WashingMachineState.WASHING) { + LOGGER.error("Cannot wash if the machine has been already washing!"); + return; + } + this.washingMachineState = WashingMachineState.WASHING; + } + LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); + this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing); + } + + public synchronized void endOfWashing() { + washingMachineState = WashingMachineState.ENABLED; + LOGGER.info("{}: Washing completed.", Thread.currentThread().getId()); + } +} +``` + +Here's the simple `DelayProvider` interface used by the `WashingMachine`. + +```java +public interface DelayProvider { + void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task); +} +``` + +Now, we introduce the application using the `WashingMachine`. + +```java +public static void main(String... args) { + final var washingMachine = new WashingMachine(); + var executorService = Executors.newFixedThreadPool(3); + for (int i = 0; i < 3; i++) { + executorService.execute(washingMachine::wash); + } + executorService.shutdown(); + try { + if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } + } catch (InterruptedException ie) { + LOGGER.error("ERROR: Waiting on executor service shutdown!"); + Thread.currentThread().interrupt(); + } +} +``` + +Here is the console output of the program. + +``` +14:02:52.268 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Actual machine state: ENABLED +14:02:52.272 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Doing the washing +14:02:52.272 [pool-1-thread-3] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-3: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-3] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.273 [pool-1-thread-1] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-1: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-1] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.324 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - 14: Washing completed. +``` + +## When to Use the Balking Pattern in Java -## Applicability Use the Balking pattern when -* you want to invoke an action on an object only when it is in a particular state -* objects are generally only in a state that is prone to balking temporarily -but for an unknown amount of time +* You want to invoke an action on an object only when it is in a particular state +* Objects are generally only in a state that is prone to balking temporarily but for an unknown amount of time +* In multithreaded applications where certain actions should only proceed when specific conditions are met, and those conditions are expected to change over time due to external factors or concurrent operations. + +## Real-World Applications of Balking Pattern in Java + +* Resource pooling, where resources are only allocated if they are in a valid state for allocation. +* Thread management, where threads only proceed with tasks if certain conditions (like task availability or resource locks) are met. + +## Benefits and Trade-offs of Balking Pattern + +Benefits: + +* Reduces unnecessary lock acquisitions in situations where actions cannot proceed, enhancing performance in concurrent applications. +* Encourages clear separation of state management and behavior, leading to cleaner code. +* Simplifies the handling of operations that should only be performed under certain conditions without cluttering the caller code with state checks. + +Trade-offs: + +* Can introduce complexity by obscuring the conditions under which actions are taken or ignored, potentially making the system harder to debug and understand. +* May lead to missed opportunities or actions if the state changes are not properly monitored or if the balking condition is too restrictive. + +## Related Java Design Patterns + +* [Double-Checked Locking](https://java-design-patterns.com/patterns/double-checked-locking/): Ensures that initialization occurs only when necessary and avoids unnecessary locking, which is related to Balking in terms of conditionally executing logic based on the object's state. +* [Guarded Suspension](https://java-design-patterns.com/patterns/guarded-suspension/): Similar in ensuring actions are only performed when an object is in a certain state, but typically involves waiting until the state is valid. +* [State](https://java-design-patterns.com/patterns/state/): The State pattern can be used in conjunction with Balking to manage the states and transitions of the object. + +## References and Credits -## Related patterns -* Guarded Suspension Pattern -* Double Checked Locking Pattern +* [Concurrent Programming in Java : Design Principles and Patterns](https://amzn.to/4dIBqxL) +* [Java Concurrency in Practice](https://amzn.to/4aRMruW) +* [Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML](https://amzn.to/4bOtzwF) diff --git a/balking/etc/balking-flowchart.png b/balking/etc/balking-flowchart.png new file mode 100644 index 000000000000..400a1ce8d3e3 Binary files /dev/null and b/balking/etc/balking-flowchart.png differ diff --git a/balking/etc/balking.urm.puml b/balking/etc/balking.urm.puml new file mode 100644 index 000000000000..191fd350bcd8 --- /dev/null +++ b/balking/etc/balking.urm.puml @@ -0,0 +1,30 @@ +@startuml +package com.iluwatar.balking { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + interface DelayProvider { + + executeAfterDelay(long, TimeUnit, Runnable) {abstract} + } + class WashingMachine { + - LOGGER : Logger {static} + - delayProvider : DelayProvider + - washingMachineState : WashingMachineState + + WashingMachine() + + WashingMachine(delayProvider : DelayProvider) + + endOfWashing() + + getWashingMachineState() : WashingMachineState + + wash() + } + enum WashingMachineState { + + ENABLED {static} + + WASHING {static} + + valueOf(name : String) : WashingMachineState {static} + + values() : WashingMachineState[] {static} + } +} +WashingMachine --> "-washingMachineState" WashingMachineState +WashingMachine --> "-delayProvider" DelayProvider +@enduml \ No newline at end of file diff --git a/balking/pom.xml b/balking/pom.xml index e16065359668..818f7549c330 100644 --- a/balking/pom.xml +++ b/balking/pom.xml @@ -1,8 +1,10 @@ - + java-design-patterns com.iluwatar - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT 4.0.0 - balking - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -46,6 +48,23 @@ test - - - \ No newline at end of file + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.balking.App + + + + + + + + + diff --git a/balking/src/main/java/com/iluwatar/balking/App.java b/balking/src/main/java/com/iluwatar/balking/App.java index 47b10cd4606d..c7651ec54147 100644 --- a/balking/src/main/java/com/iluwatar/balking/App.java +++ b/balking/src/main/java/com/iluwatar/balking/App.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,44 +24,43 @@ */ package com.iluwatar.balking; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; /** * In Balking Design Pattern if an object’s method is invoked when it is in an inappropriate state, - * then the method will return without doing anything. Objects that use this pattern are generally only in a - * state that is prone to balking temporarily but for an unknown amount of time + * then the method will return without doing anything. Objects that use this pattern are generally + * only in a state that is prone to balking temporarily but for an unknown amount of time * - * In this example implementation WashingMachine is an object that has two states - * in which it can be: ENABLED and WASHING. If the machine is ENABLED - * the state is changed into WASHING that any other thread can't invoke this action on this and then do the job. - * On the other hand if it have been already washing and any other thread execute wash() - * it can't do that once again and returns doing nothing. + *

    In this example implementation, {@link WashingMachine} is an object that has two states in + * which it can be: ENABLED and WASHING. If the machine is ENABLED, the state changes to WASHING + * using a thread-safe method. On the other hand, if it already has been washing and any other + * thread executes {@link WashingMachine#wash()} it won't do that and returns without doing + * anything. */ - +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** + * Entry Point. + * * @param args the command line arguments - not used */ public static void main(String... args) { - final WashingMachine washingMachine = new WashingMachine(); - ExecutorService executorService = Executors.newFixedThreadPool(3); + final var washingMachine = new WashingMachine(); + var executorService = Executors.newFixedThreadPool(3); for (int i = 0; i < 3; i++) { executorService.execute(washingMachine::wash); } executorService.shutdown(); try { - executorService.awaitTermination(10, TimeUnit.SECONDS); + if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } } catch (InterruptedException ie) { LOGGER.error("ERROR: Waiting on executor service shutdown!"); + Thread.currentThread().interrupt(); } } - } diff --git a/balking/src/main/java/com/iluwatar/balking/DelayProvider.java b/balking/src/main/java/com/iluwatar/balking/DelayProvider.java new file mode 100644 index 000000000000..f27922219ea6 --- /dev/null +++ b/balking/src/main/java/com/iluwatar/balking/DelayProvider.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.balking; + +import java.util.concurrent.TimeUnit; + +/** An interface to simulate delay while executing some work. */ +public interface DelayProvider { + void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task); +} diff --git a/balking/src/main/java/com/iluwatar/balking/WashingMachine.java b/balking/src/main/java/com/iluwatar/balking/WashingMachine.java index e4f1259add25..52ce7c593b6b 100644 --- a/balking/src/main/java/com/iluwatar/balking/WashingMachine.java +++ b/balking/src/main/java/com/iluwatar/balking/WashingMachine.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,55 +24,60 @@ */ package com.iluwatar.balking; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.concurrent.TimeUnit; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; -/** - * Washing machine class - */ +/** Washing machine class. */ +@Slf4j public class WashingMachine { - private static final Logger LOGGER = LoggerFactory.getLogger(WashingMachine.class); + private final DelayProvider delayProvider; - private WashingMachineState washingMachineState; + @Getter private WashingMachineState washingMachineState; + /** Creates a new instance of WashingMachine. */ public WashingMachine() { - washingMachineState = WashingMachineState.ENABLED; - } - - public WashingMachineState getWashingMachineState() { - return washingMachineState; + this( + (interval, timeUnit, task) -> { + try { + Thread.sleep(timeUnit.toMillis(interval)); + } catch (InterruptedException ie) { + LOGGER.error("", ie); + Thread.currentThread().interrupt(); + } + task.run(); + }); } /** - * Method responsible for washing - * if the object is in appropriate state + * Creates a new instance of WashingMachine using provided delayProvider. This constructor is used + * only for unit testing purposes. */ + public WashingMachine(DelayProvider delayProvider) { + this.delayProvider = delayProvider; + this.washingMachineState = WashingMachineState.ENABLED; + } + + /** Method responsible for washing if the object is in appropriate state. */ public void wash() { synchronized (this) { - LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), getWashingMachineState()); - if (washingMachineState == WashingMachineState.WASHING) { - LOGGER.error("ERROR: Cannot wash if the machine has been already washing!"); + var machineState = getWashingMachineState(); + LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState); + if (this.washingMachineState == WashingMachineState.WASHING) { + LOGGER.error("Cannot wash if the machine has been already washing!"); return; } - washingMachineState = WashingMachineState.WASHING; + this.washingMachineState = WashingMachineState.WASHING; } LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); - try { - Thread.sleep(50); - } catch (InterruptedException ie) { - ie.printStackTrace(); - } - endOfWashing(); + + this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing); } - /** - * Method responsible of ending the washing - * by changing machine state - */ + /** Method is responsible for ending the washing by changing machine state. */ public synchronized void endOfWashing() { washingMachineState = WashingMachineState.ENABLED; LOGGER.info("{}: Washing completed.", Thread.currentThread().getId()); } - } diff --git a/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java b/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java index 40a5b2f38e30..e0b2ba7ac8f1 100644 --- a/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java +++ b/balking/src/main/java/com/iluwatar/balking/WashingMachineState.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -23,10 +25,10 @@ package com.iluwatar.balking; /** - * WashingMachineState enum describes in which state machine is, - * it can be enabled and ready to work as well as during washing + * WashingMachineState enum describes in which state machine is, it can be enabled and ready to work + * as well as during washing. */ - public enum WashingMachineState { - ENABLED, WASHING + ENABLED, + WASHING } diff --git a/balking/src/test/java/com/iluwatar/balking/AppTest.java b/balking/src/test/java/com/iluwatar/balking/AppTest.java index 87941dc27d91..40beabf553d0 100644 --- a/balking/src/test/java/com/iluwatar/balking/AppTest.java +++ b/balking/src/test/java/com/iluwatar/balking/AppTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,20 +22,24 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.balking; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; -/** - * Application test - */ -public class AppTest { +/** Application test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ @Test - public void main() throws Exception { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow((Executable) App::main); } - -} \ No newline at end of file +} diff --git a/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java index 9a13b8b2dcf4..9bf7ac2548a0 100644 --- a/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java +++ b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,46 +24,47 @@ */ package com.iluwatar.balking; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; +/** Tests for {@link WashingMachine} */ +class WashingMachineTest { -/** - * Tests for {@link WashingMachine} - */ -public class WashingMachineTest { + private final FakeDelayProvider fakeDelayProvider = new FakeDelayProvider(); - private volatile WashingMachineState machineStateGlobal; - - @Disabled @Test - public void wash() throws Exception { - WashingMachine washingMachine = new WashingMachine(); - ExecutorService executorService = Executors.newFixedThreadPool(2); - executorService.execute(washingMachine::wash); - executorService.execute(() -> { - washingMachine.wash(); - machineStateGlobal = washingMachine.getWashingMachineState(); - }); - executorService.shutdown(); - try { - executorService.awaitTermination(10, TimeUnit.SECONDS); - } catch (InterruptedException ie) { - ie.printStackTrace(); - } + void wash() { + var washingMachine = new WashingMachine(fakeDelayProvider); + + washingMachine.wash(); + washingMachine.wash(); + + var machineStateGlobal = washingMachine.getWashingMachineState(); + + fakeDelayProvider.task.run(); + + // washing machine remains in washing state assertEquals(WashingMachineState.WASHING, machineStateGlobal); + + // washing machine goes back to enabled state + assertEquals(WashingMachineState.ENABLED, washingMachine.getWashingMachineState()); } @Test - public void endOfWashing() throws Exception { - WashingMachine washingMachine = new WashingMachine(); + void endOfWashing() { + var washingMachine = new WashingMachine(); washingMachine.wash(); assertEquals(WashingMachineState.ENABLED, washingMachine.getWashingMachineState()); } -} \ No newline at end of file + private static class FakeDelayProvider implements DelayProvider { + private Runnable task; + + @Override + public void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task) { + this.task = task; + } + } +} diff --git a/bloc/README.md b/bloc/README.md new file mode 100644 index 000000000000..76a4a0917485 --- /dev/null +++ b/bloc/README.md @@ -0,0 +1,230 @@ +--- +title: "Bloc Pattern in Java: State Management Simplified" +shortTitle: Bloc +description: "Learn how the Bloc pattern helps manage state changes in Java applications. This guide covers dynamic listener management, real-world examples, and clean code practices for state management." +category: Architectural +language: en +tag: + - Abstraction + - Data binding + - Decoupling + - Event-driven + - Presentation + - Reactive + - Reusability + - State tracking +--- + +## Also known as + +* Business Logic Component +* Business Logic Controller + +## Intent of the Bloc Pattern + +The Bloc pattern manages the state of an object and allows for dynamically notifying interested listeners about state changes. It separates state management logic from the rest of the application, improving code organization and flexibility. + +## Detailed explanation of the Bloc pattern with real-World examples + +Real-world example + +> Consider a digital counter application where multiple parts of the UI need to be updated whenever the counter changes. For example, a label displaying the counter value and an activity log showing changes. Instead of directly modifying these UI components, the Bloc pattern manages the counter state and notifies all registered listeners about the state change. Listeners can dynamically subscribe or unsubscribe from receiving updates. + +In plain words + +> The Bloc pattern manages a single state object and dynamically notifies registered listeners whenever the state changes. + +Wikipedia says + +> While not a formalized "Gang of Four" design pattern, Bloc is widely used in state-driven applications. It centralizes state management and propagates state changes to registered observers, following principles of separation of concerns. + +Sequence diagram + +![Bloc sequence diagram](./etc/bloc-sequence-diagram.png) + +## Programmatic Example of the Bloc Pattern in Java + +This example demonstrates how to implement the Bloc pattern using Java and Swing. The pattern separates the state of the application from UI components, and provides a reactive, event-driven approach to managing updates. + +Core components of the Bloc Pattern include a `State` object, a `Bloc` class responsible for managing and updating that state, and interfaces (`StateListener` and `ListenerManager`) for subscribing to changes. + +The `State` class represents the application's data at any given time. + +```java +public record State(int value) {} +``` + +The `ListenerManager` interface declares methods to add and remove listeners, as well as retrieve them. + +```java +public interface ListenerManager { + void addListener(StateListener listener); + void removeListener(StateListener listener); + List> getListeners(); +} +``` + +The `StateListener` interface defines how a listener reacts to state changes. + +```java +public interface StateListener { + void onStateChange(T state); +} +``` + +The `Bloc` class maintains the current state and notifies listeners of updates. It provides `increment` and `decrement` methods to update state and automatically notify registered listeners. + +```java +public class Bloc implements ListenerManager { + + private State currentState; + private final List> listeners = new ArrayList<>(); + + public Bloc() { + this.currentState = new State(0); + } + + @Override + public void addListener(StateListener listener) { + listeners.add(listener); + listener.onStateChange(currentState); + } + + @Override + public void removeListener(StateListener listener) { + listeners.remove(listener); + } + + @Override + public List> getListeners() { + return Collections.unmodifiableList(listeners); + } + + private void emitState(State newState) { + currentState = newState; + for (StateListener listener : listeners) { + listener.onStateChange(currentState); + } + } + + public void increment() { + emitState(new State(currentState.value() + 1)); + } + + public void decrement() { + emitState(new State(currentState.value() - 1)); + } +} +``` + +This class demonstrates how to integrate the Bloc pattern with a simple Swing GUI. It sets up a counter, buttons to change the state, and a toggle to enable or disable the listener dynamically. + +```java +public class Main { + public static void main(String[] args) { + BlocUi blocUi = new BlocUi(); + blocUi.createAndShowUi(); + } +} + +public class BlocUi { + + public void createAndShowUi() { + final Bloc bloc = new Bloc(); + + JFrame frame = new JFrame("BloC example"); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.setSize(400, 300); + + JLabel counterLabel = new JLabel("Counter: 0", SwingConstants.CENTER); + counterLabel.setFont(new Font("Arial", Font.BOLD, 20)); + + JButton decrementButton = new JButton("Decrement"); + JButton toggleListenerButton = new JButton("Disable Listener"); + JButton incrementButton = new JButton("Increment"); + + frame.setLayout(new BorderLayout()); + frame.add(counterLabel, BorderLayout.CENTER); + frame.add(incrementButton, BorderLayout.NORTH); + frame.add(decrementButton, BorderLayout.SOUTH); + frame.add(toggleListenerButton, BorderLayout.EAST); + + StateListener stateListener = state -> counterLabel.setText("Counter: " + state.value()); + + bloc.addListener(stateListener); + + toggleListenerButton.addActionListener( + e -> { + if (bloc.getListeners().contains(stateListener)) { + bloc.removeListener(stateListener); + toggleListenerButton.setText("Enable Listener"); + } else { + bloc.addListener(stateListener); + toggleListenerButton.setText("Disable Listener"); + } + }); + + incrementButton.addActionListener(e -> bloc.increment()); + decrementButton.addActionListener(e -> bloc.decrement()); + + frame.setVisible(true); + } +} +``` + +### Program Output + +- **On Increment** + `Counter: 1` + +- **On Decrement** + `Counter: 0` + +- **Dynamic Listener Toggle** + - Listener disabled: Counter stops updating. + - Listener enabled: Counter updates again. + +## When to Use the Bloc Pattern + +Use the Bloc pattern when: + +* When you want a clean separation of business logic and UI in Java applications +* When you need a reactive approach to updating UI based on state changes +* When you want to avoid coupling controllers or presenters directly to data manipulation +* When multiple UI elements need access to the same business logic + +## Real-World Applications of Bloc Pattern + +* Java-based desktop applications that require real-time UI updates +* Backend-driven Java frameworks that separate service layers from presentation +* Cross-platform applications where the logic must remain consistent regardless of the UI technology + +## Benefits and Trade-offs of Bloc Pattern + +Benefits: + +* Simplifies UI components by removing direct business logic +* Improves testability by isolating state and behavior +* Encourages code reuse by centralizing data flows +* Enhances maintainability through clear separation of concerns + +Trade-offs: + +* May introduce additional boilerplate code for managing streams or observers +* Requires careful design to avoid a monolithic “god” component +* Demands consistent reactive programming practices to be effective + +## Related Patterns + +- [Observer](https://java-design-patterns.com/patterns/observer/): Bloc is a specialized implementation of the Observer pattern. +- [Mediator](https://java-design-patterns.com/patterns/mediator/): Orchestrates interactions among multiple objects through a central component +- [MVC](https://java-design-patterns.com/patterns/model-view-controller/): Shares the idea of separating concerns between layers + +## References and Credits + +* [Bloc architecture(bloclibrary.dev)](https://bloclibrary.dev/architecture/) +* [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3UoKkaR) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Event-Driven Programming in Java (Oracle)](https://www.oracle.com/java/) +* [Java Swing Documentation (Oracle)](https://docs.oracle.com/javase/tutorial/uiswing/) diff --git a/bloc/etc/bloc-sequence-diagram.png b/bloc/etc/bloc-sequence-diagram.png new file mode 100644 index 000000000000..588863985019 Binary files /dev/null and b/bloc/etc/bloc-sequence-diagram.png differ diff --git a/bloc/etc/bloc.png b/bloc/etc/bloc.png new file mode 100644 index 000000000000..60d6eb77c8fc Binary files /dev/null and b/bloc/etc/bloc.png differ diff --git a/bloc/etc/bloc.puml b/bloc/etc/bloc.puml new file mode 100644 index 000000000000..5991f533ae70 --- /dev/null +++ b/bloc/etc/bloc.puml @@ -0,0 +1,41 @@ +@startuml +package com.iluwatar.bloc { + + class State { + - value : int + + State(value : int) + + getValue() : int + } + + interface StateListener { + + onStateChange(state : T) + } + + interface ListenerManager { + + addListener(listener : StateListener) + + removeListener(listener : StateListener) + + getListeners() : List> + } + + class BloC { + - currentState : State + - listeners : List> + + BloC() + + addListener(listener : StateListener) + + removeListener(listener : StateListener) + + getListeners() : List> + - emitState(newState : State) + + increment() + + decrement() + } + + class Main { + + main(args : String[]) + } + + ListenerManager <|.. BloC + StateListener <|.. BloC + BloC o-- State + BloC *-- StateListener +} +@enduml diff --git a/bloc/etc/bloc.urm.puml b/bloc/etc/bloc.urm.puml new file mode 100644 index 000000000000..6408aa76e6a4 --- /dev/null +++ b/bloc/etc/bloc.urm.puml @@ -0,0 +1,32 @@ +@startuml +package com.iluwatar.bloc { + class Bloc { + - currentState : State + - listeners : List> + + Bloc() + + addListener(listener : StateListener) + + decrement() + - emitState(newState : State) + + getListeners() : List> + + increment() + + removeListener(listener : StateListener) + } + class BlocUi { + + BlocUi() + + createAndShowUi() + } + interface ListenerManager { + + addListener(StateListener) {abstract} + + getListeners() : List> {abstract} + + removeListener(StateListener) {abstract} + } + class Main { + + Main() + + main(args : String[]) {static} + } + interface StateListener { + + onStateChange(T) {abstract} + } +} +Bloc ..|> ListenerManager +@enduml \ No newline at end of file diff --git a/bloc/pom.xml b/bloc/pom.xml new file mode 100644 index 000000000000..cc52a3b99dc2 --- /dev/null +++ b/bloc/pom.xml @@ -0,0 +1,76 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + bloc + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.testng + testng + 7.11.0 + test + + + org.assertj + assertj-core + 3.27.3 + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.bloc.Main + + + + + + + + + diff --git a/bloc/src/main/java/com/iluwatar/bloc/Bloc.java b/bloc/src/main/java/com/iluwatar/bloc/Bloc.java new file mode 100644 index 000000000000..f6ab0a61cdbf --- /dev/null +++ b/bloc/src/main/java/com/iluwatar/bloc/Bloc.java @@ -0,0 +1,98 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bloc; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * The Bloc class is responsible for managing the current state and notifying registered listeners + * whenever the state changes. It implements the ListenerManager interface, allowing listeners to be + * added, removed, and notified of state changes. + */ +public class Bloc implements ListenerManager { + + private State currentState; + private final List> listeners = new ArrayList<>(); + + /** Constructs a new Bloc instance with an initial state of value 0. */ + public Bloc() { + this.currentState = new State(0); + } + + /** + * Adds a listener to receive state change notifications. + * + * @param listener the listener to add + */ + @Override + public void addListener(StateListener listener) { + listeners.add(listener); + listener.onStateChange(currentState); + } + + /** + * Removes a listener from receiving state change notifications. + * + * @param listener the listener to remove + */ + @Override + public void removeListener(StateListener listener) { + listeners.remove(listener); + } + + /** + * Returns an unmodifiable list of all registered listeners. + * + * @return an unmodifiable list of listeners + */ + @Override + public List> getListeners() { + return Collections.unmodifiableList(listeners); + } + + /** + * Emits a new state and notifies all registered listeners of the change. + * + * @param newState the new state to emit + */ + private void emitState(State newState) { + currentState = newState; + for (StateListener listener : listeners) { + listener.onStateChange(currentState); + } + } + + /** Increments the current state value by 1 and notifies listeners of the change. */ + public void increment() { + emitState(new State(currentState.value() + 1)); + } + + /** Decrements the current state value by 1 and notifies listeners of the change. */ + public void decrement() { + emitState(new State(currentState.value() - 1)); + } +} diff --git a/bloc/src/main/java/com/iluwatar/bloc/BlocUi.java b/bloc/src/main/java/com/iluwatar/bloc/BlocUi.java new file mode 100644 index 000000000000..500d455d82e1 --- /dev/null +++ b/bloc/src/main/java/com/iluwatar/bloc/BlocUi.java @@ -0,0 +1,85 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bloc; + +import java.awt.BorderLayout; +import java.awt.Font; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.SwingConstants; +import javax.swing.WindowConstants; + +/** The BlocUI class handles the creation and management of the UI components. */ +public class BlocUi { + + /** Creates and shows the UI. */ + public void createAndShowUi() { + // Create a Bloc instance to manage the state + final Bloc bloc = new Bloc(); + + // setting up a frame window with a title + JFrame frame = new JFrame("BloC example"); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.setSize(400, 300); + + // label to display the counter value + JLabel counterLabel = new JLabel("Counter: 0", SwingConstants.CENTER); + counterLabel.setFont(new Font("Arial", Font.BOLD, 20)); + + // buttons for increment, decrement, and toggling listener + JButton decrementButton = new JButton("Decrement"); + JButton toggleListenerButton = new JButton("Disable Listener"); + JButton incrementButton = new JButton("Increment"); + + frame.setLayout(new BorderLayout()); + frame.add(counterLabel, BorderLayout.CENTER); + frame.add(incrementButton, BorderLayout.NORTH); + frame.add(decrementButton, BorderLayout.SOUTH); + frame.add(toggleListenerButton, BorderLayout.EAST); + + // making a state listener to update the counter label when the state changes + StateListener stateListener = state -> counterLabel.setText("Counter: " + state.value()); + + // adding the listener to the Bloc instance + bloc.addListener(stateListener); + + toggleListenerButton.addActionListener( + e -> { + if (bloc.getListeners().contains(stateListener)) { + bloc.removeListener(stateListener); + toggleListenerButton.setText("Enable Listener"); + } else { + bloc.addListener(stateListener); + toggleListenerButton.setText("Disable Listener"); + } + }); + + incrementButton.addActionListener(e -> bloc.increment()); + decrementButton.addActionListener(e -> bloc.decrement()); + + frame.setVisible(true); + } +} diff --git a/bloc/src/main/java/com/iluwatar/bloc/ListenerManager.java b/bloc/src/main/java/com/iluwatar/bloc/ListenerManager.java new file mode 100644 index 000000000000..cd55b0fb320d --- /dev/null +++ b/bloc/src/main/java/com/iluwatar/bloc/ListenerManager.java @@ -0,0 +1,56 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bloc; + +import java.util.List; + +/** + * Interface for managing listeners for state changes. + * + * @param The type of state to be handled by the listeners. + */ +public interface ListenerManager { + + /** + * Adds a listener that will be notified of state changes. + * + * @param listener the listener to be added + */ + void addListener(StateListener listener); + + /** + * Removes a listener so that it no longer receives state change notifications. + * + * @param listener the listener to be removed + */ + void removeListener(StateListener listener); + + /** + * Returns a list of all listeners currently registered for state changes. + * + * @return a list of registered listeners + */ + List> getListeners(); +} diff --git a/bloc/src/main/java/com/iluwatar/bloc/Main.java b/bloc/src/main/java/com/iluwatar/bloc/Main.java new file mode 100644 index 000000000000..b7a929bcf2bd --- /dev/null +++ b/bloc/src/main/java/com/iluwatar/bloc/Main.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bloc; + +/** + * The BLoC (Business Logic Component) pattern is a software design pattern primarily used in + * Flutter applications. It facilitates the separation of business logic from UI code, making the + * application more modular, testable, and scalable. The BLoC pattern uses streams to manage the + * flow of data and state changes, allowing widgets to react to new states as they arrive. In the + * BLoC pattern, the application is divided into three key components: - Input streams: Represent + * user interactions or external events fed into the BLoC. - Business logic: Processes the input and + * determines the resulting state or actions. - Output streams: Emit the updated state for the UI to + * consume. The BLoC pattern is especially useful in reactive programming scenarios and aligns well + * with the declarative nature of Flutter. By using this pattern, developers can ensure a clear + * separation of concerns, enhance reusability, and maintain consistent state management throughout + * the application. + */ +public class Main { + + /** + * The entry point of the application. Initializes the GUI. + * + * @param args command-line arguments (not used in this example) + */ + public static void main(String[] args) { + BlocUi blocUi = new BlocUi(); + blocUi.createAndShowUi(); + } +} diff --git a/bloc/src/main/java/com/iluwatar/bloc/State.java b/bloc/src/main/java/com/iluwatar/bloc/State.java new file mode 100644 index 000000000000..430747548cd3 --- /dev/null +++ b/bloc/src/main/java/com/iluwatar/bloc/State.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bloc; + +/** + * The {@code State} class represents a state with an integer value. This class encapsulates the + * value and provides methods to retrieve it. + */ +public record State(int value) {} diff --git a/bloc/src/main/java/com/iluwatar/bloc/StateListener.java b/bloc/src/main/java/com/iluwatar/bloc/StateListener.java new file mode 100644 index 000000000000..77aac172e4e3 --- /dev/null +++ b/bloc/src/main/java/com/iluwatar/bloc/StateListener.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bloc; + +/** + * The {@code StateListener} interface defines the contract for listening to state changes. + * Implementations of this interface should handle state changes and define actions to take when the + * state changes. + * + * @param the type of state that this listener will handle + */ +public interface StateListener { + + /** + * This method is called when the state has changed. + * + * @param state the updated state + */ + void onStateChange(T state); +} diff --git a/bloc/src/test/java/com/iluwatar/bloc/BlocTest.java b/bloc/src/test/java/com/iluwatar/bloc/BlocTest.java new file mode 100644 index 000000000000..98e34b8d4a22 --- /dev/null +++ b/bloc/src/test/java/com/iluwatar/bloc/BlocTest.java @@ -0,0 +1,85 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bloc; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class BlocTest { + private Bloc bloc; + private AtomicInteger stateValue; + + @BeforeEach + void setUp() { + bloc = new Bloc(); + stateValue = new AtomicInteger(0); + } + + @Test + void initialState() { + assertTrue(bloc.getListeners().isEmpty(), "No listeners should be present initially."); + } + + @Test + void IncrementUpdateState() { + bloc.addListener(state -> stateValue.set(state.value())); + bloc.increment(); + assertEquals(1, stateValue.get(), "State should increment to 1"); + } + + @Test + void DecrementUpdateState() { + bloc.addListener(state -> stateValue.set(state.value())); + bloc.decrement(); + assertEquals(-1, stateValue.get(), "State should decrement to -1"); + } + + @Test + void addingListener() { + bloc.addListener(state -> {}); + assertEquals(1, bloc.getListeners().size(), "Listener count should be 1."); + } + + @Test + void removingListener() { + StateListener listener = state -> {}; + bloc.addListener(listener); + bloc.removeListener(listener); + assertTrue(bloc.getListeners().isEmpty(), "Listener count should be 0 after removal."); + } + + @Test + void multipleListeners() { + AtomicInteger secondValue = new AtomicInteger(); + bloc.addListener(state -> stateValue.set(state.value())); + bloc.addListener(state -> secondValue.set(state.value())); + bloc.increment(); + assertEquals(1, stateValue.get(), "First listener should receive state 1."); + assertEquals(1, secondValue.get(), "Second listener should receive state 1."); + } +} diff --git a/bloc/src/test/java/com/iluwatar/bloc/BlocUiTest.java b/bloc/src/test/java/com/iluwatar/bloc/BlocUiTest.java new file mode 100644 index 000000000000..f1fc73947896 --- /dev/null +++ b/bloc/src/test/java/com/iluwatar/bloc/BlocUiTest.java @@ -0,0 +1,121 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bloc; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.awt.*; +import javax.swing.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class BlocUiTest { + + private JFrame frame; + private JLabel counterLabel; + private JButton incrementButton; + private JButton decrementButton; + private JButton toggleListenerButton; + private Bloc bloc; + private StateListener stateListener; + + @BeforeEach + void setUp() { + bloc = new Bloc(); // Re-initialize the Bloc for each test + + frame = new JFrame("BloC example"); + frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + frame.setSize(400, 300); + + counterLabel = new JLabel("Counter: 0", SwingConstants.CENTER); + counterLabel.setFont(new Font("Arial", Font.BOLD, 20)); + + incrementButton = new JButton("Increment"); + decrementButton = new JButton("Decrement"); + toggleListenerButton = new JButton("Disable Listener"); + + frame.setLayout(new BorderLayout()); + frame.add(counterLabel, BorderLayout.CENTER); + frame.add(incrementButton, BorderLayout.NORTH); + frame.add(decrementButton, BorderLayout.SOUTH); + frame.add(toggleListenerButton, BorderLayout.EAST); + + stateListener = state -> counterLabel.setText("Counter: " + state.value()); + bloc.addListener(stateListener); + + incrementButton.addActionListener(e -> bloc.increment()); + decrementButton.addActionListener(e -> bloc.decrement()); + toggleListenerButton.addActionListener( + e -> { + if (bloc.getListeners().contains(stateListener)) { + bloc.removeListener(stateListener); + toggleListenerButton.setText("Enable Listener"); + } else { + bloc.addListener(stateListener); + toggleListenerButton.setText("Disable Listener"); + } + }); + + frame.setVisible(true); + } + + @AfterEach + void tearDown() { + frame.dispose(); + bloc = new Bloc(); // Reset Bloc state after each test to avoid state carryover + } + + @Test + void testIncrementButton() { + simulateButtonClick(incrementButton); + assertEquals("Counter: 1", counterLabel.getText()); + } + + @Test + void testDecrementButton() { + simulateButtonClick(decrementButton); + assertEquals("Counter: -1", counterLabel.getText()); + } + + @Test + void testToggleListenerButton() { + // Disable listener + simulateButtonClick(toggleListenerButton); + simulateButtonClick(incrementButton); + assertEquals("Counter: 0", counterLabel.getText()); // Listener is disabled + + // Enable listener + simulateButtonClick(toggleListenerButton); + simulateButtonClick(incrementButton); + assertEquals("Counter: 2", counterLabel.getText()); // Listener is re-enabled + } + + private void simulateButtonClick(JButton button) { + for (var listener : button.getActionListeners()) { + listener.actionPerformed(null); + } + } +} diff --git a/bridge/README.md b/bridge/README.md index cfbbcf0d95a4..26567b292c81 100644 --- a/bridge/README.md +++ b/bridge/README.md @@ -1,196 +1,256 @@ --- -layout: pattern -title: Bridge -folder: bridge -permalink: /patterns/bridge/ -categories: Structural -tags: - - Java - - Gang Of Four - - Difficulty-Intermediate +title: "Bridge Pattern in Java: Decouple Abstraction from Implementation" +shortTitle: Bridge +description: "Learn about the Bridge design pattern in Java. Decouple abstraction from implementation to enhance flexibility and extensibility. Explore real-world examples, class diagrams, and use cases." +category: Structural +language: en +tag: + - Abstraction + - Decoupling + - Extensibility + - Gang of Four + - Object composition --- ## Also known as -Handle/Body -## Intent -Decouple an abstraction from its implementation so that the two can vary independently. +* Handle/Body -## Explanation +## Intent of Bridge Design Pattern -Real world example +The Bridge design pattern is a structural pattern in Java that decouples an abstraction from its implementation, allowing both to vary independently. This pattern is essential for developing flexible and extensible software systems. -> 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. +## Detailed Explanation of Bridge Pattern with Real-World Examples + +Real-world example + +> In Java, the Bridge pattern is commonly used in GUI frameworks, database drivers, and device drivers. For instance, a universal remote control (abstraction) can operate various TV brands (implementations) through a consistent interface. +> +> Imagine a universal remote control (abstraction) that can operate different brands and types of televisions (implementations). The remote control provides a consistent interface for operations like turning on/off, changing channels, and adjusting the volume. Each television brand or type has its own specific implementation of these operations. By using the Bridge pattern, the remote control interface is decoupled from the television implementations, allowing the remote control to work with any television regardless of its brand or internal workings. This separation allows new television models to be added without changing the remote control's code, and different remote controls can be developed to work with the same set of televisions. 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. +> Bridge pattern is about preferring composition to 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** +Sequence diagram + +![Bridge sequence diagram](./etc/bridge-sequence-diagram.png) + +## Programmatic Example of Bridge Pattern in Java -Translating our weapon example from above. Here we have the `Weapon` hierarchy +Imagine you have a weapon that can have various enchantments, and you need to combine different weapons with different enchantments. How would you handle this? Would you create multiple copies of each weapon, each with a different enchantment, or would you create separate enchantments and apply them to the weapon as needed? The Bridge pattern enables you to do the latter. + +Here we have the `Weapon` hierarchy: ```java public interface Weapon { - void wield(); - void swing(); - void unwield(); - Enchantment getEnchantment(); + 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; - } + 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 swung."); + 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; - } + 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 swung."); + 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 +Here's the separate `Enchantment` hierarchy: ```java public interface Enchantment { - void onActivate(); - void apply(); - void onDeactivate(); + 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 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 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."); - } + @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 onActivate() { + LOGGER.info("The item spreads bloodlust."); + } - @Override - public void apply() { - LOGGER.info("The item eats the soul of enemies."); - } + @Override + public void apply() { + LOGGER.info("The item eats the soul of enemies."); + } - @Override - public void onDeactivate() { - LOGGER.info("Bloodlust slowly disappears."); - } + @Override + public void onDeactivate() { + LOGGER.info("Bloodlust slowly disappears."); + } } ``` -And both the hierarchies in action +Here are both hierarchies in action: ```java -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. +public static void main(String[] args) { + LOGGER.info("The knight receives an enchanted sword."); + var enchantedSword = new Sword(new SoulEatingEnchantment()); + enchantedSword.wield(); + enchantedSword.swing(); + enchantedSword.unwield(); + + LOGGER.info("The valkyrie receives an enchanted hammer."); + var hammer = new Hammer(new FlyingEnchantment()); + hammer.wield(); + hammer.swing(); + hammer.unwield(); +} +``` + +Here's the console output. + +``` +The knight receives an enchanted sword. +The sword is wielded. +The item spreads bloodlust. +The sword is swung. +The item eats the soul of enemies. +The sword is unwielded. +Bloodlust slowly disappears. +The valkyrie receives an enchanted hammer. +The hammer is wielded. +The item begins to glow faintly. +The hammer is swung. +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 +## When to Use the Bridge Pattern in Java + +Consider using the Bridge pattern when: + +* You need to avoid a permanent binding between an abstraction and its implementation, such as when the implementation must be chosen or switched at runtime. +* Both the abstractions and their implementations should be extendable via subclassing, allowing independent extension of each component. +* Changes to the implementation of an abstraction should not affect clients, meaning their code should not require recompilation. +* You encounter a large number of classes in your hierarchy, indicating the need to split an object into two parts, a concept referred to as "nested generalizations" by Rumbaugh. +* You want to share an implementation among multiple objects, potentially using reference counting, while keeping this detail hidden from the client, as exemplified by Coplien's String class, where multiple objects can share the same string representation. + +## Bridge Pattern Java Tutorials + +* [Bridge Pattern Tutorial (DigitalOcean)](https://www.digitalocean.com/community/tutorials/bridge-design-pattern-java) + +## Real-World Applications of Bridge Pattern in Java + +* GUI Frameworks where the abstraction is the window, and the implementation could be the underlying OS windowing system. +* Database Drivers where the abstraction is a generic database interface, and the implementations are database-specific drivers. +* Device Drivers where the abstraction is the device-independent code, and the implementation is the device-dependent code. + +## Benefits and Trade-offs of Bridge Pattern + +Benefits: + +* Decoupling Interface and Implementation: The Bridge pattern enhances modularity by separating the interface (the high-level operations) from the implementation (the low-level operations). +* Improved Extensibility: You can extend the abstraction and implementation hierarchies independently. +* Hiding Implementation Details: Clients only see the abstraction's interface, not its implementation. + +Trade-offs: + +* Increased Complexity: The pattern can complicate the system architecture and code, especially for clients unfamiliar with the pattern. +* Runtime Overhead: The extra layer of abstraction can introduce a performance penalty, although it is often negligible in practice. -* you want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time. -* both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently -* changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled. -* you have a proliferation of classes. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term "nested generalizations" to refer to such class hierarchies -* you want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client. A simple example is Coplien's String class, in which multiple objects can share the same string representation. +## Related Java Design Patterns -## Tutorial -* [Bridge Pattern Tutorial](https://www.journaldev.com/1491/bridge-design-pattern-java) +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): The Abstract Factory pattern can be used along with the Bridge pattern to create platforms that are independent of the concrete classes used to create their objects. +* [Adapter](https://java-design-patterns.com/patterns/adapter/): The Adapter pattern is used to provide a different interface to an object, while the Bridge pattern is used to separate an object's interface from its implementation. +* [Composite](https://java-design-patterns.com/patterns/composite/): The Bridge pattern is often used with the Composite pattern to model the implementation details of a component. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): The Strategy pattern is like the Bridge pattern, but with a different intent. Both patterns are based on composition: Strategy uses composition to change the behavior of a class, while Bridge uses composition to separate an abstraction from its implementation. -## Credits +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) +* [Pattern-Oriented Software Architecture Volume 1: A System of Patterns](https://amzn.to/3TEnhtl) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/bridge/etc/bridge-sequence-diagram.png b/bridge/etc/bridge-sequence-diagram.png new file mode 100644 index 000000000000..b797827628bc Binary files /dev/null and b/bridge/etc/bridge-sequence-diagram.png differ diff --git a/bridge/etc/bridge.urm.png b/bridge/etc/bridge.urm.png new file mode 100644 index 000000000000..785585bf8163 Binary files /dev/null and b/bridge/etc/bridge.urm.png differ diff --git a/bridge/etc/bridge.urm.puml b/bridge/etc/bridge.urm.puml new file mode 100644 index 000000000000..d5d6a38a91d9 --- /dev/null +++ b/bridge/etc/bridge.urm.puml @@ -0,0 +1,58 @@ +@startuml +package com.iluwatar.bridge { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + interface Enchantment { + + apply() {abstract} + + onActivate() {abstract} + + onDeactivate() {abstract} + } + class FlyingEnchantment { + - LOGGER : Logger {static} + + FlyingEnchantment() + + apply() + + onActivate() + + onDeactivate() + } + class Hammer { + - LOGGER : Logger {static} + - enchantment : Enchantment + + Hammer(enchantment : Enchantment) + + getEnchantment() : Enchantment + + swing() + + unwield() + + wield() + } + class SoulEatingEnchantment { + - LOGGER : Logger {static} + + SoulEatingEnchantment() + + apply() + + onActivate() + + onDeactivate() + } + class Sword { + - LOGGER : Logger {static} + - enchantment : Enchantment + + Sword(enchantment : Enchantment) + + getEnchantment() : Enchantment + + swing() + + unwield() + + wield() + } + interface Weapon { + + getEnchantment() : Enchantment {abstract} + + swing() {abstract} + + unwield() {abstract} + + wield() {abstract} + } +} +Sword --> "-enchantment" Enchantment +Hammer --> "-enchantment" Enchantment +FlyingEnchantment ..|> Enchantment +Hammer ..|> Weapon +SoulEatingEnchantment ..|> Enchantment +Sword ..|> Weapon +@enduml \ No newline at end of file diff --git a/bridge/pom.xml b/bridge/pom.xml index 8ab24c159fd6..3cfd33997c05 100644 --- a/bridge/pom.xml +++ b/bridge/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT bridge - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.bridge.App + + + + + + + + diff --git a/bridge/src/main/java/com/iluwatar/bridge/App.java b/bridge/src/main/java/com/iluwatar/bridge/App.java index c986de6565dd..c3ea3d50c35a 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/App.java +++ b/bridge/src/main/java/com/iluwatar/bridge/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,40 +24,38 @@ */ package com.iluwatar.bridge; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * - * 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 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. - * + * 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 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. */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { LOGGER.info("The knight receives an enchanted sword."); - Sword enchantedSword = new Sword(new SoulEatingEnchantment()); + var enchantedSword = new Sword(new SoulEatingEnchantment()); enchantedSword.wield(); enchantedSword.swing(); enchantedSword.unwield(); LOGGER.info("The valkyrie receives an enchanted hammer."); - Hammer hammer = new Hammer(new FlyingEnchantment()); + var hammer = new Hammer(new FlyingEnchantment()); hammer.wield(); hammer.swing(); hammer.unwield(); diff --git a/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java b/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java index dd0c172059cf..4bdd4502fd47 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.bridge; -/** - * - * Enchantment - * - */ +/** Enchantment. */ public interface Enchantment { void onActivate(); diff --git a/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java b/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java index 8b12c6114e88..42da3523fb31 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.bridge; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * FlyingEnchantment - * - */ +/** FlyingEnchantment. */ +@Slf4j public class FlyingEnchantment implements Enchantment { - private static final Logger LOGGER = LoggerFactory.getLogger(FlyingEnchantment.class); - @Override public void onActivate() { LOGGER.info("The item begins to glow faintly."); diff --git a/bridge/src/main/java/com/iluwatar/bridge/Hammer.java b/bridge/src/main/java/com/iluwatar/bridge/Hammer.java index 51bfda2a1b97..328f3b79e9d6 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Hammer.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Hammer.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,24 +24,16 @@ */ package com.iluwatar.bridge; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; -/** - * - * Hammer - * - */ +/** Hammer. */ +@Slf4j +@AllArgsConstructor public class Hammer implements Weapon { - private static final Logger LOGGER = LoggerFactory.getLogger(Hammer.class); - private final Enchantment enchantment; - public Hammer(Enchantment enchantment) { - this.enchantment = enchantment; - } - @Override public void wield() { LOGGER.info("The hammer is wielded."); @@ -48,7 +42,7 @@ public void wield() { @Override public void swing() { - LOGGER.info("The hammer is swinged."); + LOGGER.info("The hammer is swung."); enchantment.apply(); } diff --git a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java index 8b08d155c083..ed22174673d3 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.bridge; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * SoulEatingEnchantment - * - */ +/** SoulEatingEnchantment. */ +@Slf4j public class SoulEatingEnchantment implements Enchantment { - private static final Logger LOGGER = LoggerFactory.getLogger(SoulEatingEnchantment.class); - @Override public void onActivate() { LOGGER.info("The item spreads bloodlust."); diff --git a/bridge/src/main/java/com/iluwatar/bridge/Sword.java b/bridge/src/main/java/com/iluwatar/bridge/Sword.java index 6f52943a6ead..417bc9334046 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Sword.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Sword.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,24 +24,16 @@ */ package com.iluwatar.bridge; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; -/** - * - * Sword - * - */ +/** Sword. */ +@Slf4j +@AllArgsConstructor public class Sword implements Weapon { - private static final Logger LOGGER = LoggerFactory.getLogger(Sword.class); - private final Enchantment enchantment; - public Sword(Enchantment enchantment) { - this.enchantment = enchantment; - } - @Override public void wield() { LOGGER.info("The sword is wielded."); @@ -48,7 +42,7 @@ public void wield() { @Override public void swing() { - LOGGER.info("The sword is swinged."); + LOGGER.info("The sword is swung."); enchantment.apply(); } diff --git a/bridge/src/main/java/com/iluwatar/bridge/Weapon.java b/bridge/src/main/java/com/iluwatar/bridge/Weapon.java index a2d21b88f5aa..a9f0ab4bbf52 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Weapon.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Weapon.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.bridge; -/** - * - * Weapon - * - */ +/** Weapon. */ public interface Weapon { void wield(); diff --git a/bridge/src/test/java/com/iluwatar/bridge/AppTest.java b/bridge/src/test/java/com/iluwatar/bridge/AppTest.java index 233f1d481e33..d1136fc90f41 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/AppTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,21 @@ */ package com.iluwatar.bridge; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java b/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java index 4cb3bd69e925..d8853647cb84 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,23 +24,21 @@ */ package com.iluwatar.bridge; -import org.junit.jupiter.api.Test; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; -/** - * Tests for hammer - */ -public class HammerTest extends WeaponTest { +import org.junit.jupiter.api.Test; + +/** Tests for hammer */ +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 testHammer() throws Exception { - final Hammer hammer = spy(new Hammer(mock(FlyingEnchantment.class))); + void testHammer() { + final var 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/SwordTest.java b/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java index e1cccb39afb6..b021cd08d00c 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,23 +24,21 @@ */ package com.iluwatar.bridge; -import org.junit.jupiter.api.Test; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; -/** - * Tests for sword - */ -public class SwordTest extends WeaponTest { +import org.junit.jupiter.api.Test; + +/** Tests for sword */ +class SwordTest 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 testSword() throws Exception { - final Sword sword = spy(new Sword(mock(FlyingEnchantment.class))); + void testSword() { + final var sword = spy(new Sword(mock(FlyingEnchantment.class))); testBasicWeaponActions(sword); } -} \ No newline at end of file +} diff --git a/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java b/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java index e8518eb50b06..67648ea6391e 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,25 +24,20 @@ */ package com.iluwatar.bridge; -import org.junit.jupiter.api.Disabled; - import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -/** - * Base class for weapon tests - */ -public abstract class WeaponTest { +/** Base class for weapon tests */ +abstract class WeaponTest { /** - * Invoke the basic actions of the given weapon, and test if the underlying enchantment implementation - * is invoked - * + * Invoke the basic actions of the given weapon, and test if the underlying enchantment + * implementation is invoked */ - protected final void testBasicWeaponActions(final Weapon weapon) { + final void testBasicWeaponActions(final Weapon weapon) { assertNotNull(weapon); - Enchantment enchantment = weapon.getEnchantment(); + var enchantment = weapon.getEnchantment(); assertNotNull(enchantment); assertNotNull(weapon.getEnchantment()); @@ -55,6 +52,5 @@ protected final void testBasicWeaponActions(final Weapon weapon) { weapon.unwield(); verify(enchantment).onDeactivate(); verifyNoMoreInteractions(enchantment); - } } diff --git a/builder/README.md b/builder/README.md index b775f1064a1e..cf6e3242dd51 100644 --- a/builder/README.md +++ b/builder/README.md @@ -1,25 +1,26 @@ --- -layout: pattern -title: Builder -folder: builder -permalink: /patterns/builder/ -categories: Creational -tags: - - Java - - Gang Of Four - - Difficulty-Intermediate +title: "Builder Pattern in Java: Crafting Custom Objects with Clarity" +shortTitle: Builder +description: "Discover the Builder design pattern in Java, a powerful creational pattern that simplifies object construction. Learn how to separate the construction of a complex object from its representation with practical examples and use cases." +category: Creational +language: en +tag: + - Gang of Four + - Instantiation + - Object composition --- -## Intent -Separate the construction of a complex object from its -representation so that the same construction process can create different -representations. +## Intent of Builder Design Pattern -## Explanation +The Builder design pattern in Java, a fundamental creational pattern, allows for the step-by-step construction of complex objects. It separates the construction of a complex object from its representation so that the same construction process can create different representations. -Real world example +## Detailed Explanation of Builder Pattern with Real-World Examples -> 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. +Real-world example + +> The Java Builder pattern is particularly useful in scenarios where object creation involves numerous parameters. +> +> Imagine you are building a customizable sandwich at a deli. The Builder design pattern in this context would involve a SandwichBuilder that allows you to specify each component of the sandwich, such as the type of bread, meat, cheese, vegetables, and condiments. Instead of having to know how to construct the sandwich from scratch, you use the SandwichBuilder to add each desired component step-by-step, ensuring you get exactly the sandwich you want. This separation of construction from the final product representation ensures that the same construction process can yield different types of sandwiches based on the specified components. In plain words @@ -27,42 +28,51 @@ In plain words 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. +> The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor antipattern. -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: +With that in mind, let's explain what the telescoping constructor antipattern is. At some point, we have all encountered a constructor like the one below: ```java -public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) { +public Hero(Profession profession,String name,HairType hairType,HairColor hairColor,Armor armor,Weapon weapon){ + // Value assignments } ``` -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. +As you can see, the number of constructor parameters can quickly become overwhelming, making it difficult to understand their arrangement. Additionally, this list of parameters might continue to grow if you decide to add more options in the future. This is known as the telescoping constructor antipattern. + +Sequence diagram + +![Builder sequence diagram](./etc/builder-sequence-diagram.png) -**Programmatic Example** +## Programmatic Example of Builder Pattern in Java -The sane alternative is to use the Builder pattern. First of all we have our hero that we want to create +In this Java Builder pattern example, we construct different types of `Hero` objects with varying attributes. + +Imagine a character generator for a role-playing game. The simplest option is to let the computer generate the character for you. However, if you prefer to manually select character details such as profession, gender, hair color, etc., the character creation becomes a step-by-step process that concludes once all selections are made. + +A more sensible approach is to use the Builder pattern. First, let's consider the `Hero` that we want to create: ```java 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; - } + 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 +Then we have the `Builder`: ```java public static class Builder { @@ -74,60 +84,121 @@ And then we have the builder 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; + 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; + this.hairType = hairType; + return this; } public Builder withHairColor(HairColor hairColor) { - this.hairColor = hairColor; - return this; + this.hairColor = hairColor; + return this; } public Builder withArmor(Armor armor) { - this.armor = armor; - return this; + this.armor = armor; + return this; } public Builder withWeapon(Weapon weapon) { - this.weapon = weapon; - return this; + this.weapon = weapon; + return this; } public Hero build() { - return new Hero(this); + return new Hero(this); } - } +} ``` -And then it can be used as: +Then it can be used as: ```java -Hero mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build(); + public static void main(String[] args) { + + var mage = new Hero.Builder(Profession.MAGE, "Riobard") + .withHairColor(HairColor.BLACK) + .withWeapon(Weapon.DAGGER) + .build(); + LOGGER.info(mage.toString()); + + var warrior = new Hero.Builder(Profession.WARRIOR, "Amberjill") + .withHairColor(HairColor.BLOND) + .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD) + .build(); + LOGGER.info(warrior.toString()); + + var thief = new Hero.Builder(Profession.THIEF, "Desmond") + .withHairType(HairType.BALD) + .withWeapon(Weapon.BOW) + .build(); + LOGGER.info(thief.toString()); +} +``` + +Program output: + +``` +16:28:06.058 [main] INFO com.iluwatar.builder.App -- This is a mage named Riobard with black hair and wielding a dagger. +16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a warrior named Amberjill with blond long curly hair wearing chain mail and wielding a sword. +16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a thief named Desmond with bald head and wielding a bow. ``` -## Applicability +## When to Use the Builder Pattern in Java + Use the Builder pattern when -* the algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled -* the construction process must allow different representations for the object that's constructed +* The Builder pattern is ideal for Java applications requiring complex object creation. +* The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled +* The construction process must allow different representations for the object that's constructed +* It's particularly useful when a product requires a lot of steps to be created and when these steps need to be executed in a specific sequence -## Real world examples +## Builder Pattern Java Tutorials -* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) -* [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) as well as similar buffers such as FloatBuffer, IntBuffer and so on. -* [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) +* [Builder Design Pattern in Java (DigitalOcean)](https://www.journaldev.com/1425/builder-design-pattern-in-java) +* [Builder (Refactoring Guru)](https://refactoring.guru/design-patterns/builder) +* [Exploring Joshua Bloch’s Builder design pattern in Java (Java Magazine)](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) + +## Real-World Applications of Builder Pattern in Java + +* StringBuilder in Java for constructing strings. +* java.lang.StringBuffer used to create mutable string objects. +* Java.nio.ByteBuffer as well as similar buffers such as FloatBuffer, IntBuffer, and others +* javax.swing.GroupLayout.Group#addComponent() +* Various GUI builders in IDEs that construct UI components. * All implementations of [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) * [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## Benefits and Trade-offs of Builder Pattern + +Benefits: + +* More control over the construction process compared to other creational patterns +* Supports constructing objects step-by-step, defer construction steps or run steps recursively +* Can construct objects that require a complex assembly of sub-objects. The final product is detached from the parts that make it up, as well as their assembly process +* Single Responsibility Principle. You can isolate complex construction code from the business logic of the product + +Trade-offs: + +* The overall complexity of the code can increase since the pattern requires creating multiple new classes +* May increase memory usage due to the necessity of creating multiple builder objects + +## Related Java Design Patterns + +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Can be used in conjunction with Builder to build parts of a complex object. +* [Prototype](https://java-design-patterns.com/patterns/prototype/): Builders often create objects from a prototype. +* [Step Builder](https://java-design-patterns.com/patterns/step-builder/): It is a variation of the Builder pattern that generates a complex object using a step-by-step approach. The Step Builder pattern is a good choice when you need to build an object with a large number of optional parameters, and you want to avoid the telescoping constructor antipattern. -## Credits +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) -* [Effective Java (2nd Edition)](http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/builder/etc/builder-sequence-diagram.png b/builder/etc/builder-sequence-diagram.png new file mode 100644 index 000000000000..355556637870 Binary files /dev/null and b/builder/etc/builder-sequence-diagram.png differ diff --git a/builder/etc/builder.urm.png b/builder/etc/builder.urm.png new file mode 100644 index 000000000000..d77808d36097 Binary files /dev/null and b/builder/etc/builder.urm.png differ diff --git a/builder/etc/builder.urm.puml b/builder/etc/builder.urm.puml new file mode 100644 index 000000000000..43d595a176fc --- /dev/null +++ b/builder/etc/builder.urm.puml @@ -0,0 +1,100 @@ +@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} + } +} +Hero --> "-profession" Profession +Builder ..+ Hero +Hero --> "-armor" Armor +Builder --> "-hairColor" HairColor +Builder --> "-weapon" Weapon +Builder --> "-hairType" HairType +Hero --> "-hairColor" HairColor +Builder --> "-profession" Profession +Hero --> "-weapon" Weapon +Hero --> "-hairType" HairType +Builder --> "-armor" Armor +@enduml \ No newline at end of file diff --git a/builder/pom.xml b/builder/pom.xml index b17d530301d5..3677c187d5e6 100644 --- a/builder/pom.xml +++ b/builder/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT builder - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.builder.App + + + + + + + + diff --git a/builder/src/main/java/com/iluwatar/builder/App.java b/builder/src/main/java/com/iluwatar/builder/App.java index 9fcfdb65ac57..acec73a48ee1 100644 --- a/builder/src/main/java/com/iluwatar/builder/App.java +++ b/builder/src/main/java/com/iluwatar/builder/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,59 +25,60 @@ package com.iluwatar.builder; import com.iluwatar.builder.Hero.Builder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * * The intention of the Builder pattern is to find a solution to the telescoping constructor - * anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object + * antipattern. The telescoping constructor antipattern occurs when the increase of object * constructor parameter combination leads to an exponential list of constructors. Instead of using * numerous constructors, the builder pattern uses another object, a builder, that receives each * initialization parameter step by step and then returns the resulting constructed object at once. - *

    - * The Builder pattern has another benefit. It can be used for objects that contain flat data (html - * code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. This - * type of data cannot be edited step by step and must be edited at once. The best way to construct - * such an object is to use a builder class. - *

    - * In this example we have the Builder pattern variation as described by Joshua Bloch in Effective - * Java 2nd Edition. - *

    - * We want to build {@link Hero} objects, but its construction is complex because of the many - * parameters needed. To aid the user we introduce {@link Builder} class. {@link Hero.Builder} - * takes the minimum parameters to build {@link Hero} object in its constructor. After that - * additional configuration for the {@link Hero} object can be done using the fluent - * {@link Builder} interface. When configuration is ready the build method is called to receive - * the final {@link Hero} object. - * + * + *

    The Builder pattern has another benefit. It can be used for objects that contain flat data + * (html code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. + * This type of data cannot be edited step by step and must be edited at once. The best way to + * construct such an object is to use a builder class. + * + *

    In this example we have the Builder pattern variation as described by Joshua Bloch in + * Effective Java 2nd Edition. + * + *

    We want to build {@link Hero} objects, but its construction is complex because of the many + * parameters needed. To aid the user we introduce {@link Builder} class. {@link Hero.Builder} takes + * the minimum parameters to build {@link Hero} object in its constructor. After that additional + * configuration for the {@link Hero} object can be done using the fluent {@link Builder} interface. + * When configuration is ready the build method is called to receive the final {@link Hero} object. */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - Hero mage = - new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK) - .withWeapon(Weapon.DAGGER).build(); + var mage = + new Hero.Builder(Profession.MAGE, "Riobard") + .withHairColor(HairColor.BLACK) + .withWeapon(Weapon.DAGGER) + .build(); LOGGER.info(mage.toString()); - Hero warrior = - new Hero.Builder(Profession.WARRIOR, "Amberjill").withHairColor(HairColor.BLOND) - .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD) + var warrior = + new Hero.Builder(Profession.WARRIOR, "Amberjill") + .withHairColor(HairColor.BLOND) + .withHairType(HairType.LONG_CURLY) + .withArmor(Armor.CHAIN_MAIL) + .withWeapon(Weapon.SWORD) .build(); LOGGER.info(warrior.toString()); - Hero thief = - new Hero.Builder(Profession.THIEF, "Desmond").withHairType(HairType.BALD) - .withWeapon(Weapon.BOW).build(); + var thief = + new Hero.Builder(Profession.THIEF, "Desmond") + .withHairType(HairType.BALD) + .withWeapon(Weapon.BOW) + .build(); LOGGER.info(thief.toString()); - } } diff --git a/builder/src/main/java/com/iluwatar/builder/Armor.java b/builder/src/main/java/com/iluwatar/builder/Armor.java index 0deb9712c2bc..1710f569af5e 100644 --- a/builder/src/main/java/com/iluwatar/builder/Armor.java +++ b/builder/src/main/java/com/iluwatar/builder/Armor.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,17 @@ */ package com.iluwatar.builder; -/** - * - * Armor enumeration - * - */ -public enum Armor { +import lombok.AllArgsConstructor; - CLOTHES("clothes"), LEATHER("leather"), CHAIN_MAIL("chain mail"), PLATE_MAIL("plate mail"); - - private String title; +/** Armor enumeration. */ +@AllArgsConstructor +public enum Armor { + CLOTHES("clothes"), + LEATHER("leather"), + CHAIN_MAIL("chain mail"), + PLATE_MAIL("plate mail"); - Armor(String title) { - this.title = title; - } + private final String title; @Override public String toString() { diff --git a/builder/src/main/java/com/iluwatar/builder/HairColor.java b/builder/src/main/java/com/iluwatar/builder/HairColor.java index a3f03abfc952..7f767c98d661 100644 --- a/builder/src/main/java/com/iluwatar/builder/HairColor.java +++ b/builder/src/main/java/com/iluwatar/builder/HairColor.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,16 @@ */ package com.iluwatar.builder; -/** - * - * HairColor enumeration - * - */ +/** HairColor enumeration. */ public enum HairColor { - - WHITE, BLOND, RED, BROWN, BLACK; + WHITE, + BLOND, + RED, + BROWN, + BLACK; @Override public String toString() { return name().toLowerCase(); } - } diff --git a/builder/src/main/java/com/iluwatar/builder/HairType.java b/builder/src/main/java/com/iluwatar/builder/HairType.java index 604a0836d394..7ac31d0fa03e 100644 --- a/builder/src/main/java/com/iluwatar/builder/HairType.java +++ b/builder/src/main/java/com/iluwatar/builder/HairType.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,18 @@ */ package com.iluwatar.builder; -/** - * - * HairType enumeration - * - */ -public enum HairType { +import lombok.AllArgsConstructor; - BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY( - "long curly"); - - private String title; +/** HairType enumeration. */ +@AllArgsConstructor +public enum HairType { + BALD("bald"), + SHORT("short"), + CURLY("curly"), + LONG_STRAIGHT("long straight"), + LONG_CURLY("long curly"); - HairType(String title) { - this.title = title; - } + private final String title; @Override public String toString() { diff --git a/builder/src/main/java/com/iluwatar/builder/Hero.java b/builder/src/main/java/com/iluwatar/builder/Hero.java index e7f0b3cabbec..a87137e51fe0 100644 --- a/builder/src/main/java/com/iluwatar/builder/Hero.java +++ b/builder/src/main/java/com/iluwatar/builder/Hero.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,61 +24,30 @@ */ package com.iluwatar.builder; -/** - * - * Hero, the class with many parameters. - * - */ -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; +/** Hero,the record class. */ +public record Hero( + Profession profession, + String name, + HairType hairType, + HairColor hairColor, + Armor armor, + 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; - } - - public Profession getProfession() { - return profession; - } - - public String getName() { - return name; - } - - public HairType getHairType() { - return hairType; - } - - public HairColor getHairColor() { - return hairColor; - } - - public Armor getArmor() { - return armor; - } - - public Weapon getWeapon() { - return weapon; + this( + builder.profession, + builder.name, + builder.hairType, + builder.hairColor, + builder.armor, + builder.weapon); } @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("This is a ") - .append(profession) - .append(" named ") - .append(name); + var sb = new StringBuilder(); + sb.append("This is a ").append(profession).append(" named ").append(name); if (hairColor != null || hairType != null) { sb.append(" with "); if (hairColor != null) { @@ -97,11 +68,7 @@ public String toString() { return sb.toString(); } - /** - * - * The builder class. - * - */ + /** The builder class. */ public static class Builder { private final Profession profession; @@ -111,9 +78,7 @@ public static class Builder { private Armor armor; private Weapon weapon; - /** - * Constructor - */ + /** Constructor. */ public Builder(Profession profession, String name) { if (profession == null || name == null) { throw new IllegalArgumentException("profession and name can not be null"); diff --git a/builder/src/main/java/com/iluwatar/builder/Profession.java b/builder/src/main/java/com/iluwatar/builder/Profession.java index 579eed787baf..c1be949840f8 100644 --- a/builder/src/main/java/com/iluwatar/builder/Profession.java +++ b/builder/src/main/java/com/iluwatar/builder/Profession.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,12 @@ */ package com.iluwatar.builder; -/** - * - * Profession enumeration - * - */ +/** Profession enumeration. */ public enum Profession { - - WARRIOR, THIEF, MAGE, PRIEST; + WARRIOR, + THIEF, + MAGE, + PRIEST; @Override public String toString() { diff --git a/builder/src/main/java/com/iluwatar/builder/Weapon.java b/builder/src/main/java/com/iluwatar/builder/Weapon.java index 86c910a44634..03a9565d0cbe 100644 --- a/builder/src/main/java/com/iluwatar/builder/Weapon.java +++ b/builder/src/main/java/com/iluwatar/builder/Weapon.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,13 @@ */ package com.iluwatar.builder; -/** - * - * Weapon enumeration - * - */ +/** Weapon enumeration. */ public enum Weapon { - - DAGGER, SWORD, AXE, WARHAMMER, BOW; + DAGGER, + SWORD, + AXE, + WARHAMMER, + BOW; @Override public String toString() { diff --git a/builder/src/test/java/com/iluwatar/builder/AppTest.java b/builder/src/test/java/com/iluwatar/builder/AppTest.java index abaaa034f734..367d3da1c1ac 100644 --- a/builder/src/test/java/com/iluwatar/builder/AppTest.java +++ b/builder/src/test/java/com/iluwatar/builder/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,21 @@ */ package com.iluwatar.builder; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/builder/src/test/java/com/iluwatar/builder/HeroTest.java b/builder/src/test/java/com/iluwatar/builder/HeroTest.java index aa2e1490f72d..5f67a56aa999 100644 --- a/builder/src/test/java/com/iluwatar/builder/HeroTest.java +++ b/builder/src/test/java/com/iluwatar/builder/HeroTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,58 +24,47 @@ */ package com.iluwatar.builder; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; -/** - * Date: 12/6/15 - 11:01 PM - * - * @author Jeroen Meulemeester - */ -public class HeroTest { +import org.junit.jupiter.api.Test; + +/** HeroTest */ +class HeroTest { - /** - * Test if we get the expected exception when trying to create a hero without a profession - */ + /** Test if we get the expected exception when trying to create a hero without a profession */ @Test - public void testMissingProfession() throws Exception { + void testMissingProfession() { assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(null, "Sir without a job")); } - /** - * Test if we get the expected exception when trying to create a hero without a name - */ + /** Test if we get the expected exception when trying to create a hero without a name */ @Test - public void testMissingName() throws Exception { + void testMissingName() { assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(Profession.THIEF, null)); } - /** - * Test if the hero build by the builder has the correct attributes, as requested - */ + /** Test if the hero build by the builder has the correct attributes, as requested */ @Test - public void testBuildHero() throws Exception { + void testBuildHero() { final String heroName = "Sir Lancelot"; - final Hero hero = new Hero.Builder(Profession.WARRIOR, heroName) - .withArmor(Armor.CHAIN_MAIL) - .withWeapon(Weapon.SWORD) - .withHairType(HairType.LONG_CURLY) - .withHairColor(HairColor.BLOND) - .build(); + final var hero = + new Hero.Builder(Profession.WARRIOR, heroName) + .withArmor(Armor.CHAIN_MAIL) + .withWeapon(Weapon.SWORD) + .withHairType(HairType.LONG_CURLY) + .withHairColor(HairColor.BLOND) + .build(); assertNotNull(hero); assertNotNull(hero.toString()); - assertEquals(Profession.WARRIOR, hero.getProfession()); - assertEquals(heroName, hero.getName()); - assertEquals(Armor.CHAIN_MAIL, hero.getArmor()); - assertEquals(Weapon.SWORD, hero.getWeapon()); - assertEquals(HairType.LONG_CURLY, hero.getHairType()); - assertEquals(HairColor.BLOND, hero.getHairColor()); - + assertEquals(Profession.WARRIOR, hero.profession()); + assertEquals(heroName, hero.name()); + assertEquals(Armor.CHAIN_MAIL, hero.armor()); + assertEquals(Weapon.SWORD, hero.weapon()); + assertEquals(HairType.LONG_CURLY, hero.hairType()); + assertEquals(HairColor.BLOND, hero.hairColor()); } - -} \ No newline at end of file +} diff --git a/business-delegate/README.md b/business-delegate/README.md index e6e2491222e0..9f83e1a1748a 100644 --- a/business-delegate/README.md +++ b/business-delegate/README.md @@ -1,29 +1,193 @@ --- -layout: pattern -title: Business Delegate -folder: business-delegate -permalink: /patterns/business-delegate/ -categories: Business Tier -tags: - - Java - - Difficulty-Intermediate +title: "Business Delegate Pattern in Java: Simplifying Business Service Interaction" +shortTitle: Business Delegate +description: "Learn about the Business Delegate pattern in Java. This design pattern adds an abstraction layer between presentation and business tiers, ensuring loose coupling and easier service interaction. Includes examples and class diagrams." +category: Structural +language: en +tag: + - Business + - Decoupling + - Delegation + - Enterprise patterns + - Layered architecture --- -## Intent -The Business Delegate pattern adds an abstraction layer between -presentation and business tiers. By using the pattern we gain loose coupling -between the tiers and encapsulate knowledge about how to locate, connect to, -and interact with the business objects that make up the application. +## Also known as -![alt text](./etc/business-delegate.png "Business Delegate") +* Service Representative + +## Intent of Business Delegate Design Pattern + +The Business Delegate pattern is a structural design pattern in Java that adds an abstraction layer between the presentation and business tiers. By using the pattern we gain loose coupling between the tiers and encapsulate knowledge about how to locate, connect to, and interact with the business objects that make up the application. + +## Detailed Explanation of Business Delegate Pattern with Real-World Examples + +Real-world example + +> In an Enterprise application using Java EE, the Business Delegate pattern helps manage interactions between different business services. +> +> Imagine a restaurant where the waitstaff serves as intermediaries between the customers and the kitchen. When a customer places an order, the waiter takes the order to the kitchen, relays any specific requests, and later brings the prepared food back to the customer. The waitstaff abstracts the complexity of the kitchen operations from the customers, allowing the chefs to focus solely on cooking without needing to interact directly with customers. This setup allows both the customer service (presentation tier) and the kitchen (business service) to operate independently and efficiently. The waitstaff acts as the Business Delegate, managing communication and ensuring smooth interactions between the two distinct areas. + +In Plain Words + +> Business Delegate adds an abstraction layer between the presentation and business tiers. + +Wikipedia says + +> Business Delegate is a Java EE design pattern. This pattern is directing to reduce the coupling in between business services and the connected presentation tier, and to hide the implementation details of services (including lookup and accessibility of EJB architecture). Business Delegates acts as an adaptor to invoke business objects from the presentation tier. + +Sequence diagram + +![Business Delegate sequence diagram](./etc/business-delegate-sequence-diagram.png) + +## Programmatic Example of Business Delegate Pattern in Java + +The following Java code demonstrates how to implement the Business Delegate pattern. This pattern is particularly useful in applications requiring loose coupling and efficient service interaction. + +A mobile phone application promises to stream any movie in existence to your device. It captures the user's search string and passes this on to the Business Delegate. The Business Delegate selects the most suitable video streaming service and plays the video from there. + +First, we have an abstraction for video streaming services and a couple of implementations. + +```java +public interface VideoStreamingService { + void doProcessing(); +} + +@Slf4j +public class NetflixService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("NetflixService is now processing"); + } +} + +@Slf4j +public class YouTubeService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("YouTubeService is now processing"); + } +} +``` + +Then, we have a lookup service that decides which video streaming service to use. + +```java + +@Setter +public class BusinessLookup { + + private NetflixService netflixService; + private YouTubeService youTubeService; + + public VideoStreamingService getBusinessService(String movie) { + if (movie.toLowerCase(Locale.ROOT).contains("die hard")) { + return netflixService; + } else { + return youTubeService; + } + } +} +``` + +The Business Delegate uses a business lookup to route movie playback requests to a suitable video streaming service. + +```java + +@Setter +public class BusinessDelegate { + + private BusinessLookup lookupService; + + public void playbackMovie(String movie) { + VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie); + videoStreamingService.doProcessing(); + } +} +``` + +The mobile client utilizes Business Delegate to call the business tier. + +```java +public class MobileClient { + + private final BusinessDelegate businessDelegate; + + public MobileClient(BusinessDelegate businessDelegate) { + this.businessDelegate = businessDelegate; + } + + public void playbackMovie(String movie) { + businessDelegate.playbackMovie(movie); + } +} +``` + +Finally, we can demonstrate the complete example in action. + +```java +public static void main(String[] args) { + + // prepare the objects + var businessDelegate = new BusinessDelegate(); + var businessLookup = new BusinessLookup(); + businessLookup.setNetflixService(new NetflixService()); + businessLookup.setYouTubeService(new YouTubeService()); + businessDelegate.setLookupService(businessLookup); + + // create the client and use the business delegate + var client = new MobileClient(businessDelegate); + client.playbackMovie("Die Hard 2"); + client.playbackMovie("Maradona: The Greatest Ever"); +} +``` + +Here is the console output. + +``` +21:15:33.790 [main] INFO com.iluwatar.business.delegate.NetflixService - NetflixService is now processing +21:15:33.794 [main] INFO com.iluwatar.business.delegate.YouTubeService - YouTubeService is now processing +``` + +## When to Use the Business Delegate Pattern in Java -## Applicability Use the Business Delegate pattern when -* you want loose coupling between presentation and business tiers -* you want to orchestrate calls to multiple business services -* you want to encapsulate service lookups and service calls +* You need loose coupling between presentation and business tiers or need to abstract service lookups. +* You want to orchestrate calls to multiple business services +* You want to encapsulate service lookups and service calls +* There is a need to abstract and encapsulate the communication between the client tier and business services + +## Business Delegate Pattern Java Tutorials + +* [Design Patterns - Business Delegate Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/business_delegate_pattern.htm) + +## Real-World Applications of Business Delegate Pattern in Java + +* Enterprise applications using Java EE (Java Platform, Enterprise Edition) +* Applications requiring remote access to business services + +## Benefits and Trade-offs of Business Delegate Pattern + +Benefits: + +* Decoupling of Presentation and Business Tiers: Allows the client tier and business services to evolve independently. +* Location Transparency: Clients remain unaffected by changes in the location or the instantiation of business services. +* Reuse and Scalability: Business Delegate objects can be reused by multiple clients, and the pattern supports load balancing and scalability. + +Trade-offs: + +* Complexity: Introduces additional layers and abstractions, which may increase complexity. +* Performance Overhead: The additional indirection may incur a slight performance penalty. + +## Related Java Design Patterns + +* [Service Locator](https://java-design-patterns.com/patterns/service-locator/): Business Delegate uses Service Locator to locate business services. +* [Session Facade](https://java-design-patterns.com/patterns/session-facade/): Business Delegate may use Session Facade to provide a unified interface to a set of business services. +* [Composite Entity](https://java-design-patterns.com/patterns/composite-entity/): Business Delegate may use Composite Entity to manage the state of business services. -## Credits +## References and Credits -* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2) +* [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/business-delegate/etc/business-delegate-sequence-diagram.png b/business-delegate/etc/business-delegate-sequence-diagram.png new file mode 100644 index 000000000000..a6279e9d1888 Binary files /dev/null and b/business-delegate/etc/business-delegate-sequence-diagram.png differ diff --git a/business-delegate/etc/business-delegate.png b/business-delegate/etc/business-delegate.png deleted file mode 100644 index 928cf934645b..000000000000 Binary files a/business-delegate/etc/business-delegate.png and /dev/null differ diff --git a/business-delegate/etc/business-delegate.ucls b/business-delegate/etc/business-delegate.ucls deleted file mode 100644 index 668a6579eb47..000000000000 --- a/business-delegate/etc/business-delegate.ucls +++ /dev/null @@ -1,136 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/business-delegate/etc/business-delegate.urm.png b/business-delegate/etc/business-delegate.urm.png new file mode 100644 index 000000000000..4dca6c263b99 Binary files /dev/null and b/business-delegate/etc/business-delegate.urm.png differ diff --git a/business-delegate/etc/business-delegate.urm.puml b/business-delegate/etc/business-delegate.urm.puml new file mode 100644 index 000000000000..407e3e12d1ea --- /dev/null +++ b/business-delegate/etc/business-delegate.urm.puml @@ -0,0 +1,46 @@ +@startuml +package com.iluwatar.business.delegate { + class App { + + App() + + main(args : String[]) {static} + } + class BusinessDelegate { + - lookupService : BusinessLookup + + BusinessDelegate() + + playbackMovie(movie : String) + + setLookupService(lookupService : BusinessLookup) + } + class BusinessLookup { + - netflixService : NetflixService + - youTubeService : YouTubeService + + BusinessLookup() + + getBusinessService(movie : String) : VideoStreamingService + + setNetflixService(netflixService : NetflixService) + + setYouTubeService(youTubeService : YouTubeService) + } + class MobileClient { + - businessDelegate : BusinessDelegate + + MobileClient(businessDelegate : BusinessDelegate) + + playbackMovie(movie : String) + } + class NetflixService { + - LOGGER : Logger {static} + + NetflixService() + + doProcessing() + } + interface VideoStreamingService { + + doProcessing() {abstract} + } + class YouTubeService { + - LOGGER : Logger {static} + + YouTubeService() + + doProcessing() + } +} +BusinessLookup --> "-netflixService" NetflixService +BusinessLookup --> "-youTubeService" YouTubeService +MobileClient --> "-businessDelegate" BusinessDelegate +BusinessDelegate --> "-lookupService" BusinessLookup +NetflixService ..|> VideoStreamingService +YouTubeService ..|> VideoStreamingService +@enduml \ No newline at end of file diff --git a/business-delegate/pom.xml b/business-delegate/pom.xml index d48faeff4240..a5bccb1529e7 100644 --- a/business-delegate/pom.xml +++ b/business-delegate/pom.xml @@ -1,8 +1,10 @@ - + - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - business-delegate - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.mockito - mockito-core - test - - + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + business-delegate + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.business.delegate.App + + + + + + + + diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java index 945f09c0a52f..c23ed42caecd 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -27,14 +29,14 @@ * tiers. By using the pattern we gain loose coupling between the tiers. The Business Delegate * encapsulates knowledge about how to locate, connect to, and interact with the business objects * that make up the application. - * + * *

    Some of the services the Business Delegate uses are instantiated directly, and some can be * retrieved through service lookups. The Business Delegate itself may contain business logic too * potentially tying together multiple service calls, exception handling, retrying etc. - * - *

    In this example the client ({@link Client}) utilizes a business delegate ( - * {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate - * service and makes the service call. + * + *

    In this example the client ({@link MobileClient}) utilizes a business delegate ( {@link + * BusinessDelegate}) to search for movies in video streaming services. The Business Delegate then + * selects the appropriate service and makes the service call. */ public class App { @@ -45,18 +47,16 @@ public class App { */ public static void main(String[] args) { - BusinessDelegate businessDelegate = new BusinessDelegate(); - BusinessLookup businessLookup = new BusinessLookup(); - businessLookup.setEjbService(new EjbService()); - businessLookup.setJmsService(new JmsService()); - + // prepare the objects + var businessDelegate = new BusinessDelegate(); + var businessLookup = new BusinessLookup(); + businessLookup.setNetflixService(new NetflixService()); + businessLookup.setYouTubeService(new YouTubeService()); businessDelegate.setLookupService(businessLookup); - businessDelegate.setServiceType(ServiceType.EJB); - - Client client = new Client(businessDelegate); - client.doTask(); - businessDelegate.setServiceType(ServiceType.JMS); - client.doTask(); + // create the client and use the business delegate + var client = new MobileClient(businessDelegate); + client.playbackMovie("Die Hard 2"); + client.playbackMovie("Maradona: The Greatest Ever"); } } diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java index 32b2bc770c36..81920c857cd8 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,25 +24,16 @@ */ package com.iluwatar.business.delegate; -/** - * BusinessDelegate separates the presentation and business tiers - */ +import lombok.Setter; + +/** BusinessDelegate separates the presentation and business tiers. */ +@Setter public class BusinessDelegate { private BusinessLookup lookupService; - private BusinessService businessService; - private ServiceType serviceType; - - public void setLookupService(BusinessLookup businessLookup) { - this.lookupService = businessLookup; - } - - public void setServiceType(ServiceType serviceType) { - this.serviceType = serviceType; - } - public void doTask() { - businessService = lookupService.getBusinessService(serviceType); - businessService.doProcessing(); + public void playbackMovie(String movie) { + VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie); + videoStreamingService.doProcessing(); } } diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java index ae3c54b864d9..81a1b2f18fd0 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,32 +24,28 @@ */ package com.iluwatar.business.delegate; -/** - * Class for performing service lookups. - */ +import java.util.Locale; +import lombok.Setter; + +/** Class for performing service lookups. */ +@Setter public class BusinessLookup { - private EjbService ejbService; + private NetflixService netflixService; - private JmsService jmsService; + private YouTubeService youTubeService; /** - * @param serviceType Type of service instance to be returned. + * Gets service instance based on given movie search string. + * + * @param movie Search string for the movie. * @return Service instance. */ - public BusinessService getBusinessService(ServiceType serviceType) { - if (serviceType.equals(ServiceType.EJB)) { - return ejbService; + public VideoStreamingService getBusinessService(String movie) { + if (movie.toLowerCase(Locale.ROOT).contains("die hard")) { + return netflixService; } else { - return jmsService; + return youTubeService; } } - - public void setJmsService(JmsService jmsService) { - this.jmsService = jmsService; - } - - public void setEjbService(EjbService ejbService) { - this.ejbService = ejbService; - } } diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java deleted file mode 100644 index fbda6c67eabc..000000000000 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java +++ /dev/null @@ -1,33 +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.business.delegate; - -/** - * - * Interface for service implementations - * - */ -public interface BusinessService { - - void doProcessing(); -} diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java deleted file mode 100644 index e521426aec71..000000000000 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java +++ /dev/null @@ -1,41 +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.business.delegate; - -/** - * - * Client utilizes BusinessDelegate to call the business tier - * - */ -public class Client { - - private BusinessDelegate businessDelegate; - - public Client(BusinessDelegate businessDelegate) { - this.businessDelegate = businessDelegate; - } - - public void doTask() { - businessDelegate.doTask(); - } -} diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java deleted file mode 100644 index afe53600aaab..000000000000 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java +++ /dev/null @@ -1,41 +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.business.delegate; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Service EJB implementation - * - */ -public class EjbService implements BusinessService { - - private static final Logger LOGGER = LoggerFactory.getLogger(EjbService.class); - - @Override - public void doProcessing() { - LOGGER.info("EjbService is now processing"); - } -} diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java deleted file mode 100644 index 4b112906efba..000000000000 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java +++ /dev/null @@ -1,41 +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.business.delegate; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Service JMS implementation - * - */ -public class JmsService implements BusinessService { - - private static final Logger LOGGER = LoggerFactory.getLogger(JmsService.class); - - @Override - public void doProcessing() { - LOGGER.info("JmsService is now processing"); - } -} diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/MobileClient.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/MobileClient.java new file mode 100644 index 000000000000..01b5b642735b --- /dev/null +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/MobileClient.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.business.delegate; + +/** MobileClient utilizes BusinessDelegate to call the business tier. */ +public class MobileClient { + + private final BusinessDelegate businessDelegate; + + public MobileClient(BusinessDelegate businessDelegate) { + this.businessDelegate = businessDelegate; + } + + public void playbackMovie(String movie) { + businessDelegate.playbackMovie(movie); + } +} diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/NetflixService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/NetflixService.java new file mode 100644 index 000000000000..696480e678f3 --- /dev/null +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/NetflixService.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.business.delegate; + +import lombok.extern.slf4j.Slf4j; + +/** NetflixService implementation. */ +@Slf4j +public class NetflixService implements VideoStreamingService { + + @Override + public void doProcessing() { + LOGGER.info("NetflixService is now processing"); + } +} diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java deleted file mode 100644 index ac82d7daf628..000000000000 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java +++ /dev/null @@ -1,33 +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.business.delegate; - -/** - * - * Enumeration for service types - * - */ -public enum ServiceType { - - EJB, JMS; -} diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/VideoStreamingService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/VideoStreamingService.java new file mode 100644 index 000000000000..594b51850efb --- /dev/null +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/VideoStreamingService.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.business.delegate; + +/** Interface for video streaming service implementations. */ +public interface VideoStreamingService { + + void doProcessing(); +} diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/YouTubeService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/YouTubeService.java new file mode 100644 index 000000000000..65c2e55ff6fa --- /dev/null +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/YouTubeService.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.business.delegate; + +import lombok.extern.slf4j.Slf4j; + +/** YouTubeService implementation. */ +@Slf4j +public class YouTubeService implements VideoStreamingService { + + @Override + public void doProcessing() { + LOGGER.info("YouTubeService is now processing"); + } +} diff --git a/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java b/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java index 415f855d1d33..5f862bf6e5ff 100644 --- a/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java +++ b/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,22 @@ */ package com.iluwatar.business.delegate; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -import java.io.IOException; +/** Tests that Business Delegate example runs without errors. */ +class AppTest { -/** - * Tests that Business Delegate example runs without errors. - */ -public class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java b/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java index ccdaaae4ea4b..4b8e0ee77d5c 100644 --- a/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java +++ b/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,30 +24,20 @@ */ package com.iluwatar.business.delegate; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -/** - * The Business Delegate pattern adds an abstraction layer between the presentation and business - * tiers. By using the pattern we gain loose coupling between the tiers. The Business Delegate - * encapsulates knowledge about how to locate, connect to, and interact with the business objects - * that make up the application. - * - *

    Some of the services the Business Delegate uses are instantiated directly, and some can be - * retrieved through service lookups. The Business Delegate itself may contain business logic too - * potentially tying together multiple service calls, exception handling, retrying etc. - */ -public class BusinessDelegateTest { +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; - private EjbService ejbService; +/** Tests for the {@link BusinessDelegate} */ +class BusinessDelegateTest { - private JmsService jmsService; + private NetflixService netflixService; - private BusinessLookup businessLookup; + private YouTubeService youTubeService; private BusinessDelegate businessDelegate; @@ -54,47 +46,41 @@ public class BusinessDelegateTest { * execution of every test. */ @BeforeEach - public void setup() { - ejbService = spy(new EjbService()); - jmsService = spy(new JmsService()); + void setup() { + netflixService = spy(new NetflixService()); + youTubeService = spy(new YouTubeService()); - businessLookup = spy(new BusinessLookup()); - businessLookup.setEjbService(ejbService); - businessLookup.setJmsService(jmsService); + BusinessLookup businessLookup = spy(new BusinessLookup()); + businessLookup.setNetflixService(netflixService); + businessLookup.setYouTubeService(youTubeService); businessDelegate = spy(new BusinessDelegate()); businessDelegate.setLookupService(businessLookup); } /** - * In this example the client ({@link Client}) utilizes a business delegate ( - * {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate + * In this example the client ({@link MobileClient}) utilizes a business delegate ( {@link + * BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate * service and makes the service call. */ @Test - public void testBusinessDelegate() { + void testBusinessDelegate() { // setup a client object - Client client = new Client(businessDelegate); - - // set the service type - businessDelegate.setServiceType(ServiceType.EJB); + var client = new MobileClient(businessDelegate); // action - client.doTask(); - - // verifying that the businessDelegate was used by client during doTask() method. - verify(businessDelegate).doTask(); - verify(ejbService).doProcessing(); + client.playbackMovie("Die hard"); - // set the service type - businessDelegate.setServiceType(ServiceType.JMS); + // verifying that the businessDelegate was used by client during playbackMovie() method. + verify(businessDelegate).playbackMovie(anyString()); + verify(netflixService).doProcessing(); // action - client.doTask(); + client.playbackMovie("Maradona"); // verifying that the businessDelegate was used by client during doTask() method. - verify(businessDelegate, times(2)).doTask(); - verify(jmsService).doProcessing(); + verify(businessDelegate, times(2)).playbackMovie(anyString()); + verify(youTubeService).doProcessing(); } } diff --git a/bytecode/README.md b/bytecode/README.md new file mode 100644 index 000000000000..793eecffcc0e --- /dev/null +++ b/bytecode/README.md @@ -0,0 +1,270 @@ +--- +title: "Bytecode Pattern in Java: Interpreting Instructions with Custom Virtual Machines" +shortTitle: Bytecode +description: "Explore the Bytecode design pattern in Java, including its implementation, real-world examples, and use cases for efficient virtual machine instruction handling." +category: Behavioral +language: en +tag: + - Abstraction + - Code simplification + - Encapsulation + - Game programming + - Performance + - Runtime +--- + +## Intent of Bytecode Design Pattern + +The Bytecode design pattern in Java allows encoding behavior as instructions for a virtual machine, making it a powerful tool in game development and other applications. + +## Detailed Explanation of Bytecode Pattern with Real-World Examples + +Real-world example + +> An analogous real-world example of the Bytecode design pattern can be seen in the process of translating a book into multiple languages. Instead of directly translating the book from the original language into every other language, the book is first translated into a common intermediate language, like Esperanto. This intermediate version is easier to translate because it is simpler and more structured. Translators for each target language then translate from Esperanto into their specific languages. This approach ensures consistency, reduces errors, and simplifies the translation process, similar to how bytecode serves as an intermediate representation to optimize and facilitate the execution of high-level programming languages across different platforms. + +In plain words + +> Bytecode pattern enables behavior driven by data instead of code. + +[gameprogrammingpatterns.com](https://gameprogrammingpatterns.com/bytecode.html) documentation states: + +> An instruction set defines the low-level operations that can be performed. A series of instructions is encoded as a sequence of bytes. A virtual machine executes these instructions one at a time, using a stack for intermediate values. By combining instructions, complex high-level behavior can be defined. + +Sequence diagram + +![Bytecode sequence diagram](./etc/bytecode-sequence-diagram.png) + +## Programmatic Example of Bytecode Pattern in Java + +In this programmatic example, we show how the Bytecode pattern in Java can simplify the execution of complex virtual machine instructions through a well-defined set of operations. This real-world example demonstrates how the Bytecode design pattern in Java can streamline game programming by allowing wizards' behavior to be easily adjusted through bytecode instructions. + +A team is working on a new game where wizards battle against each other. The wizard behavior needs to be carefully adjusted and iterated hundreds of times through playtesting. It's not optimal to ask the programmer to make changes each time the game designer wants to vary the behavior, so the wizard behavior is implemented as a data-driven virtual machine. + +One of the most important game objects is the `Wizard` class. + +```java + +@AllArgsConstructor +@Setter +@Getter +@Slf4j +public class Wizard { + + private int health; + private int agility; + private int wisdom; + private int numberOfPlayedSounds; + private int numberOfSpawnedParticles; + + public void playSound() { + LOGGER.info("Playing sound"); + numberOfPlayedSounds++; + } + + public void spawnParticles() { + LOGGER.info("Spawning particles"); + numberOfSpawnedParticles++; + } +} +``` + +Next, we show the available instructions for our virtual machine. Each of the instructions has its own semantics on how it operates with the stack data. For example, the ADD instruction takes the top two items from the stack, adds them together and pushes the result to the stack. + +```java + +@AllArgsConstructor +@Getter +public enum Instruction { + + LITERAL(1), // e.g. "LITERAL 0", push 0 to stack + SET_HEALTH(2), // e.g. "SET_HEALTH", pop health and wizard number, call set health + SET_WISDOM(3), // e.g. "SET_WISDOM", pop wisdom and wizard number, call set wisdom + SET_AGILITY(4), // e.g. "SET_AGILITY", pop agility and wizard number, call set agility + PLAY_SOUND(5), // e.g. "PLAY_SOUND", pop value as wizard number, call play sound + SPAWN_PARTICLES(6), // e.g. "SPAWN_PARTICLES", pop value as wizard number, call spawn particles + GET_HEALTH(7), // e.g. "GET_HEALTH", pop value as wizard number, push wizard's health + GET_AGILITY(8), // e.g. "GET_AGILITY", pop value as wizard number, push wizard's agility + GET_WISDOM(9), // e.g. "GET_WISDOM", pop value as wizard number, push wizard's wisdom + ADD(10), // e.g. "ADD", pop 2 values, push their sum + DIVIDE(11); // e.g. "DIVIDE", pop 2 values, push their division + + // Other properties and methods... +} +``` + +At the heart of our example is the `VirtualMachine` class. It takes instructions as input and executes them to provide the game object behavior. + +```java + +@Getter +@Slf4j +public class VirtualMachine { + + private final Stack stack = new Stack<>(); + + private final Wizard[] wizards = new Wizard[2]; + + public VirtualMachine() { + wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), + 0, 0); + wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), + 0, 0); + } + + public VirtualMachine(Wizard wizard1, Wizard wizard2) { + wizards[0] = wizard1; + wizards[1] = wizard2; + } + + public void execute(int[] bytecode) { + for (var i = 0; i < bytecode.length; i++) { + Instruction instruction = Instruction.getInstruction(bytecode[i]); + switch (instruction) { + case LITERAL: + // Read the next byte from the bytecode. + int value = bytecode[++i]; + // Push the next value to stack + stack.push(value); + break; + case SET_AGILITY: + var amount = stack.pop(); + var wizard = stack.pop(); + setAgility(wizard, amount); + break; + case SET_WISDOM: + amount = stack.pop(); + wizard = stack.pop(); + setWisdom(wizard, amount); + break; + case SET_HEALTH: + amount = stack.pop(); + wizard = stack.pop(); + setHealth(wizard, amount); + break; + case GET_HEALTH: + wizard = stack.pop(); + stack.push(getHealth(wizard)); + break; + case GET_AGILITY: + wizard = stack.pop(); + stack.push(getAgility(wizard)); + break; + case GET_WISDOM: + wizard = stack.pop(); + stack.push(getWisdom(wizard)); + break; + case ADD: + var a = stack.pop(); + var b = stack.pop(); + stack.push(a + b); + break; + case DIVIDE: + a = stack.pop(); + b = stack.pop(); + stack.push(b / a); + break; + case PLAY_SOUND: + wizard = stack.pop(); + getWizards()[wizard].playSound(); + break; + case SPAWN_PARTICLES: + wizard = stack.pop(); + getWizards()[wizard].spawnParticles(); + break; + default: + throw new IllegalArgumentException("Invalid instruction value"); + } + LOGGER.info("Executed " + instruction.name() + ", Stack contains " + getStack()); + } + } + + public void setHealth(int wizard, int amount) { + wizards[wizard].setHealth(amount); + } + + // Other properties and methods... +} +``` + +Now we can show the full example utilizing the virtual machine. + +```java +public static void main(String[] args) { + + var vm = new VirtualMachine( + new Wizard(45, 7, 11, 0, 0), + new Wizard(36, 18, 8, 0, 0)); + + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "GET"))); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(GET_AGILITY)); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(GET_WISDOM)); + vm.execute(InstructionConverterUtil.convertToByteCode(ADD)); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_2)); + vm.execute(InstructionConverterUtil.convertToByteCode(DIVIDE)); + vm.execute(InstructionConverterUtil.convertToByteCode(ADD)); + vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "SET"))); +} +``` + +Here is the console output. + +``` +16:20:10.193 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0] +16:20:10.196 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_HEALTH, Stack contains [0, 45] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_AGILITY, Stack contains [0, 45, 7] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 7, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_WISDOM, Stack contains [0, 45, 7, 11] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 45, 18] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 18, 2] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed DIVIDE, Stack contains [0, 45, 9] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 54] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed SET_HEALTH, Stack contains [] +``` + +Utilizing the Bytecode design pattern in Java can significantly enhance the flexibility and maintainability of your virtual machine-based applications. + +## When to Use the Bytecode Pattern in Java + +Use the Bytecode pattern when you have a lot of behavior you need to define and your game’s implementation language isn’t a good fit because: + +* It’s too low-level, making it tedious or error-prone to program in. +* Iterating on it takes too long due to slow compile times or other tooling issues. +* It has too much trust. If you want to ensure the behavior being defined can’t break the game, you need to sandbox it from the rest of the codebase. + +## Real-World Applications of Bytecode Pattern in Java + +* Java Virtual Machine (JVM) uses bytecode to allow Java programs to run on any device that has JVM installed +* Python compiles its scripts to bytecode which is then interpreted by Python Virtual Machine +* The .NET Framework uses a form of bytecode called Microsoft Intermediate Language (MSIL) + +## Benefits and Trade-offs of Bytecode Pattern + +Benefits: + +* Portability: Programs can run on any platform that has a compatible VM. +* Security: The VM can enforce security checks on the bytecode. +* Performance: JIT compilers can optimize bytecode at runtime, potentially improving performance over interpreted code. + +Trade-offs: + +* Overhead: Running bytecode typically involves more overhead than running native code, potentially affecting performance. +* Complexity: Implementing and maintaining a VM adds complexity to the system. + +## Related Java Design Patterns + +* [Interpreter](https://java-design-patterns.com/patterns/interpreter/) is often used within the implementation of VMs to interpret bytecode instructions +* [Command](https://java-design-patterns.com/patterns/command/): Bytecode instructions can be seen as commands executed by the VM. +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/): VMs may use factory methods to instantiate operations or instructions defined in the bytecode. + +## References and Credits + +* [Game Programming Patterns](https://amzn.to/3K96fOn) +* [Programming Language Pragmatics](https://amzn.to/49Tusnn) +* [Bytecode (Game Programming Patterns)](http://gameprogrammingpatterns.com/bytecode.html) diff --git a/bytecode/etc/bytecode-sequence-diagram.png b/bytecode/etc/bytecode-sequence-diagram.png new file mode 100644 index 000000000000..c863a0e0b5cd Binary files /dev/null and b/bytecode/etc/bytecode-sequence-diagram.png differ diff --git a/bytecode/etc/bytecode.urm.png b/bytecode/etc/bytecode.urm.png new file mode 100644 index 000000000000..51335fa0a4b4 Binary files /dev/null and b/bytecode/etc/bytecode.urm.png differ diff --git a/bytecode/etc/bytecode.urm.puml b/bytecode/etc/bytecode.urm.puml new file mode 100644 index 000000000000..224e909efa15 --- /dev/null +++ b/bytecode/etc/bytecode.urm.puml @@ -0,0 +1,73 @@ +@startuml +package com.iluwatar.bytecode { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + enum Instruction { + + ADD {static} + + DIVIDE {static} + + GET_AGILITY {static} + + GET_HEALTH {static} + + GET_WISDOM {static} + + LITERAL {static} + + PLAY_SOUND {static} + + SET_AGILITY {static} + + SET_HEALTH {static} + + SET_WISDOM {static} + + SPAWN_PARTICLES {static} + - intValue : int + + getInstruction(value : int) : Instruction {static} + + getIntValue() : int + + valueOf(name : String) : Instruction {static} + + values() : Instruction[] {static} + } + class VirtualMachine { + - LOGGER : Logger {static} + - stack : Stack + - wizards : Wizard[] + + VirtualMachine() + + VirtualMachine(wizard1 : Wizard, wizard2 : Wizard) + + execute(bytecode : int[]) + + getAgility(wizard : int) : int + + getHealth(wizard : int) : int + + getStack() : Stack + + getWisdom(wizard : int) : int + + getWizards() : Wizard[] + - randomInt(min : int, max : int) : int + + setAgility(wizard : int, amount : int) + + setHealth(wizard : int, amount : int) + + setWisdom(wizard : int, amount : int) + } + class Wizard { + - LOGGER : Logger {static} + - agility : int + - health : int + - numberOfPlayedSounds : int + - numberOfSpawnedParticles : int + - wisdom : int + + Wizard(health : int, agility : int, wisdom : int, numberOfPlayedSounds : int, numberOfSpawnedParticles : int) + + getAgility() : int + + getHealth() : int + + getNumberOfPlayedSounds() : int + + getNumberOfSpawnedParticles() : int + + getWisdom() : int + + playSound() + + setAgility(agility : int) + + setHealth(health : int) + + setNumberOfPlayedSounds(numberOfPlayedSounds : int) + + setNumberOfSpawnedParticles(numberOfSpawnedParticles : int) + + setWisdom(wisdom : int) + + spawnParticles() + } +} +package com.iluwatar.bytecode.util { + class InstructionConverterUtil { + + InstructionConverterUtil() + + convertToByteCode(instructions : String) : int[] {static} + - isValidInstruction(instruction : String) : boolean {static} + - isValidInt(value : String) : boolean {static} + } +} +@enduml \ No newline at end of file diff --git a/bytecode/pom.xml b/bytecode/pom.xml new file mode 100644 index 000000000000..2fb01fe2f914 --- /dev/null +++ b/bytecode/pom.xml @@ -0,0 +1,70 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + bytecode + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.bytecode.App + + + + + + + + + diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/App.java b/bytecode/src/main/java/com/iluwatar/bytecode/App.java new file mode 100644 index 000000000000..9293b5876ef5 --- /dev/null +++ b/bytecode/src/main/java/com/iluwatar/bytecode/App.java @@ -0,0 +1,76 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bytecode; + +import com.iluwatar.bytecode.util.InstructionConverterUtil; +import lombok.extern.slf4j.Slf4j; + +/** + * The intention of Bytecode pattern is to give behavior the flexibility of data by encoding it as + * instructions for a virtual machine. An instruction set defines the low-level operations that can + * be performed. A series of instructions is encoded as a sequence of bytes. A virtual machine + * executes these instructions one at a time, using a stack for intermediate values. By combining + * instructions, complex high-level behavior can be defined. + * + *

    This pattern should be used when there is a need to define high number of behaviours and + * implementation engine is not a good choice because It is too lowe level Iterating on it takes too + * long due to slow compile times or other tooling issues. It has too much trust. If you want to + * ensure the behavior being defined can’t break the game, you need to sandbox it from the rest of + * the codebase. + */ +@Slf4j +public class App { + + private static final String LITERAL_0 = "LITERAL 0"; + private static final String HEALTH_PATTERN = "%s_HEALTH"; + private static final String GET_AGILITY = "GET_AGILITY"; + private static final String GET_WISDOM = "GET_WISDOM"; + private static final String ADD = "ADD"; + private static final String LITERAL_2 = "LITERAL 2"; + private static final String DIVIDE = "DIVIDE"; + + /** + * Main app method. + * + * @param args command line args + */ + public static void main(String[] args) { + + var vm = new VirtualMachine(new Wizard(45, 7, 11, 0, 0), new Wizard(36, 18, 8, 0, 0)); + + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "GET"))); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(GET_AGILITY)); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(GET_WISDOM)); + vm.execute(InstructionConverterUtil.convertToByteCode(ADD)); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_2)); + vm.execute(InstructionConverterUtil.convertToByteCode(DIVIDE)); + vm.execute(InstructionConverterUtil.convertToByteCode(ADD)); + vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "SET"))); + } +} diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java b/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java new file mode 100644 index 000000000000..25330e73fd78 --- /dev/null +++ b/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java @@ -0,0 +1,62 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bytecode; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** Representation of instructions understandable by virtual machine. */ +@AllArgsConstructor +@Getter +public enum Instruction { + LITERAL(1), // e.g. "LITERAL 0", push 0 to stack + SET_HEALTH(2), // e.g. "SET_HEALTH", pop health and wizard number, call set health + SET_WISDOM(3), // e.g. "SET_WISDOM", pop wisdom and wizard number, call set wisdom + SET_AGILITY(4), // e.g. "SET_AGILITY", pop agility and wizard number, call set agility + PLAY_SOUND(5), // e.g. "PLAY_SOUND", pop value as wizard number, call play sound + SPAWN_PARTICLES(6), // e.g. "SPAWN_PARTICLES", pop value as wizard number, call spawn particles + GET_HEALTH(7), // e.g. "GET_HEALTH", pop value as wizard number, push wizard's health + GET_AGILITY(8), // e.g. "GET_AGILITY", pop value as wizard number, push wizard's agility + GET_WISDOM(9), // e.g. "GET_WISDOM", pop value as wizard number, push wizard's wisdom + ADD(10), // e.g. "ADD", pop 2 values, push their sum + DIVIDE(11); // e.g. "DIVIDE", pop 2 values, push their division + + private final int intValue; + + /** + * Converts integer value to Instruction. + * + * @param value value of instruction + * @return representation of the instruction + */ + public static Instruction getInstruction(int value) { + for (var i = 0; i < Instruction.values().length; i++) { + if (Instruction.values()[i].getIntValue() == value) { + return Instruction.values()[i]; + } + } + throw new IllegalArgumentException("Invalid instruction value"); + } +} diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java b/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java new file mode 100644 index 000000000000..7f835d402f15 --- /dev/null +++ b/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java @@ -0,0 +1,147 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bytecode; + +import java.util.Stack; +import java.util.concurrent.ThreadLocalRandom; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +/** Implementation of virtual machine. */ +@Getter +@Slf4j +public class VirtualMachine { + + private final Stack stack = new Stack<>(); + + private final Wizard[] wizards = new Wizard[2]; + + /** No-args constructor. */ + public VirtualMachine() { + wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), 0, 0); + wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), 0, 0); + } + + /** Constructor taking the wizards as arguments. */ + public VirtualMachine(Wizard wizard1, Wizard wizard2) { + wizards[0] = wizard1; + wizards[1] = wizard2; + } + + /** + * Executes provided bytecode. + * + * @param bytecode to execute + */ + public void execute(int[] bytecode) { + for (var i = 0; i < bytecode.length; i++) { + Instruction instruction = Instruction.getInstruction(bytecode[i]); + switch (instruction) { + case LITERAL -> { // Read the next byte from the bytecode. + int value = bytecode[++i]; + // Push the next value to stack + stack.push(value); + } + case SET_AGILITY -> { + var amount = stack.pop(); + var wizard = stack.pop(); + setAgility(wizard, amount); + } + case SET_WISDOM -> { + var amount = stack.pop(); + var wizard = stack.pop(); + setWisdom(wizard, amount); + } + case SET_HEALTH -> { + var amount = stack.pop(); + var wizard = stack.pop(); + setHealth(wizard, amount); + } + case GET_HEALTH -> { + var wizard = stack.pop(); + stack.push(getHealth(wizard)); + } + case GET_AGILITY -> { + var wizard = stack.pop(); + stack.push(getAgility(wizard)); + } + case GET_WISDOM -> { + var wizard = stack.pop(); + stack.push(getWisdom(wizard)); + } + case ADD -> { + var a = stack.pop(); + var b = stack.pop(); + stack.push(a + b); + } + case DIVIDE -> { + var a = stack.pop(); + var b = stack.pop(); + stack.push(b / a); + } + case PLAY_SOUND -> { + var wizard = stack.pop(); + getWizards()[wizard].playSound(); + } + case SPAWN_PARTICLES -> { + var wizard = stack.pop(); + getWizards()[wizard].spawnParticles(); + } + default -> { + throw new IllegalArgumentException("Invalid instruction value"); + } + } + LOGGER.info("Executed " + instruction.name() + ", Stack contains " + getStack()); + } + } + + public void setHealth(int wizard, int amount) { + wizards[wizard].setHealth(amount); + } + + public void setWisdom(int wizard, int amount) { + wizards[wizard].setWisdom(amount); + } + + public void setAgility(int wizard, int amount) { + wizards[wizard].setAgility(amount); + } + + public int getHealth(int wizard) { + return wizards[wizard].getHealth(); + } + + public int getWisdom(int wizard) { + return wizards[wizard].getWisdom(); + } + + public int getAgility(int wizard) { + return wizards[wizard].getAgility(); + } + + private int randomInt(int min, int max) { + return ThreadLocalRandom.current().nextInt(min, max + 1); + } +} diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java b/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java new file mode 100644 index 000000000000..8b8bfac9f98b --- /dev/null +++ b/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bytecode; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + +/** + * This class represent game objects which properties can be changed by instructions interpreted by + * virtual machine. + */ +@AllArgsConstructor +@Setter +@Getter +@Slf4j +public class Wizard { + + private int health; + private int agility; + private int wisdom; + private int numberOfPlayedSounds; + private int numberOfSpawnedParticles; + + public void playSound() { + LOGGER.info("Playing sound"); + numberOfPlayedSounds++; + } + + public void spawnParticles() { + LOGGER.info("Spawning particles"); + numberOfSpawnedParticles++; + } +} diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java b/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java new file mode 100644 index 000000000000..d45a2aa55787 --- /dev/null +++ b/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bytecode.util; + +import com.iluwatar.bytecode.Instruction; + +/** Utility class used for instruction validation and conversion. */ +public class InstructionConverterUtil { + /** + * Converts instructions represented as String. + * + * @param instructions to convert + * @return array of int representing bytecode + */ + public static int[] convertToByteCode(String instructions) { + if (instructions == null || instructions.trim().length() == 0) { + return new int[0]; + } + + var splitedInstructions = instructions.trim().split(" "); + var bytecode = new int[splitedInstructions.length]; + for (var i = 0; i < splitedInstructions.length; i++) { + if (isValidInstruction(splitedInstructions[i])) { + bytecode[i] = Instruction.valueOf(splitedInstructions[i]).getIntValue(); + } else if (isValidInt(splitedInstructions[i])) { + bytecode[i] = Integer.parseInt(splitedInstructions[i]); + } else { + var errorMessage = "Invalid instruction or number: " + splitedInstructions[i]; + throw new IllegalArgumentException(errorMessage); + } + } + + return bytecode; + } + + private static boolean isValidInstruction(String instruction) { + try { + Instruction.valueOf(instruction); + return true; + } catch (IllegalArgumentException e) { + return false; + } + } + + private static boolean isValidInt(String value) { + try { + Integer.parseInt(value); + return true; + } catch (NumberFormatException e) { + return false; + } + } +} diff --git a/bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java b/bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java new file mode 100644 index 000000000000..72d00eb34fb3 --- /dev/null +++ b/bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bytecode; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application test */ +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java b/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java new file mode 100644 index 000000000000..1d9a5539f51b --- /dev/null +++ b/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java @@ -0,0 +1,154 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bytecode; + +import static com.iluwatar.bytecode.Instruction.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +/** Test for {@link VirtualMachine} */ +class VirtualMachineTest { + + @Test + void testLiteral() { + var bytecode = new int[2]; + bytecode[0] = LITERAL.getIntValue(); + bytecode[1] = 10; + + var vm = new VirtualMachine(); + vm.execute(bytecode); + + assertEquals(1, vm.getStack().size()); + assertEquals(Integer.valueOf(10), vm.getStack().pop()); + } + + @Test + void testSetHealth() { + var wizardNumber = 0; + var bytecode = new int[5]; + bytecode[0] = LITERAL.getIntValue(); + bytecode[1] = wizardNumber; + bytecode[2] = LITERAL.getIntValue(); + bytecode[3] = 50; // health amount + bytecode[4] = SET_HEALTH.getIntValue(); + + var vm = new VirtualMachine(); + vm.execute(bytecode); + + assertEquals(50, vm.getWizards()[wizardNumber].getHealth()); + } + + @Test + void testSetAgility() { + var wizardNumber = 0; + var bytecode = new int[5]; + bytecode[0] = LITERAL.getIntValue(); + bytecode[1] = wizardNumber; + bytecode[2] = LITERAL.getIntValue(); + bytecode[3] = 50; // agility amount + bytecode[4] = SET_AGILITY.getIntValue(); + + var vm = new VirtualMachine(); + vm.execute(bytecode); + + assertEquals(50, vm.getWizards()[wizardNumber].getAgility()); + } + + @Test + void testSetWisdom() { + var wizardNumber = 0; + var bytecode = new int[5]; + bytecode[0] = LITERAL.getIntValue(); + bytecode[1] = wizardNumber; + bytecode[2] = LITERAL.getIntValue(); + bytecode[3] = 50; // wisdom amount + bytecode[4] = SET_WISDOM.getIntValue(); + + var vm = new VirtualMachine(); + vm.execute(bytecode); + + assertEquals(50, vm.getWizards()[wizardNumber].getWisdom()); + } + + @Test + void testGetHealth() { + var wizardNumber = 0; + var bytecode = new int[8]; + bytecode[0] = LITERAL.getIntValue(); + bytecode[1] = wizardNumber; + bytecode[2] = LITERAL.getIntValue(); + bytecode[3] = 50; // health amount + bytecode[4] = SET_HEALTH.getIntValue(); + bytecode[5] = LITERAL.getIntValue(); + bytecode[6] = wizardNumber; + bytecode[7] = GET_HEALTH.getIntValue(); + + var vm = new VirtualMachine(); + vm.execute(bytecode); + + assertEquals(Integer.valueOf(50), vm.getStack().pop()); + } + + @Test + void testPlaySound() { + var wizardNumber = 0; + var bytecode = new int[3]; + bytecode[0] = LITERAL.getIntValue(); + bytecode[1] = wizardNumber; + bytecode[2] = PLAY_SOUND.getIntValue(); + + var vm = new VirtualMachine(); + vm.execute(bytecode); + + assertEquals(0, vm.getStack().size()); + assertEquals(1, vm.getWizards()[0].getNumberOfPlayedSounds()); + } + + @Test + void testSpawnParticles() { + var wizardNumber = 0; + var bytecode = new int[3]; + bytecode[0] = LITERAL.getIntValue(); + bytecode[1] = wizardNumber; + bytecode[2] = SPAWN_PARTICLES.getIntValue(); + + var vm = new VirtualMachine(); + vm.execute(bytecode); + + assertEquals(0, vm.getStack().size()); + assertEquals(1, vm.getWizards()[0].getNumberOfSpawnedParticles()); + } + + @Test + void testInvalidInstruction() { + var bytecode = new int[1]; + bytecode[0] = 999; + var vm = new VirtualMachine(); + + assertThrows(IllegalArgumentException.class, () -> vm.execute(bytecode)); + } +} diff --git a/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java b/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java new file mode 100644 index 000000000000..9dadba1eaf21 --- /dev/null +++ b/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.bytecode.util; + +import com.iluwatar.bytecode.Instruction; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** Test for {@link InstructionConverterUtil} */ +class InstructionConverterUtilTest { + + @Test + void testEmptyInstruction() { + var instruction = ""; + + var bytecode = InstructionConverterUtil.convertToByteCode(instruction); + + Assertions.assertEquals(0, bytecode.length); + } + + @Test + void testInstructions() { + var instructions = + "LITERAL 35 SET_HEALTH SET_WISDOM SET_AGILITY PLAY_SOUND" + + " SPAWN_PARTICLES GET_HEALTH ADD DIVIDE"; + + var bytecode = InstructionConverterUtil.convertToByteCode(instructions); + + Assertions.assertEquals(10, bytecode.length); + Assertions.assertEquals(Instruction.LITERAL.getIntValue(), bytecode[0]); + Assertions.assertEquals(35, bytecode[1]); + Assertions.assertEquals(Instruction.SET_HEALTH.getIntValue(), bytecode[2]); + Assertions.assertEquals(Instruction.SET_WISDOM.getIntValue(), bytecode[3]); + Assertions.assertEquals(Instruction.SET_AGILITY.getIntValue(), bytecode[4]); + Assertions.assertEquals(Instruction.PLAY_SOUND.getIntValue(), bytecode[5]); + Assertions.assertEquals(Instruction.SPAWN_PARTICLES.getIntValue(), bytecode[6]); + Assertions.assertEquals(Instruction.GET_HEALTH.getIntValue(), bytecode[7]); + Assertions.assertEquals(Instruction.ADD.getIntValue(), bytecode[8]); + Assertions.assertEquals(Instruction.DIVIDE.getIntValue(), bytecode[9]); + } +} diff --git a/caching/README.md b/caching/README.md index 7184d51d486d..2e9c3761ef8d 100644 --- a/caching/README.md +++ b/caching/README.md @@ -1,29 +1,478 @@ --- -layout: pattern -title: Caching -folder: caching -permalink: /patterns/caching/ -categories: Other -tags: - - Java - - Difficulty-Intermediate - - Performance +title: "Caching Pattern in Java: Accelerating Data Access Speeds" +shortTitle: Caching +description: "Learn how to optimize performance with the Java Caching Design Pattern. Explore various caching strategies, real-world examples, and implementation techniques for efficient resource management." +category: Performance optimization +language: en +tag: + - Caching + - Data access + - Performance + - Resource management --- -## Intent -To avoid expensive re-acquisition of resources by not releasing -the resources immediately after their use. The resources retain their identity, are kept in some -fast-access storage, and are re-used to avoid having to acquire them again. +## Also known as -![alt text](./etc/caching.png "Caching") +* Cache +* Temporary Storage -## Applicability -Use the Caching pattern(s) when +## Intent of Caching Design Pattern -* Repetitious acquisition, initialization, and release of the same resource causes unnecessary performance overhead. +The Java Caching Design Pattern is crucial for performance optimization and resource management. It involves various caching strategies such as write-through, read-through, and LRU cache to ensure efficient data access. The caching pattern avoids expensive re-acquisition of resources by not releasing them immediately after use. The resources retain their identity, are kept in some fast-access storage, and are re-used to avoid having to acquire them again. -## Credits +## Detailed Explanation of Caching Pattern with Real-World Examples -* [Write-through, write-around, write-back: Cache explained](http://www.computerweekly.com/feature/Write-through-write-around-write-back-Cache-explained) -* [Read-Through, Write-Through, Write-Behind, and Refresh-Ahead Caching](https://docs.oracle.com/cd/E15357_01/coh.360/e15723/cache_rtwtwbra.htm#COHDG5177) -* [Cache-Aside](https://msdn.microsoft.com/en-us/library/dn589799.aspx) +Real-world example + +> A real-world example of the Caching Design Pattern in Java is a library's catalog system. By caching frequently searched book results, the system reduces database load and enhances performance. When patrons frequently search for popular books, the system can cache the results of these searches. Instead of querying the database every time a user searches for a popular book, the system quickly retrieves the results from the cache. This reduces the load on the database and provides faster response times for users, enhancing their overall experience. However, the system must also ensure that the cache is updated when new books are added or existing ones are checked out, to maintain accurate information. + +In plain words + +> Caching pattern keeps frequently needed data in fast-access storage to improve performance. + +Wikipedia says + +> In computing, a cache is a hardware or software component that stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored elsewhere. A cache hit occurs when the requested data can be found in a cache, while a cache miss occurs when it cannot. Cache hits are served by reading data from the cache, which is faster than recomputing a result or reading from a slower data store; thus, the more requests that can be served from the cache, the faster the system performs. + +Flowchart + +![Caching flowchart](./etc/caching-flowchart.png) + +## Programmatic Example of Caching Pattern in Java + +In this programmatic example, we demonstrate different Java caching strategies, including write-through, write-around, and write-behind, using a user account management system. + +A team is working on a website that provides new homes for abandoned cats. People can post their cats on the website after registering, but all the new posts require approval from one of the site moderators. The user accounts of the site moderators contain a specific flag and the data is stored in a MongoDB database. Checking for the moderator flag each time a post is viewed becomes expensive, and it's a good idea to utilize caching here. + +Let's first look at the data layer of our application. The interesting classes are `UserAccount` which is a simple Java object containing the user account details, and `DbManager` interface which handles reading and writing of these objects to/from database. + +```java + +@Data +@AllArgsConstructor +@ToString +@EqualsAndHashCode +public class UserAccount { + private String userId; + private String userName; + private String additionalInfo; +} + +public interface DbManager { + + void connect(); + + void disconnect(); + + UserAccount readFromDb(String userId); + + UserAccount writeToDb(UserAccount userAccount); + + UserAccount updateDb(UserAccount userAccount); + + UserAccount upsertDb(UserAccount userAccount); +} +``` + +In the example, we are demonstrating various different caching policies. The following caching strategies are implemented in Java: Write-through, Write-around, Write-behind, and Cache-aside. Each strategy offers unique benefits for improving performance and reducing load on the database. + +* Write-through writes data to the cache and DB in a single transaction +* Write-around writes data immediately into the DB instead of the cache +* Write-behind writes data into the cache initially whilst the data is only written into the DB when the cache is full +* Cache-aside pushes the responsibility of keeping the data synchronized in both data sources to the application itself +* Read-through strategy is also included in the aforementioned strategies, and it returns data from the cache to the caller if it exists, otherwise queries from DB and stores it into the cache for future use. + +The cache implementation in `LruCache` is a hash table accompanied by a doubly linked-list. The linked-list helps in capturing and maintaining the LRU data in the cache. When data is queried (from the cache), added (to the cache), or updated, the data is moved to the front of the list to depict itself as the most-recently-used data. The LRU data is always at the end of the list. + +```java + +@Slf4j +public class LruCache { + + static class Node { + String userId; + UserAccount userAccount; + Node previous; + Node next; + + public Node(String userId, UserAccount userAccount) { + this.userId = userId; + this.userAccount = userAccount; + } + } + + // Other properties and methods... + + public LruCache(int capacity) { + this.capacity = capacity; + } + + public UserAccount get(String userId) { + if (cache.containsKey(userId)) { + var node = cache.get(userId); + remove(node); + setHead(node); + return node.userAccount; + } + return null; + } + + public void set(String userId, UserAccount userAccount) { + if (cache.containsKey(userId)) { + var old = cache.get(userId); + old.userAccount = userAccount; + remove(old); + setHead(old); + } else { + var newNode = new Node(userId, userAccount); + if (cache.size() >= capacity) { + LOGGER.info("# Cache is FULL! Removing {} from cache...", end.userId); + cache.remove(end.userId); // remove LRU data from cache. + remove(end); + setHead(newNode); + } else { + setHead(newNode); + } + cache.put(userId, newNode); + } + } + + public boolean contains(String userId) { + return cache.containsKey(userId); + } + + public void remove(Node node) { /* ... */ } + + public void setHead(Node node) { /* ... */ } + + public void invalidate(String userId) { /* ... */ } + + public boolean isFull() { /* ... */ } + + public UserAccount getLruData() { /* ... */ } + + public void clear() { /* ... */ } + + public List getCacheDataInListForm() { /* ... */ } + + public void setCapacity(int newCapacity) { /* ... */ } +} +``` + +The next layer we are going to look at is `CacheStore` which implements the different caching strategies. + +```java + +@Slf4j +public class CacheStore { + + private static final int CAPACITY = 3; + private static LruCache cache; + private final DbManager dbManager; + + // Other properties and methods... + + public UserAccount readThrough(final String userId) { + if (cache.contains(userId)) { + LOGGER.info("# Found in Cache!"); + return cache.get(userId); + } + LOGGER.info("# Not found in cache! Go to DB!!"); + UserAccount userAccount = dbManager.readFromDb(userId); + cache.set(userId, userAccount); + return userAccount; + } + + public void writeThrough(final UserAccount userAccount) { + if (cache.contains(userAccount.getUserId())) { + dbManager.updateDb(userAccount); + } else { + dbManager.writeToDb(userAccount); + } + cache.set(userAccount.getUserId(), userAccount); + } + + public void writeAround(final UserAccount userAccount) { + if (cache.contains(userAccount.getUserId())) { + dbManager.updateDb(userAccount); + // Cache data has been updated -- remove older + cache.invalidate(userAccount.getUserId()); + // version from cache. + } else { + dbManager.writeToDb(userAccount); + } + } + + public static void clearCache() { + if (cache != null) { + cache.clear(); + } + } + + public static void flushCache() { + LOGGER.info("# flushCache..."); + Optional.ofNullable(cache) + .map(LruCache::getCacheDataInListForm) + .orElse(List.of()) + .forEach(DbManager::updateDb); + } + + // ... omitted the implementation of other caching strategies ... + +} +``` + +`AppManager` helps to bridge the gap in communication between the main class and the application's back-end. DB connection is initialized through this class. The chosen caching strategy/policy is also initialized here. Before the cache can be used, the size of the cache has to be set. Depending on the chosen caching policy, `AppManager` will call the appropriate function in the `CacheStore` class. + +```java + +@Slf4j +public final class AppManager { + + private static CachingPolicy cachingPolicy; + private final DbManager dbManager; + private final CacheStore cacheStore; + + private AppManager() { + } + + public void initDb() { /* ... */ } + + public static void initCachingPolicy(CachingPolicy policy) { /* ... */ } + + public static void initCacheCapacity(int capacity) { /* ... */ } + + public UserAccount find(final String userId) { + LOGGER.info("Trying to find {} in cache", userId); + if (cachingPolicy == CachingPolicy.THROUGH + || cachingPolicy == CachingPolicy.AROUND) { + return cacheStore.readThrough(userId); + } else if (cachingPolicy == CachingPolicy.BEHIND) { + return cacheStore.readThroughWithWriteBackPolicy(userId); + } else if (cachingPolicy == CachingPolicy.ASIDE) { + return findAside(userId); + } + return null; + } + + public void save(final UserAccount userAccount) { + LOGGER.info("Save record!"); + if (cachingPolicy == CachingPolicy.THROUGH) { + cacheStore.writeThrough(userAccount); + } else if (cachingPolicy == CachingPolicy.AROUND) { + cacheStore.writeAround(userAccount); + } else if (cachingPolicy == CachingPolicy.BEHIND) { + cacheStore.writeBehind(userAccount); + } else if (cachingPolicy == CachingPolicy.ASIDE) { + saveAside(userAccount); + } + } + + public static String printCacheContent() { + return CacheStore.print(); + } + + // Other properties and methods... +} +``` + +Here is what we do in the main class of the application. + +```java + +@Slf4j +public class App { + + public static void main(final String[] args) { + boolean isDbMongo = isDbMongo(args); + if (isDbMongo) { + LOGGER.info("Using the Mongo database engine to run the application."); + } else { + LOGGER.info("Using the 'in Memory' database to run the application."); + } + App app = new App(isDbMongo); + app.useReadAndWriteThroughStrategy(); + String splitLine = "=============================================="; + LOGGER.info(splitLine); + app.useReadThroughAndWriteAroundStrategy(); + LOGGER.info(splitLine); + app.useReadThroughAndWriteBehindStrategy(); + LOGGER.info(splitLine); + app.useCacheAsideStategy(); + LOGGER.info(splitLine); + } + + public void useReadAndWriteThroughStrategy() { + LOGGER.info("# CachingPolicy.THROUGH"); + appManager.initCachingPolicy(CachingPolicy.THROUGH); + + var userAccount1 = new UserAccount("001", "John", "He is a boy."); + + appManager.save(userAccount1); + LOGGER.info(appManager.printCacheContent()); + appManager.find("001"); + appManager.find("001"); + } + + public void useReadThroughAndWriteAroundStrategy() { /* ... */ } + + public void useReadThroughAndWriteBehindStrategy() { /* ... */ } + + public void useCacheAsideStrategy() { /* ... */ } +} +``` + +The program output: + +``` +17:00:56.302 [main] INFO com.iluwatar.caching.App -- Using the 'in Memory' database to run the application. +17:00:56.304 [main] INFO com.iluwatar.caching.App -- # CachingPolicy.THROUGH +17:00:56.305 [main] INFO com.iluwatar.caching.AppManager -- Save record! +17:00:56.308 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +UserAccount(userId=001, userName=John, additionalInfo=He is a boy.) +---- +17:00:56.308 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 001 in cache +17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Found in Cache! +17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 001 in cache +17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Found in Cache! +17:00:56.309 [main] INFO com.iluwatar.caching.App -- ============================================== +17:00:56.309 [main] INFO com.iluwatar.caching.App -- # CachingPolicy.AROUND +17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Save record! +17:00:56.309 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +---- +17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 002 in cache +17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Not found in cache! Go to DB!! +17:00:56.309 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +UserAccount(userId=002, userName=Jane, additionalInfo=She is a girl.) +---- +17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 002 in cache +17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Found in Cache! +17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Save record! +17:00:56.309 [main] INFO com.iluwatar.caching.LruCache -- # 002 has been updated! Removing older version from cache... +17:00:56.309 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +---- +17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 002 in cache +17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Not found in cache! Go to DB!! +17:00:56.309 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +UserAccount(userId=002, userName=Jane G., additionalInfo=She is a girl.) +---- +17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 002 in cache +17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Found in Cache! +17:00:56.309 [main] INFO com.iluwatar.caching.App -- ============================================== +17:00:56.309 [main] INFO com.iluwatar.caching.App -- # CachingPolicy.BEHIND +17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Save record! +17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Save record! +17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Save record! +17:00:56.310 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +UserAccount(userId=005, userName=Isaac, additionalInfo=He is allergic to mustard.) +UserAccount(userId=004, userName=Rita, additionalInfo=She hates cats.) +UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.) +---- +17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 003 in cache +17:00:56.310 [main] INFO com.iluwatar.caching.CacheStore -- # Found in cache! +17:00:56.310 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.) +UserAccount(userId=005, userName=Isaac, additionalInfo=He is allergic to mustard.) +UserAccount(userId=004, userName=Rita, additionalInfo=She hates cats.) +---- +17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Save record! +17:00:56.310 [main] INFO com.iluwatar.caching.CacheStore -- # Cache is FULL! Writing LRU data to DB... +17:00:56.310 [main] INFO com.iluwatar.caching.LruCache -- # Cache is FULL! Removing 004 from cache... +17:00:56.310 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +UserAccount(userId=006, userName=Yasha, additionalInfo=She is an only child.) +UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.) +UserAccount(userId=005, userName=Isaac, additionalInfo=He is allergic to mustard.) +---- +17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 004 in cache +17:00:56.310 [main] INFO com.iluwatar.caching.CacheStore -- # Not found in Cache! +17:00:56.310 [main] INFO com.iluwatar.caching.CacheStore -- # Cache is FULL! Writing LRU data to DB... +17:00:56.310 [main] INFO com.iluwatar.caching.LruCache -- # Cache is FULL! Removing 005 from cache... +17:00:56.310 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +UserAccount(userId=004, userName=Rita, additionalInfo=She hates cats.) +UserAccount(userId=006, userName=Yasha, additionalInfo=She is an only child.) +UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.) +---- +17:00:56.310 [main] INFO com.iluwatar.caching.App -- ============================================== +17:00:56.310 [main] INFO com.iluwatar.caching.App -- # CachingPolicy.ASIDE +17:00:56.310 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +---- +17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Save record! +17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Save record! +17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Save record! +17:00:56.310 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +---- +17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 003 in cache +17:00:56.313 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.) +---- +17:00:56.313 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 004 in cache +17:00:56.313 [main] INFO com.iluwatar.caching.App -- +--CACHE CONTENT-- +UserAccount(userId=004, userName=Rita, additionalInfo=She hates cats.) +UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.) +---- +17:00:56.313 [main] INFO com.iluwatar.caching.App -- ============================================== +17:00:56.314 [Thread-0] INFO com.iluwatar.caching.CacheStore -- # flushCache... +``` + +Implementing the Java Caching Design Pattern using various strategies like LRU cache and write-through caching significantly enhances application performance and scalability. + +## When to Use the Caching Pattern in Java + +Use the Caching pattern when + +* Repetitious acquisition, initialization, and release of the same resource cause unnecessary performance overhead +* In scenarios where the cost of recomputing or re-fetching data is significantly higher than storing and retrieving it from cache +* For read-heavy applications with relatively static data or data that changes infrequently + +## Real-World Applications of Caching Pattern in Java + +* Web page caching to reduce server load and improve response time +* Database query caching to avoid repeated expensive SQL queries +* Caching results of CPU-intensive computations +* Content Delivery Networks (CDNs) for caching static resources like images, CSS, and JavaScript files closer to the end users + +## Benefits and Trade-offs of Caching Pattern + +Benefits: + +* Improved Performance: Significantly reduces data access latency, leading to faster application performance +* Reduced Load: Decreases the load on the underlying data source, which can lead to cost savings and increased longevity of the resource +* Scalability: Enhances the scalability of applications by efficiently handling increases in load without proportional increases in resource utilization + +Trade-Offs: + +* Complexity: Introduces complexity in terms of cache invalidation, consistency, and synchronization +* Resource Utilization: Requires additional memory or storage resources to maintain the cache +* Stale Data: There's a risk of serving outdated data if the cache is not properly invalidated or updated when the underlying data changes + +## Related Java Design Patterns + +* [Proxy](https://java-design-patterns.com/patterns/proxy/): Caching can be implemented using the Proxy pattern, where the proxy object intercepts requests and returns cached data if available +* [Observer](https://java-design-patterns.com/patterns/observer/): Can be used to notify the cache when the underlying data changes, so that it can be updated or invalidated accordingly +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to add caching behavior to an existing object without modifying its code +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Different caching strategies can be implemented using the Strategy pattern, allowing the application to switch between them at runtime + +## References and Credits + +* [Effective Java](https://amzn.to/4cGk2Jz) +* [High Performance Browser Networking](https://amzn.to/3TiNNY4) +* [Java EE 8 High Performance](https://amzn.to/44T8vmH) +* [Java Performance: In-Depth Advice for Tuning and Programming Java 8, 11, and Beyond](https://amzn.to/3yyD58W) +* [Java Performance: The Definitive Guide: Getting the Most Out of Your Code](https://amzn.to/3Wu5neF) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3PMAHRZ) +* [Scalable Internet Architectures](https://amzn.to/48V3ni9) +* [Write-through, write-around, write-back: Cache explained (ComputerWeekly)](http://www.computerweekly.com/feature/Write-through-write-around-write-back-Cache-explained) +* [Cache-Aside Pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/cache-aside) diff --git a/caching/docker-compose.yml b/caching/docker-compose.yml new file mode 100644 index 000000000000..9643d91cf3b7 --- /dev/null +++ b/caching/docker-compose.yml @@ -0,0 +1,36 @@ +# +# This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). +# +# The MIT License +# Copyright © 2014-2022 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. +# + +version: '3.7' +services: + mongodb_container: + image: mongo:latest + environment: + MONGO_INITDB_ROOT_USERNAME: root + MONGO_INITDB_ROOT_PASSWORD: rootpassword + ports: + - '27017:27017' + volumes: + - ./mongo-data/:/data/db diff --git a/caching/etc/caching-flowchart.png b/caching/etc/caching-flowchart.png new file mode 100644 index 000000000000..8068392cd9bd Binary files /dev/null and b/caching/etc/caching-flowchart.png differ diff --git a/caching/etc/caching.png b/caching/etc/caching.png index b6ed703ab8b7..5be2dc0ea7f8 100644 Binary files a/caching/etc/caching.png and b/caching/etc/caching.png differ diff --git a/caching/etc/caching.urm.puml b/caching/etc/caching.urm.puml new file mode 100644 index 000000000000..f6f2e4732005 --- /dev/null +++ b/caching/etc/caching.urm.puml @@ -0,0 +1,119 @@ +@startuml +package com.iluwatar.caching.constants { + class CachingConstants { + + ADD_INFO : String {static} + + USER_ACCOUNT : String {static} + + USER_ID : String {static} + + USER_NAME : String {static} + + CachingConstants() + } +} +package com.iluwatar.caching { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + + useCacheAsideStrategy() + + useReadAndWriteThroughStrategy() + + useReadThroughAndWriteAroundStrategy() + + useReadThroughAndWriteBehindStrategy() + } + class AppManager { + - cachingPolicy : CachingPolicy {static} + - AppManager() + + find(userId : String) : UserAccount {static} + - findAside(userId : String) : UserAccount {static} + + initCacheCapacity(capacity : int) {static} + + initCachingPolicy(policy : CachingPolicy) {static} + + initDb(useMongoDb : boolean) {static} + + printCacheContent() : String {static} + + save(userAccount : UserAccount) {static} + - saveAside(userAccount : UserAccount) {static} + } + class CacheStore { + - LOGGER : Logger {static} + - cache : LruCache {static} + - CacheStore() + + clearCache() {static} + + flushCache() {static} + + get(userId : String) : UserAccount {static} + + initCapacity(capacity : int) {static} + + invalidate(userId : String) {static} + + print() : String {static} + + readThrough(userId : String) : UserAccount {static} + + readThroughWithWriteBackPolicy(userId : String) : UserAccount {static} + + set(userId : String, userAccount : UserAccount) {static} + + writeAround(userAccount : UserAccount) {static} + + writeBehind(userAccount : UserAccount) {static} + + writeThrough(userAccount : UserAccount) {static} + } + enum CachingPolicy { + + AROUND {static} + + ASIDE {static} + + BEHIND {static} + + THROUGH {static} + - policy : String + + getPolicy() : String + + valueOf(name : String) : CachingPolicy {static} + + values() : CachingPolicy[] {static} + } + class DbManager { + - db : MongoDatabase {static} + - mongoClient : MongoClient {static} + - useMongoDB : boolean {static} + - virtualDB : Map {static} + - DbManager() + + connect() {static} + + createVirtualDb() {static} + + readFromDb(userId : String) : UserAccount {static} + + updateDb(userAccount : UserAccount) {static} + + upsertDb(userAccount : UserAccount) {static} + + writeToDb(userAccount : UserAccount) {static} + } + class LruCache { + - LOGGER : Logger {static} + ~ cache : Map + ~ capacity : int + ~ end : Node + ~ head : Node + + LruCache(capacity : int) + + clear() + + contains(userId : String) : boolean + + get(userId : String) : UserAccount + + getCacheDataInListForm() : List + + getLruData() : UserAccount + + invalidate(userId : String) + + isFull() : boolean + + remove(node : Node) + + set(userId : String, userAccount : UserAccount) + + setCapacity(newCapacity : int) + + setHead(node : Node) + } + ~class Node { + ~ next : Node + ~ previous : Node + ~ userAccount : UserAccount + ~ userId : String + + Node(this$0 : String, userId : UserAccount) + } + class UserAccount { + - additionalInfo : String + - userId : String + - userName : String + + UserAccount(userId : String, userName : String, additionalInfo : String) + + getAdditionalInfo() : String + + getUserId() : String + + getUserName() : String + + setAdditionalInfo(additionalInfo : String) + + setUserId(userId : String) + + setUserName(userName : String) + + toString() : String + } +} +Node --+ LruCache +LruCache --> "-head" Node +Node --> "-previous" Node +AppManager --> "-cachingPolicy" CachingPolicy +Node --> "-userAccount" UserAccount +CacheStore --> "-cache" LruCache +@enduml diff --git a/caching/pom.xml b/caching/pom.xml index 57f8f01197b9..3ffce74af493 100644 --- a/caching/pom.xml +++ b/caching/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT caching - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,19 +48,17 @@ test - org.mongodb - mongodb-driver - 3.0.4 + org.mockito + mockito-core + test org.mongodb - mongodb-driver-core - 3.0.4 + bson org.mongodb - bson - 3.0.4 + mongodb-driver-legacy AppManager --> CacheStore/LRUCache/CachingPolicy --> DBManager} - *

    + * + *

    {@literal App --> AppManager --> CacheStore/LRUCache/CachingPolicy --> DBManager} + * + *

    There are 2 ways to launch the application. - to use "in Memory" database. - to use the + * MongoDb as a database + * + *

    To run the application with "in Memory" database, just launch it without parameters Example: + * 'java -jar app.jar' + * + *

    To run the application with MongoDb you need to be installed the MongoDb in your system, or to + * launch it in the docker container. You may launch docker container from the root of current + * module with command: 'docker-compose up' Then you can start the application with parameter + * --mongo Example: 'java -jar app.jar --mongo' * * @see CacheStore * @see LruCache * @see CachingPolicy - * */ +@Slf4j public class App { + /** Constant parameter name to use mongoDB. */ + private static final String USE_MONGO_DB = "--mongo"; - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** Application manager. */ + private final AppManager appManager; + /** + * Constructor of current App. + * + * @param isMongo boolean + */ + public App(final boolean isMongo) { + DbManager dbManager = DbManagerFactory.initDb(isMongo); + appManager = new AppManager(dbManager); + appManager.initDb(); + } /** - * Program entry point + * Program entry point. * * @param args command line args */ - public static void main(String[] args) { - AppManager.initDb(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests - // and the App class to avoid Maven compilation errors. Set flag to - // true to run the tests with MongoDB (provided that MongoDB is - // installed and socket connection is open). - AppManager.initCacheCapacity(3); - App app = new App(); + public static void main(final String[] args) { + // VirtualDB (instead of MongoDB) was used in running the JUnit tests + // and the App class to avoid Maven compilation errors. Set flag to + // true to run the tests with MongoDB (provided that MongoDB is + // installed and socket connection is open). + boolean isDbMongo = isDbMongo(args); + if (isDbMongo) { + LOGGER.info("Using the Mongo database engine to run the application."); + } else { + LOGGER.info("Using the 'in Memory' database to run the application."); + } + App app = new App(isDbMongo); app.useReadAndWriteThroughStrategy(); + String splitLine = "=============================================="; + LOGGER.info(splitLine); app.useReadThroughAndWriteAroundStrategy(); + LOGGER.info(splitLine); app.useReadThroughAndWriteBehindStrategy(); - app.useCacheAsideStategy(); + LOGGER.info(splitLine); + app.useCacheAsideStrategy(); + LOGGER.info(splitLine); } /** - * Read-through and write-through + * Check the input parameters. if + * + * @param args input params + * @return true if there is "--mongo" parameter in arguments */ + private static boolean isDbMongo(final String[] args) { + for (String arg : args) { + if (arg.equals(USE_MONGO_DB)) { + return true; + } + } + return false; + } + + /** Read-through and write-through. */ public void useReadAndWriteThroughStrategy() { LOGGER.info("# CachingPolicy.THROUGH"); - AppManager.initCachingPolicy(CachingPolicy.THROUGH); + appManager.initCachingPolicy(CachingPolicy.THROUGH); - UserAccount userAccount1 = new UserAccount("001", "John", "He is a boy."); + var userAccount1 = new UserAccount("001", "John", "He is a boy."); - AppManager.save(userAccount1); - LOGGER.info(AppManager.printCacheContent()); - AppManager.find("001"); - AppManager.find("001"); + appManager.save(userAccount1); + LOGGER.info(appManager.printCacheContent()); + appManager.find("001"); + appManager.find("001"); } - /** - * Read-through and write-around - */ + /** Read-through and write-around. */ public void useReadThroughAndWriteAroundStrategy() { LOGGER.info("# CachingPolicy.AROUND"); - AppManager.initCachingPolicy(CachingPolicy.AROUND); + appManager.initCachingPolicy(CachingPolicy.AROUND); - UserAccount userAccount2 = new UserAccount("002", "Jane", "She is a girl."); + var userAccount2 = new UserAccount("002", "Jane", "She is a girl."); - AppManager.save(userAccount2); - LOGGER.info(AppManager.printCacheContent()); - AppManager.find("002"); - LOGGER.info(AppManager.printCacheContent()); - userAccount2 = AppManager.find("002"); + appManager.save(userAccount2); + LOGGER.info(appManager.printCacheContent()); + appManager.find("002"); + LOGGER.info(appManager.printCacheContent()); + userAccount2 = appManager.find("002"); userAccount2.setUserName("Jane G."); - AppManager.save(userAccount2); - LOGGER.info(AppManager.printCacheContent()); - AppManager.find("002"); - LOGGER.info(AppManager.printCacheContent()); - AppManager.find("002"); + appManager.save(userAccount2); + LOGGER.info(appManager.printCacheContent()); + appManager.find("002"); + LOGGER.info(appManager.printCacheContent()); + appManager.find("002"); } - /** - * Read-through and write-behind - */ + /** Read-through and write-behind. */ public void useReadThroughAndWriteBehindStrategy() { LOGGER.info("# CachingPolicy.BEHIND"); - AppManager.initCachingPolicy(CachingPolicy.BEHIND); - - UserAccount userAccount3 = new UserAccount("003", "Adam", "He likes food."); - UserAccount userAccount4 = new UserAccount("004", "Rita", "She hates cats."); - UserAccount userAccount5 = new UserAccount("005", "Isaac", "He is allergic to mustard."); - - AppManager.save(userAccount3); - AppManager.save(userAccount4); - AppManager.save(userAccount5); - LOGGER.info(AppManager.printCacheContent()); - AppManager.find("003"); - LOGGER.info(AppManager.printCacheContent()); + appManager.initCachingPolicy(CachingPolicy.BEHIND); + + var userAccount3 = new UserAccount("003", "Adam", "He likes food."); + var userAccount4 = new UserAccount("004", "Rita", "She hates cats."); + var userAccount5 = new UserAccount("005", "Isaac", "He is allergic to mustard."); + + appManager.save(userAccount3); + appManager.save(userAccount4); + appManager.save(userAccount5); + LOGGER.info(appManager.printCacheContent()); + appManager.find("003"); + LOGGER.info(appManager.printCacheContent()); UserAccount userAccount6 = new UserAccount("006", "Yasha", "She is an only child."); - AppManager.save(userAccount6); - LOGGER.info(AppManager.printCacheContent()); - AppManager.find("004"); - LOGGER.info(AppManager.printCacheContent()); + appManager.save(userAccount6); + LOGGER.info(appManager.printCacheContent()); + appManager.find("004"); + LOGGER.info(appManager.printCacheContent()); } - /** - * Cache-Aside - */ - public void useCacheAsideStategy() { + /** Cache-Aside. */ + public void useCacheAsideStrategy() { LOGGER.info("# CachingPolicy.ASIDE"); - AppManager.initCachingPolicy(CachingPolicy.ASIDE); - LOGGER.info(AppManager.printCacheContent()); - - UserAccount userAccount3 = new UserAccount("003", "Adam", "He likes food."); - UserAccount userAccount4 = new UserAccount("004", "Rita", "She hates cats."); - UserAccount userAccount5 = new UserAccount("005", "Isaac", "He is allergic to mustard."); - AppManager.save(userAccount3); - AppManager.save(userAccount4); - AppManager.save(userAccount5); - - LOGGER.info(AppManager.printCacheContent()); - AppManager.find("003"); - LOGGER.info(AppManager.printCacheContent()); - AppManager.find("004"); - LOGGER.info(AppManager.printCacheContent()); + appManager.initCachingPolicy(CachingPolicy.ASIDE); + LOGGER.info(appManager.printCacheContent()); + + var userAccount3 = new UserAccount("003", "Adam", "He likes food."); + var userAccount4 = new UserAccount("004", "Rita", "She hates cats."); + var userAccount5 = new UserAccount("005", "Isaac", "He is allergic to mustard."); + appManager.save(userAccount3); + appManager.save(userAccount4); + appManager.save(userAccount5); + + LOGGER.info(appManager.printCacheContent()); + appManager.find("003"); + LOGGER.info(appManager.printCacheContent()); + appManager.find("004"); + LOGGER.info(appManager.printCacheContent()); } } diff --git a/caching/src/main/java/com/iluwatar/caching/AppManager.java b/caching/src/main/java/com/iluwatar/caching/AppManager.java index 2acc1accd17d..c1d21fea33fe 100644 --- a/caching/src/main/java/com/iluwatar/caching/AppManager.java +++ b/caching/src/main/java/com/iluwatar/caching/AppManager.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,65 +24,72 @@ */ package com.iluwatar.caching; -import java.text.ParseException; +import com.iluwatar.caching.database.DbManager; +import java.util.Optional; +import lombok.extern.slf4j.Slf4j; /** - * * AppManager helps to bridge the gap in communication between the main class and the application's * back-end. DB connection is initialized through this class. The chosen caching strategy/policy is * also initialized here. Before the cache can be used, the size of the cache has to be set. * Depending on the chosen caching policy, AppManager will call the appropriate function in the * CacheStore class. - * */ -public final class AppManager { +@Slf4j +public class AppManager { + /** Caching Policy. */ + private CachingPolicy cachingPolicy; - private static CachingPolicy cachingPolicy; + /** Database Manager. */ + private final DbManager dbManager; - private AppManager() { - } + /** Cache Store. */ + private final CacheStore cacheStore; /** + * Constructor. * + * @param newDbManager database manager + */ + public AppManager(final DbManager newDbManager) { + this.dbManager = newDbManager; + this.cacheStore = new CacheStore(newDbManager); + } + + /** * Developer/Tester is able to choose whether the application should use MongoDB as its underlying * data storage or a simple Java data structure to (temporarily) store the data/objects during * runtime. */ - public static void initDb(boolean useMongoDb) { - if (useMongoDb) { - try { - DbManager.connect(); - } catch (ParseException e) { - e.printStackTrace(); - } - } else { - DbManager.createVirtualDb(); - } + public void initDb() { + dbManager.connect(); } /** - * Initialize caching policy + * Initialize caching policy. + * + * @param policy is a {@link CachingPolicy} */ - public static void initCachingPolicy(CachingPolicy policy) { + public void initCachingPolicy(final CachingPolicy policy) { cachingPolicy = policy; if (cachingPolicy == CachingPolicy.BEHIND) { - Runtime.getRuntime().addShutdownHook(new Thread(CacheStore::flushCache)); + Runtime.getRuntime().addShutdownHook(new Thread(cacheStore::flushCache)); } - CacheStore.clearCache(); - } - - public static void initCacheCapacity(int capacity) { - CacheStore.initCapacity(capacity); + cacheStore.clearCache(); } /** - * Find user account + * Find user account. + * + * @param userId String + * @return {@link UserAccount} */ - public static UserAccount find(String userId) { + public UserAccount find(final String userId) { + LOGGER.info("Trying to find {} in cache", userId); if (cachingPolicy == CachingPolicy.THROUGH || cachingPolicy == CachingPolicy.AROUND) { - return CacheStore.readThrough(userId); + return cacheStore.readThrough(userId); } else if (cachingPolicy == CachingPolicy.BEHIND) { - return CacheStore.readThroughWithWriteBackPolicy(userId); + return cacheStore.readThroughWithWriteBackPolicy(userId); } else if (cachingPolicy == CachingPolicy.ASIDE) { return findAside(userId); } @@ -88,46 +97,56 @@ public static UserAccount find(String userId) { } /** - * Save user account + * Save user account. + * + * @param userAccount {@link UserAccount} */ - public static void save(UserAccount userAccount) { + public void save(final UserAccount userAccount) { + LOGGER.info("Save record!"); if (cachingPolicy == CachingPolicy.THROUGH) { - CacheStore.writeThrough(userAccount); + cacheStore.writeThrough(userAccount); } else if (cachingPolicy == CachingPolicy.AROUND) { - CacheStore.writeAround(userAccount); + cacheStore.writeAround(userAccount); } else if (cachingPolicy == CachingPolicy.BEHIND) { - CacheStore.writeBehind(userAccount); + cacheStore.writeBehind(userAccount); } else if (cachingPolicy == CachingPolicy.ASIDE) { saveAside(userAccount); } } - public static String printCacheContent() { - return CacheStore.print(); + /** + * Returns String. + * + * @return String + */ + public String printCacheContent() { + return cacheStore.print(); } /** - * Cache-Aside save user account helper + * Cache-Aside save user account helper. + * + * @param userAccount {@link UserAccount} */ - private static void saveAside(UserAccount userAccount) { - DbManager.updateDb(userAccount); - CacheStore.invalidate(userAccount.getUserId()); + private void saveAside(final UserAccount userAccount) { + dbManager.updateDb(userAccount); + cacheStore.invalidate(userAccount.getUserId()); } /** - * Cache-Aside find user account helper + * Cache-Aside find user account helper. + * + * @param userId String + * @return {@link UserAccount} */ - private static UserAccount findAside(String userId) { - UserAccount userAccount = CacheStore.get(userId); - if (userAccount != null) { - return userAccount; - } - - userAccount = DbManager.readFromDb(userId); - if (userAccount != null) { - CacheStore.set(userId, userAccount); - } - - return userAccount; + private UserAccount findAside(final String userId) { + return Optional.ofNullable(cacheStore.get(userId)) + .or( + () -> { + Optional userAccount = Optional.ofNullable(dbManager.readFromDb(userId)); + userAccount.ifPresent(account -> cacheStore.set(userId, account)); + return userAccount; + }) + .orElse(null); } } diff --git a/caching/src/main/java/com/iluwatar/caching/CacheStore.java b/caching/src/main/java/com/iluwatar/caching/CacheStore.java index f22a731b4880..b26c52b22159 100644 --- a/caching/src/main/java/com/iluwatar/caching/CacheStore.java +++ b/caching/src/main/java/com/iluwatar/caching/CacheStore.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,29 +24,40 @@ */ package com.iluwatar.caching; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import com.iluwatar.caching.database.DbManager; import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; -/** - * - * The caching strategies are implemented in this class. - * - */ +/** The caching strategies are implemented in this class. */ +@Slf4j public class CacheStore { + /** Cache capacity. */ + private static final int CAPACITY = 3; - private static final Logger LOGGER = LoggerFactory.getLogger(CacheStore.class); + /** Lru cache see {@link LruCache}. */ + private LruCache cache; - static LruCache cache; + /** DbManager. */ + private final DbManager dbManager; - private CacheStore() { + /** + * Cache Store. + * + * @param dataBaseManager {@link DbManager} + */ + public CacheStore(final DbManager dataBaseManager) { + this.dbManager = dataBaseManager; + initCapacity(CAPACITY); } /** - * Init cache capacity + * Init cache capacity. + * + * @param capacity int */ - public static void initCapacity(int capacity) { + public void initCapacity(final int capacity) { if (cache == null) { cache = new LruCache(capacity); } else { @@ -53,130 +66,145 @@ public static void initCapacity(int capacity) { } /** - * Get user account using read-through cache + * Get user account using read-through cache. + * + * @param userId {@link String} + * @return {@link UserAccount} */ - public static UserAccount readThrough(String userId) { + public UserAccount readThrough(final String userId) { if (cache.contains(userId)) { - LOGGER.info("# Cache Hit!"); + LOGGER.info("# Found in Cache!"); return cache.get(userId); } - LOGGER.info("# Cache Miss!"); - UserAccount userAccount = DbManager.readFromDb(userId); + LOGGER.info("# Not found in cache! Go to DB!!"); + UserAccount userAccount = dbManager.readFromDb(userId); cache.set(userId, userAccount); return userAccount; } /** - * Get user account using write-through cache + * Get user account using write-through cache. + * + * @param userAccount {@link UserAccount} */ - public static void writeThrough(UserAccount userAccount) { + public void writeThrough(final UserAccount userAccount) { if (cache.contains(userAccount.getUserId())) { - DbManager.updateDb(userAccount); + dbManager.updateDb(userAccount); } else { - DbManager.writeToDb(userAccount); + dbManager.writeToDb(userAccount); } cache.set(userAccount.getUserId(), userAccount); } /** - * Get user account using write-around cache + * Get user account using write-around cache. + * + * @param userAccount {@link UserAccount} */ - public static void writeAround(UserAccount userAccount) { + public void writeAround(final UserAccount userAccount) { if (cache.contains(userAccount.getUserId())) { - DbManager.updateDb(userAccount); - cache.invalidate(userAccount.getUserId()); // Cache data has been updated -- remove older - // version from cache. + dbManager.updateDb(userAccount); + // Cache data has been updated -- remove older + cache.invalidate(userAccount.getUserId()); + // version from cache. } else { - DbManager.writeToDb(userAccount); + dbManager.writeToDb(userAccount); } } /** - * Get user account using read-through cache with write-back policy + * Get user account using read-through cache with write-back policy. + * + * @param userId {@link String} + * @return {@link UserAccount} */ - public static UserAccount readThroughWithWriteBackPolicy(String userId) { + public UserAccount readThroughWithWriteBackPolicy(final String userId) { if (cache.contains(userId)) { - LOGGER.info("# Cache Hit!"); + LOGGER.info("# Found in cache!"); return cache.get(userId); } - LOGGER.info("# Cache Miss!"); - UserAccount userAccount = DbManager.readFromDb(userId); + LOGGER.info("# Not found in Cache!"); + UserAccount userAccount = dbManager.readFromDb(userId); if (cache.isFull()) { LOGGER.info("# Cache is FULL! Writing LRU data to DB..."); UserAccount toBeWrittenToDb = cache.getLruData(); - DbManager.upsertDb(toBeWrittenToDb); + dbManager.upsertDb(toBeWrittenToDb); } cache.set(userId, userAccount); return userAccount; } /** - * Set user account + * Set user account. + * + * @param userAccount {@link UserAccount} */ - public static void writeBehind(UserAccount userAccount) { + public void writeBehind(final UserAccount userAccount) { if (cache.isFull() && !cache.contains(userAccount.getUserId())) { LOGGER.info("# Cache is FULL! Writing LRU data to DB..."); UserAccount toBeWrittenToDb = cache.getLruData(); - DbManager.upsertDb(toBeWrittenToDb); + dbManager.upsertDb(toBeWrittenToDb); } cache.set(userAccount.getUserId(), userAccount); } - /** - * Clears cache - */ - public static void clearCache() { + /** Clears cache. */ + public void clearCache() { if (cache != null) { cache.clear(); } } - /** - * Writes remaining content in the cache into the DB. - */ - public static void flushCache() { + /** Writes remaining content in the cache into the DB. */ + public void flushCache() { LOGGER.info("# flushCache..."); - if (null == cache) { - return; - } - List listOfUserAccounts = cache.getCacheDataInListForm(); - for (UserAccount userAccount : listOfUserAccounts) { - DbManager.upsertDb(userAccount); - } + Optional.ofNullable(cache) + .map(LruCache::getCacheDataInListForm) + .orElse(List.of()) + .forEach(dbManager::updateDb); + dbManager.disconnect(); } /** - * Print user accounts + * Print user accounts. + * + * @return {@link String} */ - public static String print() { - List listOfUserAccounts = cache.getCacheDataInListForm(); - StringBuilder sb = new StringBuilder(); - sb.append("\n--CACHE CONTENT--\n"); - for (UserAccount userAccount : listOfUserAccounts) { - sb.append(userAccount.toString() + "\n"); - } - sb.append("----\n"); - return sb.toString(); + public String print() { + return Optional.ofNullable(cache) + .map(LruCache::getCacheDataInListForm) + .orElse(List.of()) + .stream() + .map(userAccount -> userAccount.toString() + "\n") + .collect(Collectors.joining("", "\n--CACHE CONTENT--\n", "----")); } /** - * Delegate to backing cache store + * Delegate to backing cache store. + * + * @param userId {@link String} + * @return {@link UserAccount} */ - public static UserAccount get(String userId) { + public UserAccount get(final String userId) { return cache.get(userId); } /** - * Delegate to backing cache store + * Delegate to backing cache store. + * + * @param userId {@link String} + * @param userAccount {@link UserAccount} */ - public static void set(String userId, UserAccount userAccount) { + public void set(final String userId, final UserAccount userAccount) { cache.set(userId, userAccount); } /** - * Delegate to backing cache store + * Delegate to backing cache store. + * + * @param userId {@link String} */ - public static void invalidate(String userId) { + public void invalidate(final String userId) { cache.invalidate(userId); } } diff --git a/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java b/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java index 9f7c92b2eef5..0ec07ced7b8f 100644 --- a/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java +++ b/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,22 @@ */ package com.iluwatar.caching; -/** - * - * Enum class containing the four caching strategies implemented in the pattern. - * - */ -public enum CachingPolicy { - THROUGH("through"), AROUND("around"), BEHIND("behind"), ASIDE("aside"); - - private String policy; +import lombok.AllArgsConstructor; +import lombok.Getter; - private CachingPolicy(String policy) { - this.policy = policy; - } +/** Enum class containing the four caching strategies implemented in the pattern. */ +@AllArgsConstructor +@Getter +public enum CachingPolicy { + /** Through. */ + THROUGH("through"), + /** AROUND. */ + AROUND("around"), + /** BEHIND. */ + BEHIND("behind"), + /** ASIDE. */ + ASIDE("aside"); - public String getPolicy() { - return policy; - } + /** Policy value. */ + private final String policy; } diff --git a/caching/src/main/java/com/iluwatar/caching/DbManager.java b/caching/src/main/java/com/iluwatar/caching/DbManager.java deleted file mode 100644 index 6fccaf43e5ff..000000000000 --- a/caching/src/main/java/com/iluwatar/caching/DbManager.java +++ /dev/null @@ -1,164 +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.caching; - -import java.text.ParseException; -import java.util.HashMap; -import java.util.Map; - -import org.bson.Document; - -import com.mongodb.MongoClient; -import com.mongodb.client.FindIterable; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.UpdateOptions; - -/** - * - *

    DBManager handles the communication with the underlying data store i.e. Database. It contains the - * implemented methods for querying, inserting, and updating data. MongoDB was used as the database - * for the application.

    - * - *

    Developer/Tester is able to choose whether the application should use MongoDB as its underlying - * data storage (connect()) or a simple Java data structure to (temporarily) store the data/objects - * during runtime (createVirtualDB()).

    - * - */ -public final class DbManager { - - private static MongoClient mongoClient; - private static MongoDatabase db; - private static boolean useMongoDB; - - private static Map virtualDB; - - private DbManager() { - } - - /** - * Create DB - */ - public static void createVirtualDb() { - useMongoDB = false; - virtualDB = new HashMap<>(); - } - - /** - * Connect to DB - */ - public static void connect() throws ParseException { - useMongoDB = true; - mongoClient = new MongoClient(); - db = mongoClient.getDatabase("test"); - } - - /** - * Read user account from DB - */ - public static UserAccount readFromDb(String userId) { - if (!useMongoDB) { - if (virtualDB.containsKey(userId)) { - return virtualDB.get(userId); - } - return null; - } - if (db == null) { - try { - connect(); - } catch (ParseException e) { - e.printStackTrace(); - } - } - FindIterable iterable = - db.getCollection("user_accounts").find(new Document("userID", userId)); - if (iterable == null) { - return null; - } - Document doc = iterable.first(); - return new UserAccount(userId, doc.getString("userName"), doc.getString("additionalInfo")); - } - - /** - * Write user account to DB - */ - public static void writeToDb(UserAccount userAccount) { - if (!useMongoDB) { - virtualDB.put(userAccount.getUserId(), userAccount); - return; - } - if (db == null) { - try { - connect(); - } catch (ParseException e) { - e.printStackTrace(); - } - } - db.getCollection("user_accounts").insertOne( - new Document("userID", userAccount.getUserId()).append("userName", - userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo())); - } - - /** - * Update DB - */ - public static void updateDb(UserAccount userAccount) { - if (!useMongoDB) { - virtualDB.put(userAccount.getUserId(), userAccount); - return; - } - if (db == null) { - try { - connect(); - } catch (ParseException e) { - e.printStackTrace(); - } - } - db.getCollection("user_accounts").updateOne( - new Document("userID", userAccount.getUserId()), - new Document("$set", new Document("userName", userAccount.getUserName()).append( - "additionalInfo", userAccount.getAdditionalInfo()))); - } - - /** - * - * Insert data into DB if it does not exist. Else, update it. - */ - public static void upsertDb(UserAccount userAccount) { - if (!useMongoDB) { - virtualDB.put(userAccount.getUserId(), userAccount); - return; - } - if (db == null) { - try { - connect(); - } catch (ParseException e) { - e.printStackTrace(); - } - } - db.getCollection("user_accounts").updateOne( - new Document("userID", userAccount.getUserId()), - new Document("$set", new Document("userID", userAccount.getUserId()).append("userName", - userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo())), - new UpdateOptions().upsert(true)); - } -} diff --git a/caching/src/main/java/com/iluwatar/caching/LruCache.java b/caching/src/main/java/com/iluwatar/caching/LruCache.java index fb9127bdc8b8..9c9107de6f88 100644 --- a/caching/src/main/java/com/iluwatar/caching/LruCache.java +++ b/caching/src/main/java/com/iluwatar/caching/LruCache.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,54 +24,77 @@ */ package com.iluwatar.caching; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import lombok.extern.slf4j.Slf4j; /** - * * Data structure/implementation of the application's cache. The data structure consists of a hash * table attached with a doubly linked-list. The linked-list helps in capturing and maintaining the * LRU data in the cache. When a data is queried (from the cache), added (to the cache), or updated, * the data is moved to the front of the list to depict itself as the most-recently-used data. The * LRU data is always at the end of the list. - * */ +@Slf4j public class LruCache { + /** Static class Node. */ + static class Node { + /** user id. */ + private final String userId; + + /** User Account. */ + private UserAccount userAccount; + + /** previous. */ + private Node previous; + + /** next. */ + private Node next; + + /** + * Node definition. + * + * @param id String + * @param account {@link UserAccount} + */ + Node(final String id, final UserAccount account) { + this.userId = id; + this.userAccount = account; + } + } - private static final Logger LOGGER = LoggerFactory.getLogger(LruCache.class); + /** Capacity of Cache. */ + private int capacity; - class Node { - String userId; - UserAccount userAccount; - Node previous; - Node next; + /** Cache {@link HashMap}. */ + private Map cache = new HashMap<>(); - public Node(String userId, UserAccount userAccount) { - this.userId = userId; - this.userAccount = userAccount; - } - } + /** Head. */ + private Node head; - int capacity; - Map cache = new HashMap<>(); - Node head; - Node end; + /** End. */ + private Node end; - public LruCache(int capacity) { - this.capacity = capacity; + /** + * Constructor. + * + * @param cap Integer. + */ + public LruCache(final int cap) { + this.capacity = cap; } /** - * Get user account + * Get user account. + * + * @param userId String + * @return {@link UserAccount} */ - public UserAccount get(String userId) { + public UserAccount get(final String userId) { if (cache.containsKey(userId)) { - Node node = cache.get(userId); + var node = cache.get(userId); remove(node); setHead(node); return node.userAccount; @@ -79,8 +104,10 @@ public UserAccount get(String userId) { /** * Remove node from linked list. + * + * @param node {@link Node} */ - public void remove(Node node) { + public void remove(final Node node) { if (node.previous != null) { node.previous.next = node.next; } else { @@ -95,8 +122,10 @@ public void remove(Node node) { /** * Move node to the front of the list. + * + * @param node {@link Node} */ - public void setHead(Node node) { + public void setHead(final Node node) { node.next = head; node.previous = null; if (head != null) { @@ -109,16 +138,19 @@ public void setHead(Node node) { } /** - * Set user account + * Set user account. + * + * @param userAccount {@link UserAccount} + * @param userId {@link String} */ - public void set(String userId, UserAccount userAccount) { + public void set(final String userId, final UserAccount userAccount) { if (cache.containsKey(userId)) { - Node old = cache.get(userId); + var old = cache.get(userId); old.userAccount = userAccount; remove(old); setHead(old); } else { - Node newNode = new Node(userId, userAccount); + var newNode = new Node(userId, userAccount); if (cache.size() >= capacity) { LOGGER.info("# Cache is FULL! Removing {} from cache...", end.userId); cache.remove(end.userId); // remove LRU data from cache. @@ -131,32 +163,48 @@ public void set(String userId, UserAccount userAccount) { } } - public boolean contains(String userId) { + /** + * Check if Cache contains the userId. + * + * @param userId {@link String} + * @return boolean + */ + public boolean contains(final String userId) { return cache.containsKey(userId); } /** - * Invalidate cache for user + * Invalidate cache for user. + * + * @param userId {@link String} */ - public void invalidate(String userId) { - Node toBeRemoved = cache.remove(userId); + public void invalidate(final String userId) { + var toBeRemoved = cache.remove(userId); if (toBeRemoved != null) { - LOGGER.info("# {} has been updated! Removing older version from cache...", userId); + LOGGER.info("# {} has been updated! " + "Removing older version from cache...", userId); remove(toBeRemoved); } } + /** + * Check if the cache is full. + * + * @return boolean + */ public boolean isFull() { return cache.size() >= capacity; } + /** + * Get LRU data. + * + * @return {@link UserAccount} + */ public UserAccount getLruData() { return end.userAccount; } - /** - * Clear cache - */ + /** Clear cache. */ public void clear() { head = null; end = null; @@ -165,10 +213,12 @@ public void clear() { /** * Returns cache data in list form. + * + * @return {@link List} */ public List getCacheDataInListForm() { - List listOfCacheData = new ArrayList<>(); - Node temp = head; + var listOfCacheData = new ArrayList(); + var temp = head; while (temp != null) { listOfCacheData.add(temp.userAccount); temp = temp.next; @@ -177,12 +227,16 @@ public List getCacheDataInListForm() { } /** - * Set cache capacity + * Set cache capacity. + * + * @param newCapacity int */ - public void setCapacity(int newCapacity) { + public void setCapacity(final int newCapacity) { if (capacity > newCapacity) { - clear(); // Behavior can be modified to accommodate for decrease in cache size. For now, we'll - // just clear the cache. + // Behavior can be modified to accommodate + // for decrease in cache size. For now, we'll + clear(); + // just clear the cache. } else { this.capacity = newCapacity; } diff --git a/caching/src/main/java/com/iluwatar/caching/UserAccount.java b/caching/src/main/java/com/iluwatar/caching/UserAccount.java index 769eef6f6d2f..561c942ac781 100644 --- a/caching/src/main/java/com/iluwatar/caching/UserAccount.java +++ b/caching/src/main/java/com/iluwatar/caching/UserAccount.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,49 +24,23 @@ */ package com.iluwatar.caching; -/** - * Entity class (stored in cache and DB) used in the application. - */ +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; + +/** Entity class (stored in cache and DB) used in the application. */ +@Data +@AllArgsConstructor +@ToString +@EqualsAndHashCode public class UserAccount { + /** User Id. */ private String userId; - private String userName; - private String additionalInfo; - - /** - * Constructor - */ - public UserAccount(String userId, String userName, String additionalInfo) { - this.userId = userId; - this.userName = userName; - this.additionalInfo = additionalInfo; - } - - public String getUserId() { - return userId; - } - public void setUserId(String userId) { - this.userId = userId; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getAdditionalInfo() { - return additionalInfo; - } - - public void setAdditionalInfo(String additionalInfo) { - this.additionalInfo = additionalInfo; - } + /** User Name. */ + private String userName; - @Override - public String toString() { - return userId + ", " + userName + ", " + additionalInfo; - } + /** Additional Info. */ + private String additionalInfo; } diff --git a/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java b/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java new file mode 100644 index 000000000000..5e8fc415df4c --- /dev/null +++ b/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.caching.constants; + +/** Constant class for defining constants. */ +public final class CachingConstants { + /** User Account. */ + public static final String USER_ACCOUNT = "user_accounts"; + + /** User ID. */ + public static final String USER_ID = "userID"; + + /** User Name. */ + public static final String USER_NAME = "userName"; + + /** Additional Info. */ + public static final String ADD_INFO = "additionalInfo"; + + /** Constructor. */ + private CachingConstants() {} +} diff --git a/caching/src/main/java/com/iluwatar/caching/constants/package-info.java b/caching/src/main/java/com/iluwatar/caching/constants/package-info.java new file mode 100644 index 000000000000..b94476cbabeb --- /dev/null +++ b/caching/src/main/java/com/iluwatar/caching/constants/package-info.java @@ -0,0 +1,26 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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. + */ +/** Constants. */ +package com.iluwatar.caching.constants; diff --git a/caching/src/main/java/com/iluwatar/caching/database/DbManager.java b/caching/src/main/java/com/iluwatar/caching/database/DbManager.java new file mode 100644 index 000000000000..14b98a66b52b --- /dev/null +++ b/caching/src/main/java/com/iluwatar/caching/database/DbManager.java @@ -0,0 +1,72 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.caching.database; + +import com.iluwatar.caching.UserAccount; + +/** + * DBManager handles the communication with the underlying data store i.e. Database. It contains the + * implemented methods for querying, inserting, and updating data. MongoDB was used as the database + * for the application. + */ +public interface DbManager { + /** Connect to DB. */ + void connect(); + + /** Disconnect from DB. */ + void disconnect(); + + /** + * Read from DB. + * + * @param userId {@link String} + * @return {@link UserAccount} + */ + UserAccount readFromDb(String userId); + + /** + * Write to DB. + * + * @param userAccount {@link UserAccount} + * @return {@link UserAccount} + */ + UserAccount writeToDb(UserAccount userAccount); + + /** + * Update record. + * + * @param userAccount {@link UserAccount} + * @return {@link UserAccount} + */ + UserAccount updateDb(UserAccount userAccount); + + /** + * Update record or Insert if not exists. + * + * @param userAccount {@link UserAccount} + * @return {@link UserAccount} + */ + UserAccount upsertDb(UserAccount userAccount); +} diff --git a/caching/src/main/java/com/iluwatar/caching/database/DbManagerFactory.java b/caching/src/main/java/com/iluwatar/caching/database/DbManagerFactory.java new file mode 100644 index 000000000000..92031b7c95b0 --- /dev/null +++ b/caching/src/main/java/com/iluwatar/caching/database/DbManagerFactory.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.caching.database; + +/** Creates the database connection according the input parameter. */ +public final class DbManagerFactory { + /** Private constructor. */ + private DbManagerFactory() {} + + /** + * Init database. + * + * @param isMongo boolean + * @return {@link DbManager} + */ + public static DbManager initDb(final boolean isMongo) { + if (isMongo) { + return new MongoDb(); + } + return new VirtualDb(); + } +} diff --git a/caching/src/main/java/com/iluwatar/caching/database/MongoDb.java b/caching/src/main/java/com/iluwatar/caching/database/MongoDb.java new file mode 100644 index 000000000000..e47eef55cd8c --- /dev/null +++ b/caching/src/main/java/com/iluwatar/caching/database/MongoDb.java @@ -0,0 +1,148 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.caching.database; + +import static com.iluwatar.caching.constants.CachingConstants.ADD_INFO; +import static com.iluwatar.caching.constants.CachingConstants.USER_ACCOUNT; +import static com.iluwatar.caching.constants.CachingConstants.USER_ID; +import static com.iluwatar.caching.constants.CachingConstants.USER_NAME; + +import com.iluwatar.caching.UserAccount; +import com.iluwatar.caching.constants.CachingConstants; +import com.mongodb.MongoClient; +import com.mongodb.MongoClientOptions; +import com.mongodb.MongoCredential; +import com.mongodb.ServerAddress; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.UpdateOptions; +import lombok.extern.slf4j.Slf4j; +import org.bson.Document; + +/** Implementation of DatabaseManager. implements base methods to work with MongoDb. */ +@Slf4j +public class MongoDb implements DbManager { + private static final String DATABASE_NAME = "admin"; + private static final String MONGO_USER = "root"; + private static final String MONGO_PASSWORD = "rootpassword"; + private MongoClient client; + private MongoDatabase db; + + void setDb(MongoDatabase db) { + this.db = db; + } + + /** Connect to Db. Check th connection */ + @Override + public void connect() { + MongoCredential mongoCredential = + MongoCredential.createCredential(MONGO_USER, DATABASE_NAME, MONGO_PASSWORD.toCharArray()); + MongoClientOptions options = MongoClientOptions.builder().build(); + client = new MongoClient(new ServerAddress(), mongoCredential, options); + db = client.getDatabase(DATABASE_NAME); + } + + @Override + public void disconnect() { + client.close(); + } + + /** + * Read data from DB. + * + * @param userId {@link String} + * @return {@link UserAccount} + */ + @Override + public UserAccount readFromDb(final String userId) { + var iterable = + db.getCollection(CachingConstants.USER_ACCOUNT).find(new Document(USER_ID, userId)); + if (iterable.first() == null) { + return null; + } + Document doc = iterable.first(); + if (doc != null) { + String userName = doc.getString(USER_NAME); + String appInfo = doc.getString(ADD_INFO); + return new UserAccount(userId, userName, appInfo); + } else { + return null; + } + } + + /** + * Write data to DB. + * + * @param userAccount {@link UserAccount} + * @return {@link UserAccount} + */ + @Override + public UserAccount writeToDb(final UserAccount userAccount) { + db.getCollection(USER_ACCOUNT) + .insertOne( + new Document(USER_ID, userAccount.getUserId()) + .append(USER_NAME, userAccount.getUserName()) + .append(ADD_INFO, userAccount.getAdditionalInfo())); + return userAccount; + } + + /** + * Update DB. + * + * @param userAccount {@link UserAccount} + * @return {@link UserAccount} + */ + @Override + public UserAccount updateDb(final UserAccount userAccount) { + Document id = new Document(USER_ID, userAccount.getUserId()); + Document dataSet = + new Document(USER_NAME, userAccount.getUserName()) + .append(ADD_INFO, userAccount.getAdditionalInfo()); + db.getCollection(CachingConstants.USER_ACCOUNT).updateOne(id, new Document("$set", dataSet)); + return userAccount; + } + + /** + * Update data if exists. + * + * @param userAccount {@link UserAccount} + * @return {@link UserAccount} + */ + @Override + public UserAccount upsertDb(final UserAccount userAccount) { + String userId = userAccount.getUserId(); + String userName = userAccount.getUserName(); + String additionalInfo = userAccount.getAdditionalInfo(); + db.getCollection(CachingConstants.USER_ACCOUNT) + .updateOne( + new Document(USER_ID, userId), + new Document( + "$set", + new Document(USER_ID, userId) + .append(USER_NAME, userName) + .append(ADD_INFO, additionalInfo)), + new UpdateOptions().upsert(true)); + return userAccount; + } +} diff --git a/caching/src/main/java/com/iluwatar/caching/database/VirtualDb.java b/caching/src/main/java/com/iluwatar/caching/database/VirtualDb.java new file mode 100644 index 000000000000..6040ca174a21 --- /dev/null +++ b/caching/src/main/java/com/iluwatar/caching/database/VirtualDb.java @@ -0,0 +1,94 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.caching.database; + +import com.iluwatar.caching.UserAccount; +import java.util.HashMap; +import java.util.Map; + +/** Implementation of DatabaseManager. implements base methods to work with hashMap as database. */ +public class VirtualDb implements DbManager { + /** Virtual DataBase. */ + private Map db; + + /** Creates new HashMap. */ + @Override + public void connect() { + db = new HashMap<>(); + } + + @Override + public void disconnect() { + db = null; + } + + /** + * Read from Db. + * + * @param userId {@link String} + * @return {@link UserAccount} + */ + @Override + public UserAccount readFromDb(final String userId) { + if (db.containsKey(userId)) { + return db.get(userId); + } + return null; + } + + /** + * Write to DB. + * + * @param userAccount {@link UserAccount} + * @return {@link UserAccount} + */ + @Override + public UserAccount writeToDb(final UserAccount userAccount) { + db.put(userAccount.getUserId(), userAccount); + return userAccount; + } + + /** + * Update reecord in DB. + * + * @param userAccount {@link UserAccount} + * @return {@link UserAccount} + */ + @Override + public UserAccount updateDb(final UserAccount userAccount) { + return writeToDb(userAccount); + } + + /** + * Update. + * + * @param userAccount {@link UserAccount} + * @return {@link UserAccount} + */ + @Override + public UserAccount upsertDb(final UserAccount userAccount) { + return updateDb(userAccount); + } +} diff --git a/caching/src/main/java/com/iluwatar/caching/database/package-info.java b/caching/src/main/java/com/iluwatar/caching/database/package-info.java new file mode 100644 index 000000000000..631cb4c584cd --- /dev/null +++ b/caching/src/main/java/com/iluwatar/caching/database/package-info.java @@ -0,0 +1,26 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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. + */ +/** Database classes. */ +package com.iluwatar.caching.database; diff --git a/caching/src/main/java/com/iluwatar/caching/package-info.java b/caching/src/main/java/com/iluwatar/caching/package-info.java new file mode 100644 index 000000000000..e7a60b3e95b5 --- /dev/null +++ b/caching/src/main/java/com/iluwatar/caching/package-info.java @@ -0,0 +1,25 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.caching; diff --git a/caching/src/test/java/com/iluwatar/caching/AppTest.java b/caching/src/test/java/com/iluwatar/caching/AppTest.java index 32935bf24a67..35e01edbc37e 100644 --- a/caching/src/test/java/com/iluwatar/caching/AppTest.java +++ b/caching/src/test/java/com/iluwatar/caching/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,20 @@ */ package com.iluwatar.caching; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import java.io.IOException; +import org.junit.jupiter.api.Test; -/** - * Tests that Caching example runs without errors. - */ -public class AppTest { +/** Tests that Caching example runs without errors. */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/caching/src/test/java/com/iluwatar/caching/CachingTest.java b/caching/src/test/java/com/iluwatar/caching/CachingTest.java index 0a7e8aed381c..d17cff5bd2ef 100644 --- a/caching/src/test/java/com/iluwatar/caching/CachingTest.java +++ b/caching/src/test/java/com/iluwatar/caching/CachingTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,47 +24,46 @@ */ package com.iluwatar.caching; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class CachingTest { - App app; +/** Application test */ +class CachingTest { + private App app; - /** - * Setup of application test includes: initializing DB connection and cache size/capacity. - */ + /** Setup of application test includes: initializing DB connection and cache size/capacity. */ @BeforeEach - public void setUp() { - AppManager.initDb(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests - // to avoid Maven compilation errors. Set flag to true to run the - // tests with MongoDB (provided that MongoDB is installed and socket - // connection is open). - AppManager.initCacheCapacity(3); - app = new App(); + void setUp() { + // VirtualDB (instead of MongoDB) was used in running the JUnit tests + // to avoid Maven compilation errors. Set flag to true to run the + // tests with MongoDB (provided that MongoDB is installed and socket + // connection is open). + app = new App(false); } @Test - public void testReadAndWriteThroughStrategy() { + void testReadAndWriteThroughStrategy() { + assertNotNull(app); app.useReadAndWriteThroughStrategy(); } @Test - public void testReadThroughAndWriteAroundStrategy() { + void testReadThroughAndWriteAroundStrategy() { + assertNotNull(app); app.useReadThroughAndWriteAroundStrategy(); } @Test - public void testReadThroughAndWriteBehindStrategy() { + void testReadThroughAndWriteBehindStrategy() { + assertNotNull(app); app.useReadThroughAndWriteBehindStrategy(); } @Test - public void testCacheAsideStrategy() { - app.useCacheAsideStategy(); + void testCacheAsideStrategy() { + assertNotNull(app); + app.useCacheAsideStrategy(); } } diff --git a/caching/src/test/java/com/iluwatar/caching/database/MongoDbTest.java b/caching/src/test/java/com/iluwatar/caching/database/MongoDbTest.java new file mode 100644 index 000000000000..87cc1ed6f587 --- /dev/null +++ b/caching/src/test/java/com/iluwatar/caching/database/MongoDbTest.java @@ -0,0 +1,110 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.caching.database; + +import static com.iluwatar.caching.constants.CachingConstants.ADD_INFO; +import static com.iluwatar.caching.constants.CachingConstants.USER_ID; +import static com.iluwatar.caching.constants.CachingConstants.USER_NAME; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + +import com.iluwatar.caching.UserAccount; +import com.iluwatar.caching.constants.CachingConstants; +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import org.bson.Document; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; + +class MongoDbTest { + private static final String ID = "123"; + private static final String NAME = "Some user"; + private static final String ADDITIONAL_INFO = "Some app Info"; + + @Mock MongoDatabase db; + private MongoDb mongoDb = new MongoDb(); + + private UserAccount userAccount; + + @BeforeEach + void init() { + db = mock(MongoDatabase.class); + mongoDb.setDb(db); + userAccount = new UserAccount(ID, NAME, ADDITIONAL_INFO); + } + + @Test + void connect() { + assertDoesNotThrow(() -> mongoDb.connect()); + } + + @Test + void readFromDb() { + Document document = + new Document(USER_ID, ID).append(USER_NAME, NAME).append(ADD_INFO, ADDITIONAL_INFO); + MongoCollection mongoCollection = mock(MongoCollection.class); + when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); + + FindIterable findIterable = mock(FindIterable.class); + when(mongoCollection.find(any(Document.class))).thenReturn(findIterable); + + when(findIterable.first()).thenReturn(document); + + assertEquals(mongoDb.readFromDb(ID), userAccount); + } + + @Test + void writeToDb() { + MongoCollection mongoCollection = mock(MongoCollection.class); + when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); + assertDoesNotThrow( + () -> { + mongoDb.writeToDb(userAccount); + }); + } + + @Test + void updateDb() { + MongoCollection mongoCollection = mock(MongoCollection.class); + when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); + assertDoesNotThrow( + () -> { + mongoDb.updateDb(userAccount); + }); + } + + @Test + void upsertDb() { + MongoCollection mongoCollection = mock(MongoCollection.class); + when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); + assertDoesNotThrow( + () -> { + mongoDb.upsertDb(userAccount); + }); + } +} diff --git a/callback/README.md b/callback/README.md index a408fd5e0bd5..923132ac5b6a 100644 --- a/callback/README.md +++ b/callback/README.md @@ -1,28 +1,135 @@ --- -layout: pattern -title: Callback -folder: callback -permalink: /patterns/callback/ -categories: Other -tags: - - Java - - Difficulty-Beginner - - Functional - - Idiom +title: "Callback Pattern in Java: Mastering Asynchronous Communication" +shortTitle: Callback +description: "Learn about the Java Callback Design Pattern, including its intent, usage scenarios, benefits, trade-offs, and real-world examples. Understand how to implement and effectively use callbacks in your Java applications." +category: Functional +language: en +tag: + - Asynchronous + - Decoupling + - Idiom + - Reactive --- -## Intent -Callback is a piece of executable code that is passed as an -argument to other code, which is expected to call back (execute) the argument -at some convenient time. +## Also known as -![alt text](./etc/callback.png "Callback") +* Call-After +* Event-Subscription +* Listener + +## Intent of Callback Design Pattern + +The Java Callback Design Pattern is a piece of executable code passed as an argument to other code, which is expected to call back (execute) the argument at a convenient time. + +## Detailed Explanation of Callback Pattern with Real-World Examples + +Real-world example + +> A real-world analogy for the Callback design pattern can be found in the restaurant industry. Imagine a situation where you place an order at a busy restaurant. Instead of waiting at the counter for your food to be ready, you provide the cashier with your phone number. Once your order is prepared, the kitchen staff calls or sends a text message to notify you that your meal is ready for pickup. +> +> In this analogy, placing your order is analogous to initiating an asynchronous task. Providing your phone number is akin to passing a callback function. The kitchen preparing your order represents the asynchronous processing, and the notification you receive is the callback being executed, allowing you to retrieve your meal without having to wait idly. This separation of task initiation and task completion is the essence of the Callback design pattern. + +In plain words + +> Callback is a method passed to an executor which will be called at a defined moment. + +Wikipedia says + +> In computer programming, a callback, also known as a "call-after" function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time. + +Sequence diagram + +![Callback sequence diagram](./etc/callback-sequence-diagram.png) + +## Programmatic Example of Callback Pattern in Java + +We need to be notified after the executing task has finished. We pass a callback method for the executor and wait for it to call back on us. + +`Callback` is a simple interface with single method. + +```java +public interface Callback { + + void call(); +} +``` + +Next we define `Task` that will execute the callback after the task execution has finished. + +```java +public abstract class Task { + + final void executeWith(Callback callback) { + execute(); + Optional.ofNullable(callback).ifPresent(Callback::call); + } + + public abstract void execute(); +} + +@Slf4j +public final class SimpleTask extends Task { + + @Override + public void execute() { + LOGGER.info("Perform some important activity and after call the callback method."); + } +} +``` + +Finally, here's how we execute a task and receive a callback when it's finished. + +```java +public static void main(final String[] args) { + var task = new SimpleTask(); + task.executeWith(() -> LOGGER.info("I'm done now.")); +} +``` + +Program output: + +``` +17:12:11.680 [main] INFO com.iluwatar.callback.SimpleTask -- Perform some important activity and after call the callback method. +17:12:11.682 [main] INFO com.iluwatar.callback.App -- I'm done now. +``` + +## When to Use the Callback Pattern in Java -## Applicability Use the Callback pattern when -* when some arbitrary synchronous or asynchronous action must be performed after execution of some defined activity. +* Asynchronous event handling in GUI applications or event-driven systems +* Implementing notification mechanisms where certain events need to trigger actions in other components. +* Decoupling modules or components that need to interact without having a direct dependency on each other + +## Real-World Applications of Callback Pattern in Java + +* GUI frameworks often use callbacks for event handling, such as user interactions (clicks, key presses) +* Node.js heavily relies on callbacks for non-blocking I/O operations +* Frameworks that deal with asynchronous operations, like Promises in JavaScript, use callbacks to handle the resolution or rejection of asynchronous tasks +* [CyclicBarrier](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) constructor can accept a callback that will be triggered every time a barrier is tripped. + +## Benefits and Trade-offs of Callback Pattern + +Benefits: + +* Decouples the execution logic of an operation from the signaling or notification logic, enhancing modularity and reusability +* Facilitates asynchronous processing, improving the responsiveness and scalability of applications +* Enables a reactive programming model where components can react to events as they occur + +Trade-offs: + +* Callback hell or pyramid of doom: Deeply nested callbacks can lead to code that is hard to read and maintain +* Inversion of control can lead to harder-to-follow code flow, making debugging more challenging +* Potential issues with error handling, especially in languages or environments where exceptions are used, as errors might need to be propagated through callbacks + +## Related Java Design Patterns + +* [Command](https://java-design-patterns.com/patterns/command/): Callbacks can be implemented as Command objects in scenarios where more flexibility or statefulness is required in the callback operation +* [Observer](https://java-design-patterns.com/patterns/observer/): Callbacks can be seen as a more dynamic and lightweight form of the Observer pattern, with the ability to subscribe and unsubscribe callback functions dynamically +* [Promise](https://java-design-patterns.com/patterns/promise/): In some languages or frameworks, Promises or Futures can be used to handle asynchronous operations more cleanly, often using callbacks for success or failure cases -## Real world examples +## References and Credits -* [CyclicBarrier](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) constructor can accept callback that will be triggered every time when barrier is tripped. +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Java Concurrency in Practice](https://amzn.to/4aRMruW) diff --git a/callback/etc/callback-sequence-diagram.png b/callback/etc/callback-sequence-diagram.png new file mode 100644 index 000000000000..5922734d8fd2 Binary files /dev/null and b/callback/etc/callback-sequence-diagram.png differ diff --git a/callback/etc/callback.png b/callback/etc/callback.png index a81745871a64..7b499f79fcaa 100644 Binary files a/callback/etc/callback.png and b/callback/etc/callback.png differ diff --git a/callback/etc/callback.urm.puml b/callback/etc/callback.urm.puml new file mode 100644 index 000000000000..2d213eda800c --- /dev/null +++ b/callback/etc/callback.urm.puml @@ -0,0 +1,23 @@ +@startuml +package com.iluwatar.callback { + class App { + - LOGGER : Logger {static} + - App() + + main(args : String[]) {static} + } + interface Callback { + + call() {abstract} + } + class SimpleTask { + - LOGGER : Logger {static} + + SimpleTask() + + execute() + } + abstract class Task { + + Task() + + execute() {abstract} + ~ executeWith(callback : Callback) + } +} +SimpleTask --|> Task +@enduml \ No newline at end of file diff --git a/callback/pom.xml b/callback/pom.xml index 387c8a6674ae..772615f457f9 100644 --- a/callback/pom.xml +++ b/callback/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT callback - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.callback.App + + + + + + + + diff --git a/callback/src/main/java/com/iluwatar/callback/App.java b/callback/src/main/java/com/iluwatar/callback/App.java index 278975db9bae..7b630f8da247 100644 --- a/callback/src/main/java/com/iluwatar/callback/App.java +++ b/callback/src/main/java/com/iluwatar/callback/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,31 +24,21 @@ */ package com.iluwatar.callback; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * * Callback pattern is more native for functional languages where functions are treated as * first-class citizens. Prior to Java 8 callbacks can be simulated using simple (alike command) * interfaces. - * */ -public class App { +@Slf4j +public final class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + private App() {} - /** - * Program entry point - */ - public static void main(String[] args) { - Task task = new SimpleTask(); - Callback callback = new Callback() { - @Override - public void call() { - LOGGER.info("I'm done now."); - } - }; - task.executeWith(callback); + /** Program entry point. */ + public static void main(final String[] args) { + var task = new SimpleTask(); + task.executeWith(() -> LOGGER.info("I'm done now.")); } } diff --git a/callback/src/main/java/com/iluwatar/callback/Callback.java b/callback/src/main/java/com/iluwatar/callback/Callback.java index 670d446c324e..7b75b5c71077 100644 --- a/callback/src/main/java/com/iluwatar/callback/Callback.java +++ b/callback/src/main/java/com/iluwatar/callback/Callback.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.callback; -/** - * - * Callback interface - * - */ +/** Callback interface. */ public interface Callback { void call(); diff --git a/callback/src/main/java/com/iluwatar/callback/LambdasApp.java b/callback/src/main/java/com/iluwatar/callback/LambdasApp.java deleted file mode 100644 index 57ab816f1445..000000000000 --- a/callback/src/main/java/com/iluwatar/callback/LambdasApp.java +++ /dev/null @@ -1,46 +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.callback; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * This example generates the exact same output as {@link App} however the callback has been - * defined as a Lambdas expression. - * - */ -public class LambdasApp { - - private static final Logger LOGGER = LoggerFactory.getLogger(LambdasApp.class); - - /** - * Program entry point - */ - public static void main(String[] args) { - Task task = new SimpleTask(); - Callback c = () -> LOGGER.info("I'm done now."); - task.executeWith(c); - } -} diff --git a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java index 091699442b35..bbf060a6fc9f 100644 --- a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java +++ b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,11 @@ */ package com.iluwatar.callback; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Implementation of task that need to be executed - * - */ -public class SimpleTask extends Task { +import lombok.extern.slf4j.Slf4j; - private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTask.class); +/** Implementation of task that need to be executed. */ +@Slf4j +public final class SimpleTask extends Task { @Override public void execute() { diff --git a/callback/src/main/java/com/iluwatar/callback/Task.java b/callback/src/main/java/com/iluwatar/callback/Task.java index 9e4ebf35fbab..d69697454dff 100644 --- a/callback/src/main/java/com/iluwatar/callback/Task.java +++ b/callback/src/main/java/com/iluwatar/callback/Task.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,15 @@ */ package com.iluwatar.callback; -/** - * - * Template-method class for callback hook execution - * - */ +import java.util.Optional; + +/** Template-method class for callback hook execution. */ public abstract class Task { - /** - * Execute with callback - */ - public final void executeWith(Callback callback) { + /** Execute with callback. */ + final void executeWith(Callback callback) { execute(); - if (callback != null) { - callback.call(); - } + Optional.ofNullable(callback).ifPresent(Callback::call); } public abstract void execute(); diff --git a/callback/src/main/java/com/iluwatar/callback/package-info.java b/callback/src/main/java/com/iluwatar/callback/package-info.java new file mode 100644 index 000000000000..496c71e073db --- /dev/null +++ b/callback/src/main/java/com/iluwatar/callback/package-info.java @@ -0,0 +1,25 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.callback; diff --git a/callback/src/test/java/com/iluwatar/callback/AppTest.java b/callback/src/test/java/com/iluwatar/callback/AppTest.java index bb9b698d410e..ca0e93072f0f 100644 --- a/callback/src/test/java/com/iluwatar/callback/AppTest.java +++ b/callback/src/test/java/com/iluwatar/callback/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,22 @@ */ package com.iluwatar.callback; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -import java.io.IOException; +/** Tests that Callback example runs without errors. */ +class AppTest { -/** - * Tests that Callback example runs without errors. - */ -public class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/callback/src/test/java/com/iluwatar/callback/CallbackTest.java b/callback/src/test/java/com/iluwatar/callback/CallbackTest.java index 7a14b0a4a600..99939d491f4e 100644 --- a/callback/src/test/java/com/iluwatar/callback/CallbackTest.java +++ b/callback/src/test/java/com/iluwatar/callback/CallbackTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,58 +24,34 @@ */ package com.iluwatar.callback; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + /** * Add a field as a counter. Every time the callback method is called increment this field. Unit * test checks that the field is being incremented. * - * Could be done with mock objects as well where the call method call is verified. + *

    Could be done with mock objects as well where the call method call is verified. */ -public class CallbackTest { +class CallbackTest { private Integer callingCount = 0; @Test - public void test() { - Callback callback = new Callback() { - @Override - public void call() { - callingCount++; - } - }; - - Task task = new SimpleTask(); - - assertEquals(new Integer(0), callingCount, "Initial calling count of 0"); - - task.executeWith(callback); - - assertEquals(new Integer(1), callingCount, "Callback called once"); - - task.executeWith(callback); - - assertEquals(new Integer(2), callingCount, "Callback called twice"); - - } - - @Test - public void testWithLambdasExample() { + void test() { Callback callback = () -> callingCount++; - Task task = new SimpleTask(); + var task = new SimpleTask(); - assertEquals(new Integer(0), callingCount, "Initial calling count of 0"); + assertEquals(Integer.valueOf(0), callingCount, "Initial calling count of 0"); task.executeWith(callback); - assertEquals(new Integer(1), callingCount, "Callback called once"); + assertEquals(Integer.valueOf(1), callingCount, "Callback called once"); task.executeWith(callback); - assertEquals(new Integer(2), callingCount, "Callback called twice"); - + assertEquals(Integer.valueOf(2), callingCount, "Callback called twice"); } } diff --git a/chain-of-responsibility/README.md b/chain-of-responsibility/README.md new file mode 100644 index 000000000000..454147dcd5d3 --- /dev/null +++ b/chain-of-responsibility/README.md @@ -0,0 +1,209 @@ +--- +title: "Chain of Responsibility Pattern in Java: Building Robust Request Handling Mechanisms" +shortTitle: Chain of Responsibility +description: "Learn the Chain of Responsibility design pattern in Java with real-world examples, code snippets, and class diagrams. Enhance your coding skills with our detailed explanations." +category: Behavioral +language: en +tag: + - Decoupling + - Event-driven + - Gang of Four + - Messaging +--- + +## Also known as + +* Chain of Command +* Chain of Objects +* Responsibility Chain + +## Intent of Chain of Responsibility Design Pattern + +The Chain of Responsibility pattern in Java is a behavioral design pattern that decouples the sender of a request from its receivers by giving more than one object a chance to handle the request. The receiving objects are chained and the request is passed along the chain until an object handles it. + +## Detailed Explanation of Chain of Responsibility Pattern with Real-World Examples + +Real-world example + +> A real-world example of the Chain of Responsibility pattern in Java is a technical support call center. When implementing this Java design pattern, each level of support represents a handler in the chain. When a customer calls in with an issue, the call is first received by a front-line support representative. If the issue is simple, the representative handles it directly. If the issue is more complex, the representative forwards the call to a second-level support technician. This process continues, with the call being escalated through multiple levels of support until it reaches a specialist who can resolve the problem. Each level of support represents a handler in the chain, and the call is passed along the chain until it finds an appropriate handler, thereby decoupling the request from the specific receiver. + +In plain words + +> It helps to build a chain of objects. A request enters from one end and keeps going from an object to another until it finds a suitable handler. + +Wikipedia says + +> In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. + +Flowchart + +![Chain of Responsibility flowchart](./etc/chain-of-responsibility-flowchart.png) + +## Programmatic Example of Chain of Responsibility Pattern + +In this Java example, the Orc King gives orders which are processed by a chain of command representing the Chain of Responsibility pattern. Learn how to implement this design pattern in Java with the following code snippet. + +The Orc King gives loud orders to his army. The closest one to react is the commander, then an officer, and then a soldier. The commander, officer, and soldier form a chain of responsibility. + +First, we have the `Request` class: + +```java +@Getter +public class Request { + + private final RequestType requestType; + private final String requestDescription; + private boolean handled; + + public Request(final RequestType requestType, final String requestDescription) { + this.requestType = Objects.requireNonNull(requestType); + this.requestDescription = Objects.requireNonNull(requestDescription); + } + + public void markHandled() { + this.handled = true; + } + + @Override + public String toString() { + return getRequestDescription(); + } +} + +public enum RequestType { + DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX +} +``` + +Next, we show the `RequestHandler` hierarchy. + +```java +public interface RequestHandler { + + boolean canHandleRequest(Request req); + + int getPriority(); + + void handle(Request req); + + String name(); +} + +@Slf4j +public class OrcCommander implements RequestHandler { + @Override + public boolean canHandleRequest(Request req) { + return req.getRequestType() == RequestType.DEFEND_CASTLE; + } + + @Override + public int getPriority() { + return 2; + } + + @Override + public void handle(Request req) { + req.markHandled(); + LOGGER.info("{} handling request \"{}\"", name(), req); + } + + @Override + public String name() { + return "Orc commander"; + } +} + +// OrcOfficer and OrcSoldier are defined similarly as OrcCommander ... + +``` + +The `OrcKing` gives the orders and forms the chain. + +```java +public class OrcKing { + + private List handlers; + + public OrcKing() { + buildChain(); + } + + private void buildChain() { + handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier()); + } + + public void makeRequest(Request req) { + handlers + .stream() + .sorted(Comparator.comparing(RequestHandler::getPriority)) + .filter(handler -> handler.canHandleRequest(req)) + .findFirst() + .ifPresent(handler -> handler.handle(req)); + } +} +``` + +The chain of responsibility in action. + +```java + public static void main(String[] args) { + + var king = new OrcKing(); + king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); + king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); + king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); +} +``` + +The console output: + +``` +Orc commander handling request "defend castle" +Orc officer handling request "torture prisoner" +Orc soldier handling request "collect tax" +``` + +## When to Use the Chain of Responsibility Pattern in Java + +Use Chain of Responsibility when + +* More than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically. +* You want to issue a request to one of several objects without specifying the receiver explicitly. +* The set of objects that can handle a request should be specified dynamically. + +## Real-World Applications of Chain of Responsibility Pattern in Java + +* Event bubbling in GUI frameworks where an event might be handled at multiple levels of a UI component hierarchy +* Middleware frameworks where a request passes through a chain of processing objects +* Logging frameworks where messages can be passed through a series of loggers, each possibly handling them differently +* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) +* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) +* [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-) + +## Benefits and Trade-offs of Chain of Responsibility Pattern + +Benefits: + +* Reduced coupling. The sender of a request does not need to know the concrete handler that will process the request. +* Increased flexibility in assigning responsibilities to objects. You can add or change responsibilities for handling a request by changing the members and order of the chain. +* Allows you to set a default handler if no concrete handler can handle the request. + +Trade-Offs: + +* It can be challenging to debug and understand the flow, especially if the chain is long and complex. +* The request might end up unhandled if the chain doesn't include a catch-all handler. +* Performance concerns might arise due to potentially going through several handlers before finding the right one, or not finding it at all. + +## Related Java Design Patterns + +* [Command](https://java-design-patterns.com/patterns/command/): can be used to encapsulate a request as an object, which might be passed along the chain. +* [Composite](https://java-design-patterns.com/patterns/composite/): the Chain of Responsibility is often applied in conjunction with the Composite pattern. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): decorators can be chained in a similar manner as responsibilities in the Chain of Responsibility pattern. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3PAJUg5) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) +* [Pattern languages of program design 3](https://amzn.to/4a4NxTH) diff --git a/chain-of-responsibility/etc/chain-of-responsibility-flowchart.png b/chain-of-responsibility/etc/chain-of-responsibility-flowchart.png new file mode 100644 index 000000000000..875507374086 Binary files /dev/null and b/chain-of-responsibility/etc/chain-of-responsibility-flowchart.png differ diff --git a/chain-of-responsibility/etc/chain-of-responsibility.urm.png b/chain-of-responsibility/etc/chain-of-responsibility.urm.png new file mode 100644 index 000000000000..af1bd105455b Binary files /dev/null and b/chain-of-responsibility/etc/chain-of-responsibility.urm.png differ diff --git a/chain-of-responsibility/etc/chain-of-responsibility.urm.puml b/chain-of-responsibility/etc/chain-of-responsibility.urm.puml new file mode 100644 index 000000000000..b548cab81847 --- /dev/null +++ b/chain-of-responsibility/etc/chain-of-responsibility.urm.puml @@ -0,0 +1,67 @@ +@startuml +package com.iluwatar.chain { + class App { + + App() + + main(args : String[]) {static} + } + class OrcCommander { + - LOGGER : Logger {static} + + OrcCommander() + + canHandleRequest(req : Request) : boolean + + getPriority() : int + + handle(req : Request) + + name() : String + } + class OrcKing { + - handlers : List + + OrcKing() + - buildChain() + + makeRequest(req : Request) + } + class OrcOfficer { + - LOGGER : Logger {static} + + OrcOfficer() + + canHandleRequest(req : Request) : boolean + + getPriority() : int + + handle(req : Request) + + name() : String + } + class OrcSoldier { + - LOGGER : Logger {static} + + OrcSoldier() + + canHandleRequest(req : Request) : boolean + + getPriority() : int + + handle(req : Request) + + name() : String + } + class Request { + - handled : boolean + - requestDescription : String + - requestType : RequestType + + Request(requestType : RequestType, requestDescription : String) + + getRequestDescription() : String + + getRequestType() : RequestType + + isHandled() : boolean + + markHandled() + + toString() : String + } + interface RequestHandler { + + canHandleRequest(Request) : boolean {abstract} + + getPriority() : int {abstract} + + handle(Request) {abstract} + + name() : String {abstract} + } + enum RequestType { + + COLLECT_TAX {static} + + DEFEND_CASTLE {static} + + TORTURE_PRISONER {static} + + valueOf(name : String) : RequestType {static} + + values() : RequestType[] {static} + } +} +OrcKing --> "-handlers" RequestHandler +Request --> "-requestType" RequestType +OrcCommander ..|> RequestHandler +OrcOfficer ..|> RequestHandler +OrcSoldier ..|> RequestHandler +@enduml \ No newline at end of file diff --git a/chain-of-responsibility/pom.xml b/chain-of-responsibility/pom.xml new file mode 100644 index 000000000000..e6a7fb974be7 --- /dev/null +++ b/chain-of-responsibility/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + chain-of-responsibility + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.chain.App + + + + + + + + + diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/App.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/App.java new file mode 100644 index 000000000000..2ddbf0166648 --- /dev/null +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/App.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.chain; + +/** + * The Chain of Responsibility pattern is a design pattern consisting of command objects and a + * series of processing objects. Each processing object contains logic that defines the types of + * command objects that it can handle; the rest are passed to the next processing object in the + * chain. A mechanism also exists for adding new processing objects to the end of this chain. + * + *

    In this example we organize the request handlers ({@link RequestHandler}) into a chain where + * each handler has a chance to act on the request on its turn. Here the king ({@link OrcKing}) + * makes requests and the military orcs ({@link OrcCommander}, {@link OrcOfficer}, {@link + * OrcSoldier}) form the handler chain. + */ +public class App { + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + + var king = new OrcKing(); + king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); + king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); + king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); + } +} diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcCommander.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcCommander.java new file mode 100644 index 000000000000..ad3749c985ca --- /dev/null +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcCommander.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.chain; + +import lombok.extern.slf4j.Slf4j; + +/** OrcCommander. */ +@Slf4j +public class OrcCommander implements RequestHandler { + @Override + public boolean canHandleRequest(Request req) { + return req.getRequestType() == RequestType.DEFEND_CASTLE; + } + + @Override + public int getPriority() { + return 2; + } + + @Override + public void handle(Request req) { + req.markHandled(); + LOGGER.info("{} handling request \"{}\"", name(), req); + } + + @Override + public String name() { + return "Orc commander"; + } +} diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcKing.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcKing.java new file mode 100644 index 000000000000..7500ebf3af77 --- /dev/null +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcKing.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.chain; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +/** OrcKing makes requests that are handled by the chain. */ +public class OrcKing { + + private List handlers; + + public OrcKing() { + buildChain(); + } + + private void buildChain() { + handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier()); + } + + /** Handle request by the chain. */ + public void makeRequest(Request req) { + handlers.stream() + .sorted(Comparator.comparing(RequestHandler::getPriority)) + .filter(handler -> handler.canHandleRequest(req)) + .findFirst() + .ifPresent(handler -> handler.handle(req)); + } +} diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcOfficer.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcOfficer.java new file mode 100644 index 000000000000..0edb579119e1 --- /dev/null +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcOfficer.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.chain; + +import lombok.extern.slf4j.Slf4j; + +/** OrcOfficer. */ +@Slf4j +public class OrcOfficer implements RequestHandler { + @Override + public boolean canHandleRequest(Request req) { + return req.getRequestType() == RequestType.TORTURE_PRISONER; + } + + @Override + public int getPriority() { + return 3; + } + + @Override + public void handle(Request req) { + req.markHandled(); + LOGGER.info("{} handling request \"{}\"", name(), req); + } + + @Override + public String name() { + return "Orc officer"; + } +} diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcSoldier.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcSoldier.java new file mode 100644 index 000000000000..7398844cd0e2 --- /dev/null +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcSoldier.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.chain; + +import lombok.extern.slf4j.Slf4j; + +/** OrcSoldier. */ +@Slf4j +public class OrcSoldier implements RequestHandler { + @Override + public boolean canHandleRequest(Request req) { + return req.getRequestType() == RequestType.COLLECT_TAX; + } + + @Override + public int getPriority() { + return 1; + } + + @Override + public void handle(Request req) { + req.markHandled(); + LOGGER.info("{} handling request \"{}\"", name(), req); + } + + @Override + public String name() { + return "Orc soldier"; + } +} diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/Request.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/Request.java new file mode 100644 index 000000000000..2f94422647a4 --- /dev/null +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/Request.java @@ -0,0 +1,69 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.chain; + +import java.util.Objects; +import lombok.Getter; + +/** Request. */ +@Getter +public class Request { + + /** + * The type of this request, used by each item in the chain to see if they should or can handle + * this particular request. + */ + private final RequestType requestType; + + /** A description of the request. */ + private final String requestDescription; + + /** + * Indicates if the request is handled or not. A request can only switch state from unhandled to + * handled, there's no way to 'unhandle' a request. + */ + private boolean handled; + + /** + * Create a new request of the given type and accompanied description. + * + * @param requestType The type of request + * @param requestDescription The description of the request + */ + public Request(final RequestType requestType, final String requestDescription) { + this.requestType = Objects.requireNonNull(requestType); + this.requestDescription = Objects.requireNonNull(requestDescription); + } + + /** Mark the request as handled. */ + public void markHandled() { + this.handled = true; + } + + @Override + public String toString() { + return getRequestDescription(); + } +} diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestHandler.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestHandler.java new file mode 100644 index 000000000000..89eafbdcb43c --- /dev/null +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestHandler.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.chain; + +/** RequestHandler. */ +public interface RequestHandler { + + boolean canHandleRequest(Request req); + + int getPriority(); + + void handle(Request req); + + String name(); +} diff --git a/chain/src/main/java/com/iluwatar/chain/RequestType.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestType.java similarity index 81% rename from chain/src/main/java/com/iluwatar/chain/RequestType.java rename to chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestType.java index f4d83edc3c94..f3cc73c97a08 100644 --- a/chain/src/main/java/com/iluwatar/chain/RequestType.java +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestType.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,13 +24,9 @@ */ package com.iluwatar.chain; -/** - * - * RequestType enumeration - * - */ +/** RequestType enumeration. */ public enum RequestType { - - DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX - + DEFEND_CASTLE, + TORTURE_PRISONER, + COLLECT_TAX } diff --git a/chain-of-responsibility/src/test/java/com/iluwatar/chain/AppTest.java b/chain-of-responsibility/src/test/java/com/iluwatar/chain/AppTest.java new file mode 100644 index 000000000000..4d2cd68991d9 --- /dev/null +++ b/chain-of-responsibility/src/test/java/com/iluwatar/chain/AppTest.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.chain; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application test */ +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/chain-of-responsibility/src/test/java/com/iluwatar/chain/OrcKingTest.java b/chain-of-responsibility/src/test/java/com/iluwatar/chain/OrcKingTest.java new file mode 100644 index 000000000000..ec53a411787a --- /dev/null +++ b/chain-of-responsibility/src/test/java/com/iluwatar/chain/OrcKingTest.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.chain; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.Test; + +/** OrcKingTest */ +class OrcKingTest { + + /** All possible requests */ + private static final List REQUESTS = + List.of( + new Request(RequestType.DEFEND_CASTLE, "Don't let the barbarians enter my castle!!"), + new Request(RequestType.TORTURE_PRISONER, "Don't just stand there, tickle him!"), + new Request(RequestType.COLLECT_TAX, "Don't steal, the King hates competition ...")); + + @Test + void testMakeRequest() { + final var king = new OrcKing(); + + REQUESTS.forEach( + request -> { + king.makeRequest(request); + assertTrue( + request.isHandled(), + "Expected all requests from King to be handled, but [" + request + "] was not!"); + }); + } +} diff --git a/chain/README.md b/chain/README.md deleted file mode 100644 index eb434aea818e..000000000000 --- a/chain/README.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -layout: pattern -title: Chain of responsibility -folder: chain -permalink: /patterns/chain/ -categories: Behavioral -tags: - - Java - - Gang Of Four - - Difficulty-Intermediate ---- - -## Intent -Avoid coupling the sender of a request to its receiver by giving -more than one object a chance to handle the request. Chain the receiving -objects and pass the request along the chain until an object handles it. - -## Explanation - -Real world example - -> The Orc King gives loud orders to his army. The closest one to react is the commander, then officer and then soldier. The commander, officer and soldier here form a chain of responsibility. - -In plain words - -> It helps building a chain of objects. Request enters from one end and keeps going from object to object till it finds the suitable handler. - -Wikipedia says - -> In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. - -**Programmatic Example** - -Translating our example with orcs from above. First we have the request class - -```java -public class Request { - - private final RequestType requestType; - private final String requestDescription; - private boolean handled; - - public Request(final RequestType requestType, final String requestDescription) { - this.requestType = Objects.requireNonNull(requestType); - this.requestDescription = Objects.requireNonNull(requestDescription); - } - - public String getRequestDescription() { return requestDescription; } - - public RequestType getRequestType() { return requestType; } - - public void markHandled() { this.handled = true; } - - public boolean isHandled() { return this.handled; } - - @Override - public String toString() { return getRequestDescription(); } -} - -public enum RequestType { - DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX -} -``` - -Then the request handler hierarchy - -```java -public abstract class RequestHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class); - private RequestHandler next; - - public RequestHandler(RequestHandler next) { - this.next = next; - } - - public void handleRequest(Request req) { - if (next != null) { - next.handleRequest(req); - } - } - - protected void printHandling(Request req) { - LOGGER.info("{} handling request \"{}\"", this, req); - } - - @Override - public abstract String toString(); -} - -public class OrcCommander extends RequestHandler { - public OrcCommander(RequestHandler handler) { - super(handler); - } - - @Override - public void handleRequest(Request req) { - if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) { - printHandling(req); - req.markHandled(); - } else { - super.handleRequest(req); - } - } - - @Override - public String toString() { - return "Orc commander"; - } -} - -// OrcOfficer and OrcSoldier are defined similarly as OrcCommander - -``` - -Then we have the Orc King who gives the orders and forms the chain - -```java -public class OrcKing { - RequestHandler chain; - - public OrcKing() { - buildChain(); - } - - private void buildChain() { - chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null))); - } - - public void makeRequest(Request req) { - chain.handleRequest(req); - } -} -``` - -Then it is used as follows - -```java -OrcKing king = new OrcKing(); -king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); // Orc commander handling request "defend castle" -king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); // Orc officer handling request "torture prisoner" -king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); // Orc soldier handling request "collect tax" -``` - -## Applicability -Use Chain of Responsibility when - -* more than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically -* you want to issue a request to one of several objects without specifying the receiver explicitly -* the set of objects that can handle a request should be specified dynamically - -## Real world examples - -* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) -* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) -* [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-) - -## Credits - -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) diff --git a/chain/pom.xml b/chain/pom.xml deleted file mode 100644 index 07b1a5e4a1c9..000000000000 --- a/chain/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - chain - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - diff --git a/chain/src/main/java/com/iluwatar/chain/App.java b/chain/src/main/java/com/iluwatar/chain/App.java deleted file mode 100644 index 456609e4f366..000000000000 --- a/chain/src/main/java/com/iluwatar/chain/App.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.chain; - -/** - * - * The Chain of Responsibility pattern is a design pattern consisting of command objects and a - * series of processing objects. Each processing object contains logic that defines the types of - * command objects that it can handle; the rest are passed to the next processing object in the - * chain. A mechanism also exists for adding new processing objects to the end of this chain. - *

    - * In this example we organize the request handlers ({@link RequestHandler}) into a chain where each - * handler has a chance to act on the request on its turn. Here the king ({@link OrcKing}) makes - * requests and the military orcs ({@link OrcCommander}, {@link OrcOfficer}, {@link OrcSoldier}) - * form the handler chain. - * - */ -public class App { - - /** - * Program entry point - * - * @param args command line args - */ - public static void main(String[] args) { - - OrcKing king = new OrcKing(); - king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); - king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); - king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); - - } -} diff --git a/chain/src/main/java/com/iluwatar/chain/OrcCommander.java b/chain/src/main/java/com/iluwatar/chain/OrcCommander.java deleted file mode 100644 index 048ba495457f..000000000000 --- a/chain/src/main/java/com/iluwatar/chain/OrcCommander.java +++ /dev/null @@ -1,50 +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.chain; - -/** - * - * OrcCommander - * - */ -public class OrcCommander extends RequestHandler { - - public OrcCommander(RequestHandler handler) { - super(handler); - } - - @Override - public void handleRequest(Request req) { - if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) { - printHandling(req); - req.markHandled(); - } else { - super.handleRequest(req); - } - } - - @Override - public String toString() { - return "Orc commander"; - } -} diff --git a/chain/src/main/java/com/iluwatar/chain/OrcKing.java b/chain/src/main/java/com/iluwatar/chain/OrcKing.java deleted file mode 100644 index 35bdbb3c1e46..000000000000 --- a/chain/src/main/java/com/iluwatar/chain/OrcKing.java +++ /dev/null @@ -1,46 +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.chain; - -/** - * - * OrcKing makes requests that are handled by the chain. - * - */ -public class OrcKing { - - RequestHandler chain; - - public OrcKing() { - buildChain(); - } - - private void buildChain() { - chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null))); - } - - public void makeRequest(Request req) { - chain.handleRequest(req); - } - -} diff --git a/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java b/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java deleted file mode 100644 index 8e90b7ca0bdb..000000000000 --- a/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java +++ /dev/null @@ -1,51 +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.chain; - -/** - * - * OrcOfficer - * - */ -public class OrcOfficer extends RequestHandler { - - public OrcOfficer(RequestHandler handler) { - super(handler); - } - - @Override - public void handleRequest(Request req) { - if (req.getRequestType().equals(RequestType.TORTURE_PRISONER)) { - printHandling(req); - req.markHandled(); - } else { - super.handleRequest(req); - } - } - - @Override - public String toString() { - return "Orc officer"; - } - -} diff --git a/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java b/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java deleted file mode 100644 index 99e0d5022348..000000000000 --- a/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java +++ /dev/null @@ -1,50 +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.chain; - -/** - * - * OrcSoldier - * - */ -public class OrcSoldier extends RequestHandler { - - public OrcSoldier(RequestHandler handler) { - super(handler); - } - - @Override - public void handleRequest(Request req) { - if (req.getRequestType().equals(RequestType.COLLECT_TAX)) { - printHandling(req); - req.markHandled(); - } else { - super.handleRequest(req); - } - } - - @Override - public String toString() { - return "Orc soldier"; - } -} diff --git a/chain/src/main/java/com/iluwatar/chain/Request.java b/chain/src/main/java/com/iluwatar/chain/Request.java deleted file mode 100644 index c9ac2505b623..000000000000 --- a/chain/src/main/java/com/iluwatar/chain/Request.java +++ /dev/null @@ -1,100 +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.chain; - -import java.util.Objects; - -/** - * Request - */ -public class Request { - - /** - * The type of this request, used by each item in the chain to see if they should or can handle - * this particular request - */ - private final RequestType requestType; - - /** - * A description of the request - */ - private final String requestDescription; - - /** - * Indicates if the request is handled or not. A request can only switch state from unhandled to - * handled, there's no way to 'unhandle' a request - */ - private boolean handled; - - /** - * Create a new request of the given type and accompanied description. - * - * @param requestType The type of request - * @param requestDescription The description of the request - */ - public Request(final RequestType requestType, final String requestDescription) { - this.requestType = Objects.requireNonNull(requestType); - this.requestDescription = Objects.requireNonNull(requestDescription); - } - - /** - * Get a description of the request - * - * @return A human readable description of the request - */ - public String getRequestDescription() { - return requestDescription; - } - - /** - * Get the type of this request, used by each person in the chain of command to see if they should - * or can handle this particular request - * - * @return The request type - */ - public RequestType getRequestType() { - return requestType; - } - - /** - * Mark the request as handled - */ - public void markHandled() { - this.handled = true; - } - - /** - * Indicates if this request is handled or not - * - * @return true when the request is handled, false if not - */ - public boolean isHandled() { - return this.handled; - } - - @Override - public String toString() { - return getRequestDescription(); - } - -} diff --git a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java deleted file mode 100644 index 81e41fb7c120..000000000000 --- a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java +++ /dev/null @@ -1,58 +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.chain; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * RequestHandler - * - */ -public abstract class RequestHandler { - - private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class); - - private RequestHandler next; - - public RequestHandler(RequestHandler next) { - this.next = next; - } - - /** - * Request handler - */ - public void handleRequest(Request req) { - if (next != null) { - next.handleRequest(req); - } - } - - protected void printHandling(Request req) { - LOGGER.info("{} handling request \"{}\"", this, req); - } - - @Override - public abstract String toString(); -} diff --git a/chain/src/test/java/com/iluwatar/chain/AppTest.java b/chain/src/test/java/com/iluwatar/chain/AppTest.java deleted file mode 100644 index 577221bac762..000000000000 --- a/chain/src/test/java/com/iluwatar/chain/AppTest.java +++ /dev/null @@ -1,39 +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.chain; - -import org.junit.jupiter.api.Test; - -/** - * - * Application test - * - */ -public class AppTest { - - @Test - public void test() { - String[] args = {}; - App.main(args); - } -} diff --git a/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java b/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java deleted file mode 100644 index c7cfb687c01a..000000000000 --- a/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java +++ /dev/null @@ -1,59 +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.chain; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Date: 12/6/15 - 9:29 PM - * - * @author Jeroen Meulemeester - */ -public class OrcKingTest { - - /** - * All possible requests - */ - private static final Request[] REQUESTS = new Request[]{ - new Request(RequestType.DEFEND_CASTLE, "Don't let the barbarians enter my castle!!"), - new Request(RequestType.TORTURE_PRISONER, "Don't just stand there, tickle him!"), - new Request(RequestType.COLLECT_TAX, "Don't steal, the King hates competition ..."), - }; - - @Test - public void testMakeRequest() throws Exception { - final OrcKing king = new OrcKing(); - - for (final Request request : REQUESTS) { - king.makeRequest(request); - assertTrue( - request.isHandled(), - "Expected all requests from King to be handled, but [" + request + "] was not!" - ); - } - - } - -} \ No newline at end of file diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index 37799eee8a93..5df5050f05ea 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -1,33 +1,11 @@ - - + - - - - + + + + + + + diff --git a/checkstyle.xml b/checkstyle.xml deleted file mode 100644 index e5c12ac3a48b..000000000000 --- a/checkstyle.xml +++ /dev/null @@ -1,197 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/circuit-breaker/README.md b/circuit-breaker/README.md new file mode 100644 index 000000000000..99c1b7b4d398 --- /dev/null +++ b/circuit-breaker/README.md @@ -0,0 +1,226 @@ +--- +title: "Circuit Breaker Pattern in Java: Enhancing System Resilience" +shortTitle: Circuit Breaker +description: "Learn about the Circuit Breaker pattern in Java design, which ensures fault tolerance and prevents cascading failures in distributed systems and microservices architectures." +category: Resilience +language: en +tag: + - Cloud distributed + - Fault tolerance + - Microservices + - Retry +--- + +## Also known as + +* Fault Tolerance Switch + +## Intent of Circuit Breaker Design Pattern + +The Circuit Breaker pattern is a critical Java design pattern that helps ensure fault tolerance and resilience in microservices and distributed systems. Using Circuit Breaker, it is possible to prevent a system from repeatedly trying to execute an operation likely to fail, allowing it to recover from faults and prevent cascading failures. + +## Detailed Explanation of Circuit Breaker Pattern with Real-World Examples + +Real-world example + +> Consider a real-world example of an e-commerce website that depends on multiple external payment gateways to process transactions. If one of the payment gateways becomes unresponsive or slow, the Circuit Breaker pattern can be used to detect the failure and prevent the system from repeatedly attempting to use the problematic gateway. Instead, it can quickly switch to alternative payment gateways or display an error message to the user, ensuring that the rest of the website remains functional and responsive. This avoids resource exhaustion and provides a better user experience by allowing transactions to be processed through other available services. This way, the Circuit Breaker pattern handles external API failures, ensuring the system remains functional. + +In plain words + +> Circuit Breaker allows graceful handling of failed remote services. It's especially useful when all parts of our application are highly decoupled from each other, and failure of one component doesn't mean the other parts will stop working. + +Wikipedia says + +> Circuit breaker is a design pattern used in modern software development. It is used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties. + +Flowchart + +![Circuit Breaker flowchart](./etc/circuit-breaker-flowchart.png) + +## Programmatic Example of Circuit Breaker Pattern in Java + +This Java example demonstrates how the Circuit Breaker pattern can manage remote service failures and maintain system stability. + +Imagine a web application that uses both local files/images and remote services to fetch data. Remote services can become slow or unresponsive, which may cause the application to hang due to thread starvation. The Circuit Breaker pattern can help detect such failures and allow the application to degrade gracefully. + +1. **Simulating a Delayed Remote Service** + +```java +// The DelayedRemoteService simulates a remote service that responds after a certain delay. +var delayedService = new DelayedRemoteService(serverStartTime, 5); +``` + +2. **Setting Up the Circuit Breaker** + +```java +// The DefaultCircuitBreaker wraps the remote service and monitors for failures. +var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2, 2000 * 1000 * 1000); +``` + +3. **Monitoring Service to Handle Requests** + +```java +// The MonitoringService is responsible for calling the remote services. +var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, quickServiceCircuitBreaker); + +// Fetch response from local resource +LOGGER.info(monitoringService.localResourceResponse()); + +// Fetch response from delayed service 2 times to meet the failure threshold +LOGGER.info(monitoringService.delayedServiceResponse()); +LOGGER.info(monitoringService.delayedServiceResponse()); +``` + +4. **Handling Circuit Breaker States** + +```java +// Fetch current state of delayed service circuit breaker after crossing failure threshold limit +LOGGER.info(delayedServiceCircuitBreaker.getState()); // Should be OPEN + +// Meanwhile, the delayed service is down, fetch response from the healthy quick service +LOGGER.info(monitoringService.quickServiceResponse()); +LOGGER.info(quickServiceCircuitBreaker.getState()); +``` + +5. **Recovering from Failure** + +```java +// Wait for the delayed service to become responsive +try { + LOGGER.info("Waiting for delayed service to become responsive"); + Thread.sleep(5000); +} catch (InterruptedException e) { + LOGGER.error("An error occurred: ", e); +} + +// Check the state of delayed circuit breaker, should be HALF_OPEN +LOGGER.info(delayedServiceCircuitBreaker.getState()); + +// Fetch response from delayed service, which should be healthy by now +LOGGER.info(monitoringService.delayedServiceResponse()); + +// As successful response is fetched, it should be CLOSED again. +LOGGER.info(delayedServiceCircuitBreaker.getState()); +``` + +6. **Full example** + +```java +public static void main(String[] args) { + + var serverStartTime = System.nanoTime(); + + var delayedService = new DelayedRemoteService(serverStartTime, 5); + var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2, + 2000 * 1000 * 1000); + + var quickService = new QuickRemoteService(); + var quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, 2, + 2000 * 1000 * 1000); + + //Create an object of monitoring service which makes both local and remote calls + var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, + quickServiceCircuitBreaker); + + //Fetch response from local resource + LOGGER.info(monitoringService.localResourceResponse()); + + //Fetch response from delayed service 2 times, to meet the failure threshold + LOGGER.info(monitoringService.delayedServiceResponse()); + LOGGER.info(monitoringService.delayedServiceResponse()); + + //Fetch current state of delayed service circuit breaker after crossing failure threshold limit + //which is OPEN now + LOGGER.info(delayedServiceCircuitBreaker.getState()); + + //Meanwhile, the delayed service is down, fetch response from the healthy quick service + LOGGER.info(monitoringService.quickServiceResponse()); + LOGGER.info(quickServiceCircuitBreaker.getState()); + + //Wait for the delayed service to become responsive + try { + LOGGER.info("Waiting for delayed service to become responsive"); + Thread.sleep(5000); + } catch (InterruptedException e) { + LOGGER.error("An error occurred: ", e); + } + //Check the state of delayed circuit breaker, should be HALF_OPEN + LOGGER.info(delayedServiceCircuitBreaker.getState()); + + //Fetch response from delayed service, which should be healthy by now + LOGGER.info(monitoringService.delayedServiceResponse()); + //As successful response is fetched, it should be CLOSED again. + LOGGER.info(delayedServiceCircuitBreaker.getState()); +} +``` + +Summary of the example + +- Initialize the Circuit Breaker with parameters: `timeout`, `failureThreshold`, and `retryTimePeriod`. +- Start in the `closed` state. +- On successful calls, reset the state. +- On failures exceeding the threshold, transition to the `open` state to prevent further calls. +- After the retry timeout, transition to the `half-open` state to test the service. +- On success in `half-open` state, transition back to `closed`. On failure, return to `open`. + +Program output: + +``` +16:59:19.767 [main] INFO com.iluwatar.circuitbreaker.App -- Local Service is working +16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- Delayed service is down +16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- Delayed service is down +16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- OPEN +16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- Quick Service is working +16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- CLOSED +16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- Waiting for delayed service to become responsive +16:59:24.779 [main] INFO com.iluwatar.circuitbreaker.App -- HALF_OPEN +16:59:24.780 [main] INFO com.iluwatar.circuitbreaker.App -- Delayed service is working +16:59:24.780 [main] INFO com.iluwatar.circuitbreaker.App -- CLOSED +``` + +This example demonstrates how the Circuit Breaker pattern can help maintain application stability and resilience by managing remote service failures. + +## When to Use the Circuit Breaker Pattern in Java + +The Circuit Breaker pattern is applicable: + +* In distributed systems where individual service failures can lead to cascading system-wide failures +* For applications that interact with third-party services or databases that might become unresponsive or slow +* In microservices architectures where the failure of one service can affect the availability of others + +## Real-World Applications of Circuit Breaker Pattern in Java + +* Cloud-based services to gracefully handle the failure of external services +* E-commerce platforms to manage high volumes of transactions and dependency on external APIs +* Microservices architectures for maintaining system stability and responsiveness +* [Spring Circuit Breaker module](https://spring.io/guides/gs/circuit-breaker) +* [Netflix Hystrix API](https://github.com/Netflix/Hystrix) + +## Benefits and Trade-offs of Circuit Breaker Pattern + +Benefits: + +* Prevents the system from performing futile operations that are likely to fail, thus saving resources +* Helps in maintaining the system stability and performance of the application during partial system failures +* Facilitates faster system recovery by avoiding the overwhelming of failing services with repeated requests + +Trade-Offs: + +* The complexity of the system increases as the pattern requires additional logic to detect failures and manage the state of the circuit breaker +* May lead to system degradation if not properly configured, as legitimate requests might be blocked if the circuit is open +* Requires careful tuning of thresholds and timeout periods to balance between responsiveness and protection + +## Related Patterns + +- Bulkhead: Can be used to isolate different parts of the system to prevent failures from spreading across the system +- [Retry Pattern](https://github.com/iluwatar/java-design-patterns/tree/master/retry): Can be used in conjunction with the Circuit Breaker pattern to retry failed operations before opening the circuit + +## References and Credits + +* [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/43Dx86g) +* [Microservices Patterns: With examples in Java](https://amzn.to/3xaZwk0) +* [Release It! Design and Deploy Production-Ready Software](https://amzn.to/4aqTNEP) +* [Understand CircuitBreaker Design Pattern with Simple Practical Example (ITNEXT)](https://itnext.io/understand-circuitbreaker-design-pattern-with-simple-practical-example-92a752615b42) +* [Circuit Breaker (Martin Fowler)](https://martinfowler.com/bliki/CircuitBreaker.html) +* [Fault tolerance in a high volume, distributed system (Netflix)](https://medium.com/netflix-techblog/fault-tolerance-in-a-high-volume-distributed-system-91ab4faae74a) +* [Circuit Breaker pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker) diff --git a/circuit-breaker/etc/circuit-breaker-flowchart.png b/circuit-breaker/etc/circuit-breaker-flowchart.png new file mode 100644 index 000000000000..6e0af83e0eee Binary files /dev/null and b/circuit-breaker/etc/circuit-breaker-flowchart.png differ diff --git a/circuit-breaker/etc/circuit-breaker.urm.png b/circuit-breaker/etc/circuit-breaker.urm.png new file mode 100644 index 000000000000..fc90318ec8da Binary files /dev/null and b/circuit-breaker/etc/circuit-breaker.urm.png differ diff --git a/circuit-breaker/etc/circuit-breaker.urm.puml b/circuit-breaker/etc/circuit-breaker.urm.puml new file mode 100644 index 000000000000..951ec02d31c5 --- /dev/null +++ b/circuit-breaker/etc/circuit-breaker.urm.puml @@ -0,0 +1,69 @@ +@startuml +package com.iluwatar.circuitbreaker { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + interface CircuitBreaker { + + attemptRequest() : String {abstract} + + getState() : String {abstract} + + recordFailure(String) {abstract} + + recordSuccess() {abstract} + + setState(State) {abstract} + } + class DefaultCircuitBreaker { + ~ failureCount : int + - failureThreshold : int + - futureTime : long + - lastFailureResponse : String + ~ lastFailureTime : long + - retryTimePeriod : long + - service : RemoteService + - state : State + - timeout : long + ~ DefaultCircuitBreaker(serviceToCall : RemoteService, timeout : long, failureThreshold : int, retryTimePeriod : long) + + attemptRequest() : String + # evaluateState() + + getState() : String + + recordFailure(response : String) + + recordSuccess() + + setState(state : State) + } + class DelayedRemoteService { + - delay : int + - serverStartTime : long + + DelayedRemoteService() + + DelayedRemoteService(serverStartTime : long, delay : int) + + call() : String + } + class MonitoringService { + - delayedService : CircuitBreaker + - quickService : CircuitBreaker + + MonitoringService(delayedService : CircuitBreaker, quickService : CircuitBreaker) + + delayedServiceResponse() : String + + localResourceResponse() : String + + quickServiceResponse() : String + } + class QuickRemoteService { + + QuickRemoteService() + + call() : String + } + interface RemoteService { + + call() : String {abstract} + } + enum State { + + CLOSED {static} + + HALF_OPEN {static} + + OPEN {static} + + valueOf(name : String) : State {static} + + values() : State[] {static} + } +} +DefaultCircuitBreaker --> "-state" State +MonitoringService --> "-delayedService" CircuitBreaker +DefaultCircuitBreaker --> "-service" RemoteService +DefaultCircuitBreaker ..|> CircuitBreaker +DelayedRemoteService ..|> RemoteService +QuickRemoteService ..|> RemoteService +@enduml \ No newline at end of file diff --git a/circuit-breaker/pom.xml b/circuit-breaker/pom.xml new file mode 100644 index 000000000000..5b2be0c5605a --- /dev/null +++ b/circuit-breaker/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + circuit-breaker + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.circuitbreaker.App + + + + + + + + + diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java new file mode 100644 index 000000000000..6011aa9d10e6 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java @@ -0,0 +1,108 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +import lombok.extern.slf4j.Slf4j; + +/** + * The intention of the Circuit Builder pattern is to handle remote failures robustly, which is to + * mean that if a service is dependent on n number of other services, and m of them fail, we should + * be able to recover from that failure by ensuring that the user can still use the services that + * are actually functional, and resources are not tied up by uselessly by the services which are not + * working. However, we should also be able to detect when any of the m failing services become + * operational again, so that we can use it + * + *

    In this example, the circuit breaker pattern is demonstrated by using three services: {@link + * DelayedRemoteService}, {@link QuickRemoteService} and {@link MonitoringService}. The monitoring + * service is responsible for calling three services: a local service, a quick remove service {@link + * QuickRemoteService} and a delayed remote service {@link DelayedRemoteService} , and by using the + * circuit breaker construction we ensure that if the call to remote service is going to fail, we + * are going to save our resources and not make the function call at all, by wrapping our call to + * the remote services in the {@link DefaultCircuitBreaker} implementation object. + * + *

    This works as follows: The {@link DefaultCircuitBreaker} object can be in one of three states: + * Open, Closed and Half-Open, which represents the real world circuits. If the + * state is closed (initial), we assume everything is alright and perform the function call. + * However, every time the call fails, we note it and once it crosses a threshold, we set the state + * to Open, preventing any further calls to the remote server. Then, after a certain retry period + * (during which we expect thee service to recover), we make another call to the remote server and + * this state is called the Half-Open state, where it stays till the service is down, and once it + * recovers, it goes back to the closed state and the cycle continues. + */ +@Slf4j +public class App { + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + + var serverStartTime = System.nanoTime(); + + var delayedService = new DelayedRemoteService(serverStartTime, 5); + var delayedServiceCircuitBreaker = + new DefaultCircuitBreaker(delayedService, 3000, 2, 2000 * 1000 * 1000); + + var quickService = new QuickRemoteService(); + var quickServiceCircuitBreaker = + new DefaultCircuitBreaker(quickService, 3000, 2, 2000 * 1000 * 1000); + + // Create an object of monitoring service which makes both local and remote calls + var monitoringService = + new MonitoringService(delayedServiceCircuitBreaker, quickServiceCircuitBreaker); + + // Fetch response from local resource + LOGGER.info(monitoringService.localResourceResponse()); + + // Fetch response from delayed service 2 times, to meet the failure threshold + LOGGER.info(monitoringService.delayedServiceResponse()); + LOGGER.info(monitoringService.delayedServiceResponse()); + + // Fetch current state of delayed service circuit breaker after crossing failure threshold limit + // which is OPEN now + LOGGER.info(delayedServiceCircuitBreaker.getState()); + + // Meanwhile, the delayed service is down, fetch response from the healthy quick service + LOGGER.info(monitoringService.quickServiceResponse()); + LOGGER.info(quickServiceCircuitBreaker.getState()); + + // Wait for the delayed service to become responsive + try { + LOGGER.info("Waiting for delayed service to become responsive"); + Thread.sleep(5000); + } catch (InterruptedException e) { + LOGGER.error("An error occurred: ", e); + } + // Check the state of delayed circuit breaker, should be HALF_OPEN + LOGGER.info(delayedServiceCircuitBreaker.getState()); + + // Fetch response from delayed service, which should be healthy by now + LOGGER.info(monitoringService.delayedServiceResponse()); + // As successful response is fetched, it should be CLOSED again. + LOGGER.info(delayedServiceCircuitBreaker.getState()); + } +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java new file mode 100644 index 000000000000..31e11751a4ea --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +/** The Circuit breaker interface. */ +public interface CircuitBreaker { + + // Success response. Reset everything to defaults + void recordSuccess(); + + // Failure response. Handle accordingly with response and change state if required. + void recordFailure(String response); + + // Get the current state of circuit breaker + String getState(); + + // Set the specific state manually. + void setState(State state); + + // Attempt to fetch response from the remote service. + String attemptRequest() throws RemoteServiceException; +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java new file mode 100644 index 000000000000..762c04d6b589 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java @@ -0,0 +1,156 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +/** + * The delay based Circuit breaker implementation that works in a + * CLOSED->OPEN-(retry_time_period)->HALF_OPEN->CLOSED flow with some retry time period for failed + * services and a failure threshold for service to open circuit. + */ +public class DefaultCircuitBreaker implements CircuitBreaker { + + private final long timeout; + private final long retryTimePeriod; + private final RemoteService service; + long lastFailureTime; + private String lastFailureResponse; + int failureCount; + private final int failureThreshold; + private State state; + // Future time offset, in nanoseconds + private final long futureTime = 1_000_000_000_000L; + + /** + * Constructor to create an instance of Circuit Breaker. + * + * @param timeout Timeout for the API request. Not necessary for this simple example + * @param failureThreshold Number of failures we receive from the depended on service before + * changing state to 'OPEN' + * @param retryTimePeriod Time, in nanoseconds, period after which a new request is made to remote + * service for status check. + */ + DefaultCircuitBreaker( + RemoteService serviceToCall, long timeout, int failureThreshold, long retryTimePeriod) { + this.service = serviceToCall; + // We start in a closed state hoping that everything is fine + this.state = State.CLOSED; + this.failureThreshold = failureThreshold; + // Timeout for the API request. + // Used to break the calls made to remote resource if it exceeds the limit + this.timeout = timeout; + this.retryTimePeriod = retryTimePeriod; + // An absurd amount of time in future which basically indicates the last failure never happened + this.lastFailureTime = System.nanoTime() + futureTime; + this.failureCount = 0; + } + + // Reset everything to defaults + @Override + public void recordSuccess() { + this.failureCount = 0; + this.lastFailureTime = System.nanoTime() + futureTime; + this.state = State.CLOSED; + } + + @Override + public void recordFailure(String response) { + failureCount = failureCount + 1; + this.lastFailureTime = System.nanoTime(); + // Cache the failure response for returning on open state + this.lastFailureResponse = response; + } + + // Evaluate the current state based on failureThreshold, failureCount and lastFailureTime. + protected void evaluateState() { + if (failureCount >= failureThreshold) { // Then something is wrong with remote service + if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) { + // We have waited long enough and should try checking if service is up + state = State.HALF_OPEN; + } else { + // Service would still probably be down + state = State.OPEN; + } + } else { + // Everything is working fine + state = State.CLOSED; + } + } + + @Override + public String getState() { + evaluateState(); + return state.name(); + } + + /** + * Break the circuit beforehand if it is known service is down Or connect the circuit manually if + * service comes online before expected. + * + * @param state State at which circuit is in + */ + @Override + public void setState(State state) { + this.state = state; + switch (state) { + case OPEN -> { + this.failureCount = failureThreshold; + this.lastFailureTime = System.nanoTime(); + } + case HALF_OPEN -> { + this.failureCount = failureThreshold; + this.lastFailureTime = System.nanoTime() - retryTimePeriod; + } + default -> this.failureCount = 0; + } + } + + /** + * Executes service call. + * + * @return Value from the remote resource, stale response or a custom exception + */ + @Override + public String attemptRequest() throws RemoteServiceException { + evaluateState(); + if (state == State.OPEN) { + // return cached response if the circuit is in OPEN state + return this.lastFailureResponse; + } else { + // Make the API request if the circuit is not OPEN + try { + // In a real application, this would be run in a thread and the timeout + // parameter of the circuit breaker would be utilized to know if service + // is working. Here, we simulate that based on server response itself + var response = service.call(); + // Yay!! the API responded fine. Let's reset everything. + recordSuccess(); + return response; + } catch (RemoteServiceException ex) { + recordFailure(ex.getMessage()); + throw ex; + } + } + } +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java new file mode 100644 index 000000000000..ad87f1a6e71d --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java @@ -0,0 +1,69 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +/** + * This simulates the remote service It responds only after a certain timeout period (default set to + * 20 seconds). + */ +public class DelayedRemoteService implements RemoteService { + + private final long serverStartTime; + private final int delay; + + /** + * Constructor to create an instance of DelayedService, which is down for first few seconds. + * + * @param delay the delay after which service would behave properly, in seconds + */ + public DelayedRemoteService(long serverStartTime, int delay) { + this.serverStartTime = serverStartTime; + this.delay = delay; + } + + public DelayedRemoteService() { + this.serverStartTime = System.nanoTime(); + this.delay = 20; + } + + /** + * Responds based on delay, current time and server start time if the service is down / working. + * + * @return The state of the service + */ + @Override + public String call() throws RemoteServiceException { + var currentTime = System.nanoTime(); + // Since currentTime and serverStartTime are both in nanoseconds, we convert it to + // seconds by diving by 10e9 and ensure floating point division by multiplying it + // with 1.0 first. We then check if it is greater or less than specified delay and then + // send the reply + if ((currentTime - serverStartTime) * 1.0 / (1000 * 1000 * 1000) < delay) { + // Can use Thread.sleep() here to block and simulate a hung server + throw new RemoteServiceException("Delayed service is down"); + } + return "Delayed service is working"; + } +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java new file mode 100644 index 000000000000..3fa5cd776d8c --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java @@ -0,0 +1,72 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +/** + * The service class which makes local and remote calls Uses {@link DefaultCircuitBreaker} object to + * ensure remote calls don't use up resources. + */ +public class MonitoringService { + + private final CircuitBreaker delayedService; + + private final CircuitBreaker quickService; + + public MonitoringService(CircuitBreaker delayedService, CircuitBreaker quickService) { + this.delayedService = delayedService; + this.quickService = quickService; + } + + // Assumption: Local service won't fail, no need to wrap it in a circuit breaker logic + public String localResourceResponse() { + return "Local Service is working"; + } + + /** + * Fetch response from the delayed service (with some simulated startup time). + * + * @return response string + */ + public String delayedServiceResponse() { + try { + return this.delayedService.attemptRequest(); + } catch (RemoteServiceException e) { + return e.getMessage(); + } + } + + /** + * Fetches response from a healthy service without any failure. + * + * @return response string + */ + public String quickServiceResponse() { + try { + return this.quickService.attemptRequest(); + } catch (RemoteServiceException e) { + return e.getMessage(); + } + } +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/QuickRemoteService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/QuickRemoteService.java new file mode 100644 index 000000000000..2367e49233ae --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/QuickRemoteService.java @@ -0,0 +1,34 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +/** A quick response remote service, that responds healthy without any delay or failure. */ +public class QuickRemoteService implements RemoteService { + + @Override + public String call() throws RemoteServiceException { + return "Quick Service is working"; + } +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteService.java new file mode 100644 index 000000000000..ced5d3ac9d47 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteService.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +/** + * The Remote service interface, used by {@link CircuitBreaker} for fetching response from remote + * services. + */ +public interface RemoteService { + + // Fetch response from remote service. + String call() throws RemoteServiceException; +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteServiceException.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteServiceException.java new file mode 100644 index 000000000000..48deec756b75 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteServiceException.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +/** Exception thrown when {@link RemoteService} does not respond successfully. */ +public class RemoteServiceException extends Exception { + + public RemoteServiceException(String message) { + super(message); + } +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java new file mode 100644 index 000000000000..f2668281eb57 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +/** Enumeration for states the circuit breaker could be in. */ +public enum State { + CLOSED, + OPEN, + HALF_OPEN +} diff --git a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/AppTest.java b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/AppTest.java new file mode 100644 index 000000000000..3cbeadcd13de --- /dev/null +++ b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/AppTest.java @@ -0,0 +1,134 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** App Test showing usage of circuit breaker. */ +class AppTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class); + + // Startup delay for delayed service (in seconds) + private static final int STARTUP_DELAY = 4; + + // Number of failed requests for circuit breaker to open + private static final int FAILURE_THRESHOLD = 1; + + // Time period in seconds for circuit breaker to retry service + private static final int RETRY_PERIOD = 2; + + private MonitoringService monitoringService; + + private CircuitBreaker delayedServiceCircuitBreaker; + + private CircuitBreaker quickServiceCircuitBreaker; + + /** + * Set up the circuit breakers and services, where {@link DelayedRemoteService} will be start with + * a delay of 4 seconds and a {@link QuickRemoteService} responding healthy. Both services are + * wrapped in a {@link DefaultCircuitBreaker} implementation with failure threshold of 1 failure + * and retry time period of 2 seconds. + */ + @BeforeEach + void setupCircuitBreakers() { + var delayedService = new DelayedRemoteService(System.nanoTime(), STARTUP_DELAY); + // Set the circuit Breaker parameters + delayedServiceCircuitBreaker = + new DefaultCircuitBreaker( + delayedService, 3000, FAILURE_THRESHOLD, RETRY_PERIOD * 1000 * 1000 * 1000); + + var quickService = new QuickRemoteService(); + // Set the circuit Breaker parameters + quickServiceCircuitBreaker = + new DefaultCircuitBreaker( + quickService, 3000, FAILURE_THRESHOLD, RETRY_PERIOD * 1000 * 1000 * 1000); + + monitoringService = + new MonitoringService(delayedServiceCircuitBreaker, quickServiceCircuitBreaker); + } + + @Test + void testFailure_OpenStateTransition() { + // Calling delayed service, which will be unhealthy till 4 seconds + assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); + // As failure threshold is "1", the circuit breaker is changed to OPEN + assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); + // As circuit state is OPEN, we expect a quick fallback response from circuit breaker. + assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); + + // Meanwhile, the quick service is responding and the circuit state is CLOSED + assertEquals("Quick Service is working", monitoringService.quickServiceResponse()); + assertEquals("CLOSED", quickServiceCircuitBreaker.getState()); + } + + @Test + void testFailure_HalfOpenStateTransition() { + // Calling delayed service, which will be unhealthy till 4 seconds + assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); + // As failure threshold is "1", the circuit breaker is changed to OPEN + assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); + + // Waiting for recovery period of 2 seconds for circuit breaker to retry service. + try { + LOGGER.info("Waiting 2s for delayed service to become responsive"); + Thread.sleep(2000); + } catch (InterruptedException e) { + LOGGER.error("An error occurred: ", e); + } + // After 2 seconds, the circuit breaker should move to "HALF_OPEN" state and retry fetching + // response from service again + assertEquals("HALF_OPEN", delayedServiceCircuitBreaker.getState()); + } + + @Test + void testRecovery_ClosedStateTransition() { + // Calling delayed service, which will be unhealthy till 4 seconds + assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); + // As failure threshold is "1", the circuit breaker is changed to OPEN + assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); + + // Waiting for 4 seconds, which is enough for DelayedService to become healthy and respond + // successfully. + try { + LOGGER.info("Waiting 4s for delayed service to become responsive"); + Thread.sleep(4000); + } catch (InterruptedException e) { + LOGGER.error("An error occurred: ", e); + } + // As retry period is 2 seconds (<4 seconds of wait), hence the circuit breaker should be back + // in HALF_OPEN state. + assertEquals("HALF_OPEN", delayedServiceCircuitBreaker.getState()); + // Check the success response from delayed service. + assertEquals("Delayed service is working", monitoringService.delayedServiceResponse()); + // As the response is success, the state should be CLOSED + assertEquals("CLOSED", delayedServiceCircuitBreaker.getState()); + } +} diff --git a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java new file mode 100644 index 000000000000..c184a8376220 --- /dev/null +++ b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java @@ -0,0 +1,82 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +/** Circuit Breaker test */ +class DefaultCircuitBreakerTest { + + // long timeout, int failureThreshold, long retryTimePeriod + @Test + void testEvaluateState() { + var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 100); + // Right now, failureCountfailureThreshold, and lastFailureTime is nearly equal to current time, + // state should be half-open + assertEquals(circuitBreaker.getState(), "HALF_OPEN"); + // Since failureCount>failureThreshold, and lastFailureTime is much lesser current time, + // state should be open + circuitBreaker.lastFailureTime = System.nanoTime() - 1000 * 1000 * 1000 * 1000; + circuitBreaker.evaluateState(); + assertEquals(circuitBreaker.getState(), "OPEN"); + // Now set it back again to closed to test idempotency + circuitBreaker.failureCount = 0; + circuitBreaker.evaluateState(); + assertEquals(circuitBreaker.getState(), "CLOSED"); + } + + @Test + void testSetStateForBypass() { + var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 2000 * 1000 * 1000); + // Right now, failureCount { + var obj = new DelayedRemoteService(); + obj.call(); + }); + } + + /** + * Testing server started in past (2 seconds ago) and with a simulated delay of 1 second. + * + * @throws RemoteServiceException + */ + @Test + void testParameterizedConstructor() throws RemoteServiceException { + var obj = new DelayedRemoteService(System.nanoTime() - 2000 * 1000 * 1000, 1); + assertEquals("Delayed service is working", obj.call()); + } +} diff --git a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java new file mode 100644 index 000000000000..f7781fd1c58d --- /dev/null +++ b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.circuitbreaker; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +/** Monitoring Service test */ +class MonitoringServiceTest { + + // long timeout, int failureThreshold, long retryTimePeriod + @Test + void testLocalResponse() { + var monitoringService = new MonitoringService(null, null); + var response = monitoringService.localResourceResponse(); + assertEquals(response, "Local Service is working"); + } + + @Test + void testDelayedRemoteResponseSuccess() { + var delayedService = new DelayedRemoteService(System.nanoTime() - 2 * 1000 * 1000 * 1000, 2); + var delayedServiceCircuitBreaker = + new DefaultCircuitBreaker(delayedService, 3000, 1, 2 * 1000 * 1000 * 1000); + + var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, null); + // Set time in past to make the server work + var response = monitoringService.delayedServiceResponse(); + assertEquals(response, "Delayed service is working"); + } + + @Test + void testDelayedRemoteResponseFailure() { + var delayedService = new DelayedRemoteService(System.nanoTime(), 2); + var delayedServiceCircuitBreaker = + new DefaultCircuitBreaker(delayedService, 3000, 1, 2 * 1000 * 1000 * 1000); + var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, null); + // Set time as current time as initially server fails + var response = monitoringService.delayedServiceResponse(); + assertEquals(response, "Delayed service is down"); + } + + @Test + void testQuickRemoteServiceResponse() { + var delayedService = new QuickRemoteService(); + var delayedServiceCircuitBreaker = + new DefaultCircuitBreaker(delayedService, 3000, 1, 2 * 1000 * 1000 * 1000); + var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, null); + // Set time as current time as initially server fails + var response = monitoringService.delayedServiceResponse(); + assertEquals(response, "Quick Service is working"); + } +} diff --git a/clean-architecture/README.md b/clean-architecture/README.md new file mode 100644 index 000000000000..599ae19ce13e --- /dev/null +++ b/clean-architecture/README.md @@ -0,0 +1,291 @@ +--- +title: "Clean Architecture - A Software Maintainable Architectural style." +shortTitle: Clean Architecture +description: "Learn the Clean Architecture Style in Java with real-world examples, code snippets, and class diagrams. Enhance your coding skills with our detailed explanations." +category: Architectural +language: en +tag: + - Architecture + - Decoupling + - Domain + - Inversion of control + - Layered architecture + - Modularity + - Testing +--- + +## Intent of Clean Architecture. + +To organize the system so that the core business logic remains independent from external concerns and frameworks. + +## Detailed Explanation of Clean Architecture Pattern with Real-World Examples + +Real-world example + +> Imagine a large pizza chain with multiple ordering channels—web, mobile app, phone calls, and in-store kiosks. The core “pizza domain” logic (calculating prices, preparing orders, managing loyalty points) is kept entirely separate from the user interfaces and storage mechanisms. As a result, the chain can add or change the ordering channel (for example, introducing a chatbot or swapping out the database) without altering the fundamental pizza-ordering rules, thanks to the layered boundaries and strict dependency rules of Clean Architecture. + +In plain words + +> Clean Architecture is a software design approach that isolates the core business logic from external concerns (like databases, frameworks, or UI) through strict layering and clear boundaries, ensuring that changes in one layer don't ripple through the entire system. + +Wikipedia says + +> The clean architecture proposed by Robert C. Martin in 2012 combines the principles of the hexagonal architecture, the onion architecture and several other variants. It provides additional levels of detail of the component, which are presented as concentric rings. It isolates adapters and interfaces (user interface, databases, external systems, devices) in the outer rings of the architecture and leaves the inner rings for use cases and entities. The clean architecture uses the principle of dependency inversion with the strict rule that dependencies shall only exist between an outer ring to an inner ring and never the contrary. + +Mind map + +![Clean Architecture Mind Map](./etc/clean-architecture-mind-map.png) + +Flowchart + +![Clean Architecture Flowchart](./etc/clean-architecture-flowchart.png) + +## Programmatic Example of Clean Architecture Pattern + +First, we define the core domain entities: `Product`, `Order`, and `Cart`. These classes capture the fundamental business logic and state. + +```java +public class Product { + private String id; + private String name; + private double price; + + public Product(String id, String name, double price) { + this.id = id; + this.name = name; + this.price = price; + } +} +``` + +```java +public class Cart { + private Product product; + private int quantity; + + public CartItem(Product product, int quantity) { + this.product = product; + this.quantity = quantity; + } + + public double getTotalPrice() { + return product.getPrice() * quantity; + } +} +``` + +```java +public class Order { + private String orderId; + private List items; + private double totalPrice; + + public Order(String orderId, List items) { + this.orderId = orderId; + this.items = items; + this.totalPrice = items.stream().mapToDouble(CartItem::getTotalPrice).sum(); + } +} +``` + +The repository interfaces are created to abstract data operations for each domain object, allowing us to switch out storage or persistence mechanisms without changing higher-level logic. + +```java +public interface CartRepository { + void addItemToCart(String userId, Product product, int quantity); + void removeItemFromCart(String userId, String productId); + List getItemsInCart(String userId); + double calculateTotal(String userId); + void clearCart(String userId); +} +``` +```java +public interface ProductRepository { + Product getProductById(String productId); +} +``` +```java +public interface OrderRepository { + void saveOrder(Order order); +} +``` + +The in-memory data store implementations use simple collections to hold state. They demonstrate how easily we can replace or extend the data layer (e.g., swapping in a database) without affecting the domain logic. + +```java +public class InMemoryCartRepository implements CartRepository { + private final Map> userCarts = new HashMap<>(); + + @Override + public void addItemToCart(String userId, Product product, int quantity) { + List cart = userCarts.getOrDefault(userId, new ArrayList<>()); + cart.add(new Cart(product, quantity)); + userCarts.put(userId, cart); + } + + @Override + public void removeItemFromCart(String userId, String productId) { + List cart = userCarts.get(userId); + if (cart != null) { + cart.removeIf(item -> item.getProduct().getId().equals(productId)); + } + } + + @Override + public List getItemsInCart(String userId) { + return userCarts.getOrDefault(userId, new ArrayList<>()); + } + + @Override + public double calculateTotal(String userId) { + return userCarts.getOrDefault(userId, new ArrayList<>()) + .stream() + .mapToDouble(Cart::getTotalPrice) + .sum(); + } + + @Override + public void clearCart(String userId) { + userCarts.remove(userId); + } +} +``` +```java +public class InMemoryOrderRepository implements OrderRepository { + private final List orders = new ArrayList<>(); + + @Override + public void saveOrder(Order order) { + orders.add(order); + } +} +``` + +```java +public class InMemoryProductRepository implements ProductRepository { + private final Map products = new HashMap<>(); + + public InMemoryProductRepository() { + products.put("1", new Product("1", "Laptop", 1000.0)); + products.put("2", new Product("2", "Smartphone", 500.0)); + } + + @Override + public Product getProductById(String productId) { + return products.get(productId); + } +} +``` + +The order controller coordinates the checkout process by using the use-case or service layer (`ShoppingCartService`). + +```java +public class OrderController{ + private final ShoppingCartService shoppingCartUseCase; + + public OrderController(ShoppingCartService shoppingCartUseCase) { + this.shoppingCartUseCase = shoppingCartUseCase; + } + + public Order checkout(String userId) { + return shoppingCartUseCase.checkout(userId); + } +} +``` + +The cart controller focuses on cart-related actions like adding or removing items and calculating totals. + + +```java +public class CartController { + private final ShoppingCartService shoppingCartUseCase; + + public CartController(ShoppingCartService shoppingCartUseCase) { + this.shoppingCartUseCase = shoppingCartUseCase; + } + + public void addItemToCart(String userId, String productId, int quantity) { + shoppingCartUseCase.addItemToCart(userId, productId, quantity); + } + + public void removeItemFromCart(String userId, String productId) { + shoppingCartUseCase.removeItemFromCart(userId, productId); + } + + public double calculateTotal(String userId) { + return shoppingCartUseCase.calculateTotal(userId); + } +} +``` + +The clean architecture in action. In the `main` method, we wire up everything, simulating a typical user flow: items are added to the cart, the total is calculated, and finally an order is placed. + +```java +public static void main(String[] args) { + + ProductRepository productRepository = new InMemoryProductRepository(); + CartRepository cartRepository = new InMemoryCartRepository(); + OrderRepository orderRepository = new InMemoryOrderRepository(); + + ShoppingCartService shoppingCartUseCase = + new ShoppingCartService(productRepository, cartRepository, orderRepository); + + CartController cartController = new CartController(shoppingCartUseCase); + OrderController orderController = new OrderController(shoppingCartUseCase); + + String userId = "user123"; + cartController.addItemToCart(userId, "1", 1); + cartController.addItemToCart(userId, "2", 2); + + System.out.println("Total: $" + cartController.calculateTotal(userId)); + + Order order = orderController.checkout(userId); + System.out.println( + "Order placed! Order ID: " + order.getOrderId() + ", Total: $" + order.getTotalPrice()); + } +``` + +The output of the code. + +```md +Total: $2000.0 +Order placed! Order ID: ORDER-1743349969254, Total: $2000.0 +``` + +## When to Use the Clean Architecture Pattern in Java + +* When you want to keep business rules independent of UI, database, or any other external agency +* When you need a high level of maintainability and testability in large Java applications +* When you aim to enforce clear boundaries among application layers + +## Real-World Applications of Clean Architecture Pattern in Java + +* Large-scale enterprise systems in finance and insurance domains +* Microservices-based architectures that prioritize decoupling and modular design +* Java systems requiring stringent separation of concerns and domain-centered design + +## Benefits and Trade-offs of Clean Architecture Pattern + +Benefits: + +* High maintainability by isolating core logic from infrastructure details +* Enhanced testability through clear boundaries around the domain model +* Flexibility in replacing or upgrading external components without affecting core logic + +Trade-Offs: + +* Initial complexity from enforcing strict layers and boundaries +* Potential overhead in smaller projects not requiring such rigid separation +* Requires disciplined team adherence to architecture rules + +## Related Java Design Patterns + +* [Dependency Injection](https://java-design-patterns.com/patterns/dependency-injection/): Facilitates decoupling layers by injecting dependencies rather than hard-coding them +* [Layered Architecture](https://java-design-patterns.com/patterns/layered-architecture/): Both separate concerns into distinct tiers but Clean Architecture emphasizes strict dependency rules +* [Hexagonal Architecture](https://java-design-patterns.com/patterns/hexagonal-architecture/): Similar focus on isolating core logic with ports and adapters + +## References and Credits + +* [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3UoKkaR) +* [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3wRnjp5) +* [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze) diff --git a/clean-architecture/etc/clean-architecture-flowchart.png b/clean-architecture/etc/clean-architecture-flowchart.png new file mode 100644 index 000000000000..043827f08844 Binary files /dev/null and b/clean-architecture/etc/clean-architecture-flowchart.png differ diff --git a/clean-architecture/etc/clean-architecture-mind-map.png b/clean-architecture/etc/clean-architecture-mind-map.png new file mode 100644 index 000000000000..59786d4a7c3e Binary files /dev/null and b/clean-architecture/etc/clean-architecture-mind-map.png differ diff --git a/clean-architecture/etc/cleanArchitectureUMLDiagram.PNG b/clean-architecture/etc/cleanArchitectureUMLDiagram.PNG new file mode 100644 index 000000000000..f107d34a14d8 Binary files /dev/null and b/clean-architecture/etc/cleanArchitectureUMLDiagram.PNG differ diff --git a/clean-architecture/etc/cleanArchitectureUMLDiagram.png b/clean-architecture/etc/cleanArchitectureUMLDiagram.png new file mode 100644 index 000000000000..f107d34a14d8 Binary files /dev/null and b/clean-architecture/etc/cleanArchitectureUMLDiagram.png differ diff --git a/clean-architecture/pom.xml b/clean-architecture/pom.xml new file mode 100644 index 000000000000..8222c6d9d80d --- /dev/null +++ b/clean-architecture/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + clean-architecture + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.cleanarchitecture.App + + + + + + + + + diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/App.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/App.java new file mode 100644 index 000000000000..4b56dcbbfd0f --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/App.java @@ -0,0 +1,71 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import lombok.extern.slf4j.Slf4j; + +/** + * Clean Architecture ensures separation of concerns by organizing code, into layers and making it + * scalable and maintainable. + * + *

    In the example there are Entities (Core Models) – Product, Cart, Order handle business logic. + * Use Cases (Application Logic) – ShoppingCartService manages operations like adding items and + * checkout. Interfaces & Adapters – Repositories (CartRepository, OrderRepository) abstract data + * handling, while controllers (CartController, OrderController) manage interactions. + */ +@Slf4j +public final class App { + + private App() { + throw new UnsupportedOperationException("Utility class"); + } + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(final String[] args) { + ProductRepository productRepository = new InMemoryProductRepository(); + CartRepository cartRepository = new InMemoryCartRepository(); + OrderRepository orderRepository = new InMemoryOrderRepository(); + + ShoppingCartService shoppingCartUseCase = + new ShoppingCartService(productRepository, cartRepository, orderRepository); + + CartController cartController = new CartController(shoppingCartUseCase); + OrderController orderController = new OrderController(shoppingCartUseCase); + + String userId = "user123"; + cartController.addItemToCart(userId, "1", 1); + cartController.addItemToCart(userId, "2", 2); + + Order order = orderController.checkout(userId); + LOGGER.info("Total: ${}", cartController.calculateTotal(userId)); + + LOGGER.info( + "Order placed! Order ID: {}, Total: ${}", order.getOrderId(), order.getTotalPrice()); + } +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/Cart.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/Cart.java new file mode 100644 index 000000000000..c4e65df94845 --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/Cart.java @@ -0,0 +1,64 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import lombok.Getter; + +/** + * Represents a shopping cart containing a product and its quantity. This class calculates the total + * price of the product based on its price and quantity. + */ +@Getter +public class Cart { + /** The product in the cart. It holds the product details such as name, price, and description. */ + private final Product product; + + /** + * The quantity of the product in the cart. It represents how many units of the product are added + * to the cart. + */ + private final int quantity; + + /** + * Constructs a new Cart instance with a specified product and quantity. + * + * @param prod the product to be added to the cart. + * @param qty the quantity of the product in the cart. + */ + public Cart(final Product prod, final int qty) { + this.product = prod; + this.quantity = qty; + } + + /** + * Calculates the total price of the products in the cart. The total price is the product's price + * multiplied by the quantity. + * + * @return the total price of the products in the cart. + */ + public double getTotalPrice() { + return product.getPrice() * quantity; + } +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/CartController.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/CartController.java new file mode 100644 index 000000000000..da93cc2a6d93 --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/CartController.java @@ -0,0 +1,77 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +/** + * Controller class for handling shopping cart operations. + * + *

    This class provides methods to add, remove, and calculate the total price of items in a user's + * shopping cart. + */ +public class CartController { + + /** Service layer responsible for cart operations. */ + private final ShoppingCartService shoppingCartUseCase; + + /** + * Constructs a CartController with the specified shopping cart service. + * + * @param shoppingCart The shopping cart service to handle cart operations. + */ + public CartController(final ShoppingCartService shoppingCart) { + this.shoppingCartUseCase = shoppingCart; + } + + /** + * Adds an item to the user's cart. + * + * @param userId The ID of the user. + * @param productId The ID of the product to be added. + * @param quantity The quantity of the product. + */ + public void addItemToCart(final String userId, final String productId, final int quantity) { + shoppingCartUseCase.addItemToCart(userId, productId, quantity); + } + + /** + * Removes an item from the user's cart. + * + * @param userId The ID of the user. + * @param productId The ID of the product to be removed. + */ + public void removeItemFromCart(final String userId, final String productId) { + shoppingCartUseCase.removeItemFromCart(userId, productId); + } + + /** + * Calculates the total cost of items in the user's cart. + * + * @param userId The ID of the user. + * @return The total price of all items in the cart. + */ + public double calculateTotal(final String userId) { + return shoppingCartUseCase.calculateTotal(userId); + } +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/CartRepository.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/CartRepository.java new file mode 100644 index 000000000000..844bc48345b4 --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/CartRepository.java @@ -0,0 +1,70 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import java.util.List; + +/** CartRepository. */ +public interface CartRepository { + /** + * Adds an item to the user's cart. + * + * @param userId The ID of the user. + * @param product The product to be added. + * @param quantity The quantity of the product. + */ + void addItemToCart(String userId, Product product, int quantity); + + /** + * Removes an item from the user's cart. + * + * @param userId The ID of the user. + * @param productId The ID of the product to be removed. + */ + void removeItemFromCart(String userId, String productId); + + /** + * Retrieves the list of items in the user's cart. + * + * @param userId The ID of the user. + * @return A list of items in the cart. + */ + List getItemsInCart(String userId); + + /** + * Calculates the total price of the items in the user's cart. + * + * @param userId The ID of the user. + * @return The total price of all items in the cart. + */ + double calculateTotal(String userId); + + /** + * Clears all items from the user's cart. + * + * @param userId The ID of the user. + */ + void clearCart(String userId); +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/InMemoryCartRepository.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/InMemoryCartRepository.java new file mode 100644 index 000000000000..2965cddd57f3 --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/InMemoryCartRepository.java @@ -0,0 +1,102 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Implementation of {@link CartRepository} that stores cart items in memory. + * + *

    This class maintains a map of user carts where each user has a list of cart items. + */ +public class InMemoryCartRepository implements CartRepository { + /** A map storing user carts with their respective cart items. */ + private final Map> userCarts = new HashMap<>(); + + /** + * Adds an item to the user's cart. + * + * @param userId The ID of the user. + * @param product The product to be added. + * @param quantity The quantity of the product. + */ + @Override + public void addItemToCart(final String userId, final Product product, final int quantity) { + List cart = userCarts.getOrDefault(userId, new ArrayList<>()); + cart.add(new Cart(product, quantity)); + userCarts.put(userId, cart); + } + + /** + * Removes an item from the user's cart. + * + * @param userId The ID of the user. + * @param productId The ID of the product to be removed. + */ + @Override + public void removeItemFromCart(final String userId, final String productId) { + List cart = userCarts.get(userId); + if (cart != null) { + cart.removeIf(item -> item.getProduct().getId().equals(productId)); + } + } + + /** + * Retrieves all items in the user's cart. + * + * @param userId The ID of the user. + * @return A list of {@link Cart} items in the user's cart. + */ + @Override + public List getItemsInCart(final String userId) { + return userCarts.getOrDefault(userId, new ArrayList<>()); + } + + /** + * Calculates the total price of items in the user's cart. + * + * @param userId The ID of the user. + * @return The total price of the cart. + */ + @Override + public double calculateTotal(final String userId) { + return userCarts.getOrDefault(userId, new ArrayList<>()).stream() + .mapToDouble(Cart::getTotalPrice) + .sum(); + } + + /** + * Clears all items from the user's cart. + * + * @param userId The ID of the user. + */ + @Override + public void clearCart(final String userId) { + userCarts.remove(userId); + } +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/InMemoryOrderRepository.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/InMemoryOrderRepository.java new file mode 100644 index 000000000000..b8a17cd6045a --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/InMemoryOrderRepository.java @@ -0,0 +1,49 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import java.util.ArrayList; +import java.util.List; + +/** + * An in-memory implementation of the {@link OrderRepository}. + * + *

    This class stores orders in a list, allowing orders to be saved but not persisted beyond the + * application's runtime. + */ +public class InMemoryOrderRepository implements OrderRepository { + /** A list to store orders in memory. */ + private final List orders = new ArrayList<>(); + + /** + * Saves an order to the in-memory repository. + * + * @param order The order to be saved. + */ + @Override + public void saveOrder(final Order order) { + orders.add(order); + } +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/InMemoryProductRepository.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/InMemoryProductRepository.java new file mode 100644 index 000000000000..c91677feeff5 --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/InMemoryProductRepository.java @@ -0,0 +1,71 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import java.util.HashMap; +import java.util.Map; + +/** + * In-memory implementation of the {@link ProductRepository} interface. + * + *

    This repository stores products in memory allowing retrieval by product ID. + */ +public class InMemoryProductRepository implements ProductRepository { + /** A map to store products by their unique product ID. */ + private final Map products = new HashMap<>(); + + /** + * The price of the Laptop in USD. + * + *

    Used in the in-memory product repository to define the cost of a Laptop. + */ + private static final double LAPTOP_PRICE = 1000.0; + + /** + * The price of the Smartphone in USD. + * + *

    Used in the in-memory product repository to define the cost of a Smartphone. + */ + private static final double SMARTPHONE_PRICE = 500.0; + + /** + * Constructs an {@code InMemoryProductRepository} and initializes it with some example products. + */ + public InMemoryProductRepository() { + products.put("1", new Product("1", "Laptop", LAPTOP_PRICE)); + products.put("2", new Product("2", "Smartphone", SMARTPHONE_PRICE)); + } + + /** + * Retrieves a product by its unique ID. + * + * @param productId The ID of the product to retrieve. + * @return The {@link Product} corresponding to the given ID {@code null} if not found. + */ + @Override + public Product getProductById(final String productId) { + return products.get(productId); + } +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/Order.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/Order.java new file mode 100644 index 000000000000..70bf058dc2eb --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/Order.java @@ -0,0 +1,58 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import java.util.List; +import lombok.Getter; + +/** + * Represents an order placed by a user containing the ordered items and total price. + * + *

    An order includes a unique order ID, a list of cart items and the total price of the order. + */ +@Getter +public class Order { + /** The unique identifier for this order. */ + private final String orderId; + + /** The list of items included in this order. */ + private final List items; + + /** The list of items included in this order. */ + private final double totalPrice; + + /** + * Constructs an {@code Order} with the given order ID and list of cart items. The total price is + * based on the individual item prices in the cart. + * + * @param id The unique identifier for the order. + * @param item The list of cart items included in the order. + */ + public Order(final String id, final List item) { + this.orderId = id; + this.items = item; + this.totalPrice = items.stream().mapToDouble(Cart::getTotalPrice).sum(); + } +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/OrderController.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/OrderController.java new file mode 100644 index 000000000000..d61dad322750 --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/OrderController.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +/** + * Controller for handling order-related operations. + * + *

    This class provides an endpoint for users to checkout their cart and place an order. + */ +public class OrderController { + /** Service for managing shopping cart operations. */ + private final ShoppingCartService shoppingCartUseCase; + + /** + * Constructs an {@code OrderController} with the given shopping cart service. + * + * @param shoppingCartUse The shopping cart service used to process orders. + */ + public OrderController(final ShoppingCartService shoppingCartUse) { + this.shoppingCartUseCase = shoppingCartUse; + } + + /** + * Processes the checkout for a given user and creates an order. + * + * @param userId The ID of the user checking out. + * @return The created {@link Order} after checkout. + */ + public Order checkout(final String userId) { + return shoppingCartUseCase.checkout(userId); + } +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/OrderRepository.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/OrderRepository.java new file mode 100644 index 000000000000..4c7276fcb53f --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/OrderRepository.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +/** + * Repository interface for managing order persistence. + * + *

    This interface defines the contract for storing orders in the system. + */ +public interface OrderRepository { + /** + * Saves an order to the repository. + * + * @param order The order to be saved. + */ + void saveOrder(Order order); +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/Product.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/Product.java new file mode 100644 index 000000000000..100613872865 --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/Product.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import lombok.Getter; + +/** Represents a product in the system. */ +@Getter +public class Product { + /** The unique identifier for the product. */ + private final String id; + + /** The name of the product. */ + private final String name; + + /** The price of the product. */ + private final double price; + + /** + * Constructs a new Product with the given details. + * + * @param pdtId The unique identifier of the product. + * @param firstName The name of the product. + * @param p The price of the product. + */ + public Product(final String pdtId, final String firstName, final double p) { + this.id = pdtId; + this.name = firstName; + this.price = p; + } +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/ProductRepository.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/ProductRepository.java new file mode 100644 index 000000000000..713b62e799bc --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/ProductRepository.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +/** Repository interface for handling product-related operations. */ +public interface ProductRepository { + /** + * Retrieves a product by its unique identifier. + * + * @param productId The unique ID of the product. + * @return The product corresponding to the given ID. + */ + Product getProductById(String productId); +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/ShoppingCartService.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/ShoppingCartService.java new file mode 100644 index 000000000000..cd74aa3145cf --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/ShoppingCartService.java @@ -0,0 +1,112 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import java.util.List; + +/** + * Service class for managing shopping cart operations. + * + *

    This class provides functionalities to add and remove items from the cart, calculate the total + * price, and handle checkout operations. + */ +public class ShoppingCartService { + /** Repository for managing product data. */ + private final ProductRepository productRepository; + + /** Repository for managing cart data. */ + private final CartRepository cartRepository; + + /** Repository for managing order data. */ + private final OrderRepository orderRepository; + + /** + * Constructs a ShoppingCartService with the required repositories. + * + * @param pdtRepository The repository to fetch product details. + * @param repository The repository to manage cart operations. + * @param ordRepository The repository to handle order persistence. + */ + public ShoppingCartService( + final ProductRepository pdtRepository, + final CartRepository repository, + final OrderRepository ordRepository) { + this.productRepository = pdtRepository; + this.cartRepository = repository; + this.orderRepository = ordRepository; + } + + /** + * Adds an item to the user's shopping cart. + * + * @param userId The ID of the user. + * @param productId The ID of the product to be added. + * @param quantity The quantity of the product. + */ + public void addItemToCart(final String userId, final String productId, final int quantity) { + Product product = productRepository.getProductById(productId); + if (product != null) { + cartRepository.addItemToCart(userId, product, quantity); + } + } + + /** + * Removes an item from the user's shopping cart. + * + * @param userId The ID of the user. + * @param productId The ID of the product to be removed. + */ + public void removeItemFromCart(final String userId, final String productId) { + cartRepository.removeItemFromCart(userId, productId); + } + + /** + * Calculates the total cost of items in the user's shopping cart. + * + * @param userId The ID of the user. + * @return The total price of all items in the cart. + */ + public double calculateTotal(final String userId) { + return cartRepository.calculateTotal(userId); + } + + /** + * Checks out the user's cart and creates an order. + * + *

    This method retrieves the cart items, generates an order ID, creates a new order, saves it, + * and clears the cart. + * + * @param userId The ID of the user. + * @return The created order containing purchased items. + */ + public Order checkout(final String userId) { + List items = cartRepository.getItemsInCart(userId); + String orderId = "ORDER-" + System.currentTimeMillis(); + Order order = new Order(orderId, items); + orderRepository.saveOrder(order); + cartRepository.clearCart(userId); + return order; + } +} diff --git a/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/package-info.java b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/package-info.java new file mode 100644 index 000000000000..7b8142f436ae --- /dev/null +++ b/clean-architecture/src/main/java/com/iluwatar/cleanarchitecture/package-info.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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. + */ +/** + * Provides classes and interfaces for the clean architecture pattern implementation. + * + *

    This package includes classes for managing products, carts, orders, repositories, and services + * for a shopping cart system, following the clean architecture principles. + */ +package com.iluwatar.cleanarchitecture; diff --git a/clean-architecture/src/test/java/com/iluwatar/cleanarchitecture/AppTest.java b/clean-architecture/src/test/java/com/iluwatar/cleanarchitecture/AppTest.java new file mode 100644 index 000000000000..86265d2886b7 --- /dev/null +++ b/clean-architecture/src/test/java/com/iluwatar/cleanarchitecture/AppTest.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/clean-architecture/src/test/java/com/iluwatar/cleanarchitecture/CartControllerTest.java b/clean-architecture/src/test/java/com/iluwatar/cleanarchitecture/CartControllerTest.java new file mode 100644 index 000000000000..c015c54c139c --- /dev/null +++ b/clean-architecture/src/test/java/com/iluwatar/cleanarchitecture/CartControllerTest.java @@ -0,0 +1,65 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.cleanarchitecture; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CartControllerTest { + + private CartController cartController; + + @BeforeEach + void setUp() { + ProductRepository productRepository = new InMemoryProductRepository(); + CartRepository cartRepository = new InMemoryCartRepository(); + OrderRepository orderRepository = new InMemoryOrderRepository(); + ShoppingCartService shoppingCartUseCase = + new ShoppingCartService(productRepository, cartRepository, orderRepository); + cartController = new CartController(shoppingCartUseCase); + } + + @Test + void testRemoveItemFromCart() { + cartController.addItemToCart("user123", "1", 1); + cartController.addItemToCart("user123", "2", 2); + + assertEquals(2000.0, cartController.calculateTotal("user123")); + + cartController.removeItemFromCart("user123", "1"); + + assertEquals(1000.0, cartController.calculateTotal("user123")); + } + + @Test + void testRemoveNonExistentItem() { + cartController.addItemToCart("user123", "2", 2); + cartController.removeItemFromCart("user123", "999"); + + assertEquals(1000.0, cartController.calculateTotal("user123")); + } +} diff --git a/client-session/README.md b/client-session/README.md new file mode 100644 index 000000000000..e693ef7db977 --- /dev/null +++ b/client-session/README.md @@ -0,0 +1,147 @@ +--- +title: "Client-Session Pattern in Java: Streamlining Client Data Across Sessions" +shortTitle: Client Session +description: "Explore the Client Session design pattern in Java. Learn how to manage user state and data across multiple requests for seamless, personalized web application experiences." +category: Behavioral +language: en +tags: + - Client-server + - Session management + - State tracking + - Web development +--- + +## Also known as + +* User Session + +## Intent of Client Session Design Pattern + +The Client Session design pattern is essential for web development involving client-server interactions. It aims to maintain a user's state and data across multiple requests within a web application, ensuring a continuous and personalized user experience. This pattern helps in creating a seamless user experience by managing user state and data effectively across different sessions, crucial for modern web applications. + +## Detailed Explanation of Client Session Pattern with Real-World Examples + +Real-world example + +> A real-world example of the Client Session pattern is a library membership system. When a member logs in, the system starts a session to track their borrowing activities. This session holds data such as the member's ID, current borrowed books, due dates, and any fines. As the member browses the catalog, borrows books, or returns them, the session maintains this stateful information, ensuring the member's interactions are consistent and personalized until they log out or the session expires. This approach helps the library system manage user-specific data efficiently across multiple interactions, providing a seamless and personalized experience for the members. + +In plain words + +> The Client Session pattern manages user-specific data across multiple requests within a web application to maintain continuity and personalization. + +Wikipedia says + +> The client-server model on Wikipedia describes a system where client devices request services and resources from centralized servers. This model is crucial in web applications where client sessions are used to manage user-specific data across multiple requests. For example, when a bank customer accesses online banking services, their login credentials and session state are managed by the web server to maintain continuity of their interactions. + +Sequence diagram + +![Client Session sequence diagram](./etc/client-session-sequence-diagram.png) + +## Programmatic Example of Client Session Pattern in Java + +The Client Session design pattern is a behavioral design pattern that maintains a user's state and data across multiple requests within a web application, ensuring a continuous and personalized user experience. This pattern is commonly used in web applications where user-specific data needs to be managed across multiple requests. + +In the given code, we have a `Server` class and a `Session` class. The `Server` class represents the server that processes incoming requests and assigns sessions to clients. The `Session` class represents a session that is assigned to a client. + +```java +// The Server class represents the server that processes incoming requests and assigns sessions to clients. +public class Server { + private String host; + private int port; + + public Server(String host, int port) { + this.host = host; + this.port = port; + } + + // Other methods... + + // This method returns a new session for a client. + public Session getSession(String name) { + return new Session(name, "ClientName"); + } + + // This method processes a request from a client. + public void process(Request request) { + // Process the request... + } +} + +// The Session class represents a session that is assigned to a client. +public class Session { + private String id; + private String clientName; + + public Session(String id, String clientName) { + this.id = id; + this.clientName = clientName; + } + + // Other methods... +} +``` + +In the `main` method, we create an instance of `Server`, create two sessions for two different clients, and then pass these sessions to the server in the request along with the data. The server is then able to interpret the client based on the session associated with it. + +```java +public class App { + public static void main(String[] args) { + var server = new Server("localhost", 8080); + var session1 = server.getSession("Session1"); + var session2 = server.getSession("Session2"); + var request1 = new Request("Data1", session1); + var request2 = new Request("Data2", session2); + server.process(request1); + server.process(request2); + } +} +``` + +In this example, the `Server` class is responsible for creating and managing sessions for clients, and the `Session` class represents the client's session. The `Request` class represents a request from a client, which includes the client's session and data. The server processes the request based on the client's session. + +Running the program produces the following console output: + +``` +19:28:49.152 [main] INFO com.iluwatar.client.session.Server -- Processing Request with client: Session1 data: Data1 +19:28:49.154 [main] INFO com.iluwatar.client.session.Server -- Processing Request with client: Session2 data: Data2 +``` + +## When to Use the Client Session Pattern in Java + +Use the client state pattern when: + +* Web applications requiring user authentication and authorization. +* Applications needing to track user activities and preferences over multiple requests or visits. +* Systems where server resources need to be optimized by offloading state management to the client side. + +## Real-World Applications of Client Session Pattern in Java + +* E-commerce websites to track shopping cart contents across sessions. +* Online platforms that offer personalized content based on user preferences and history. +* Web applications requiring user login to access personalized or secured content. + +## Benefits and Trade-offs of Client Session Pattern + +Benefits: + +* Improved server performance by reducing the need to store user state on the server. +* Enhanced user experience through personalized content and seamless navigation across different parts of the application. +* Flexibility in managing sessions through various client-side storage mechanisms (e.g., cookies, Web Storage API). + +Trade-offs: + +* Potential security risks if sensitive information is stored in client sessions without proper encryption and validation. +* Dependence on client-side capabilities and settings, such as cookie policies, which can vary across browsers and user configurations. +* Increased complexity in session management logic, especially in handling session expiration, renewal, and synchronization across multiple devices or tabs. + +## Related Patterns + +* Server Session: Often used in conjunction with the Client Session pattern to provide a balance between client-side efficiency and server-side control. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Ensuring a single instance of a user's session throughout the application. +* [State](https://java-design-patterns.com/patterns/state/): Managing state transitions in a session, such as authenticated, guest, or expired states. + +## References and Credits + +* [Professional Java for Web Applications](https://amzn.to/4aazY59) +* [Securing Web Applications with Spring Security](https://amzn.to/3PCCEA1) +* [Client Session State Design Pattern: Explained Simply (Ram N Java)](https://www.youtube.com/watch?v=ycOSj9g41pc) diff --git a/client-session/etc/client-session-sequence-diagram.png b/client-session/etc/client-session-sequence-diagram.png new file mode 100644 index 000000000000..7d1282a9bbd9 Binary files /dev/null and b/client-session/etc/client-session-sequence-diagram.png differ diff --git a/client-session/etc/client-session.urm.puml b/client-session/etc/client-session.urm.puml new file mode 100644 index 000000000000..eea5ce8a9054 --- /dev/null +++ b/client-session/etc/client-session.urm.puml @@ -0,0 +1,51 @@ +@startuml +package com.iluwatar.client.session { + class App { + + App() + + main(args : String[]) {static} + } + class Request { + - data : String + - session : Session + + Request(data : String, session : Session) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getData() : String + + getSession() : Session + + hashCode() : int + + setData(data : String) + + setSession(session : Session) + + toString() : String + } + class Server { + - LOGGER : Logger {static} + - host : String + - port : int + + Server(host : String, port : int) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getHost() : String + + getPort() : int + + getSession(name : String) : Session + + hashCode() : int + + process(request : Request) + + setHost(host : String) + + setPort(port : int) + + toString() : String + } + class Session { + - clientName : String + - id : String + + Session(id : String, clientName : String) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getClientName() : String + + getId() : String + + hashCode() : int + + setClientName(clientName : String) + + setId(id : String) + + toString() : String + } +} +Request --> "-session" Session +@enduml \ No newline at end of file diff --git a/client-session/pom.xml b/client-session/pom.xml new file mode 100644 index 000000000000..1b2ea4564ff9 --- /dev/null +++ b/client-session/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + client-session + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.client.session.App + + + + + + + + + diff --git a/client-session/src/main/java/com/iluwatar/client/session/App.java b/client-session/src/main/java/com/iluwatar/client/session/App.java new file mode 100644 index 000000000000..8f744353ed1b --- /dev/null +++ b/client-session/src/main/java/com/iluwatar/client/session/App.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.client.session; + +/** + * The Client-Session pattern allows the session data to be stored on the client side and send this + * data to the server with each request. + * + *

    In this example, The {@link Server} class represents the server that would process the + * incoming {@link Request} and also assign {@link Session} to a client. Here one instance of Server + * is created. The we create two sessions for two different clients. These sessions are then passed + * on to the server in the request along with the data. The server is then able to interpret the + * client based on the session associated with it. + */ +public class App { + + /** + * Program entry point. + * + * @param args Command line args + */ + public static void main(String[] args) { + var server = new Server("localhost", 8080); + var session1 = server.getSession("Session1"); + var session2 = server.getSession("Session2"); + var request1 = new Request("Data1", session1); + var request2 = new Request("Data2", session2); + server.process(request1); + server.process(request2); + } +} diff --git a/client-session/src/main/java/com/iluwatar/client/session/Request.java b/client-session/src/main/java/com/iluwatar/client/session/Request.java new file mode 100644 index 000000000000..e47ed2775ac4 --- /dev/null +++ b/client-session/src/main/java/com/iluwatar/client/session/Request.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.client.session; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** The Request class which contains the Session details and data. */ +@Data +@AllArgsConstructor +public class Request { + + private String data; + + private Session session; +} diff --git a/client-session/src/main/java/com/iluwatar/client/session/Server.java b/client-session/src/main/java/com/iluwatar/client/session/Server.java new file mode 100644 index 000000000000..13a43a2dda81 --- /dev/null +++ b/client-session/src/main/java/com/iluwatar/client/session/Server.java @@ -0,0 +1,67 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.client.session; + +import java.util.UUID; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; + +/** + * The Server class. The client communicates with the server and request processing and getting a + * new session. + */ +@Slf4j +@Data +@AllArgsConstructor +public class Server { + private String host; + + private int port; + + /** + * Creates a new session. + * + * @param name name of the client + * @return Session Object + */ + public Session getSession(String name) { + return new Session(UUID.randomUUID().toString(), name); + } + + /** + * Processes a request based on the session. + * + * @param request Request object with data and Session + */ + public void process(Request request) { + LOGGER.info( + "Processing Request with client: " + + request.getSession().getClientName() + + " data: " + + request.getData()); + } +} diff --git a/client-session/src/main/java/com/iluwatar/client/session/Session.java b/client-session/src/main/java/com/iluwatar/client/session/Session.java new file mode 100644 index 000000000000..a7639485b83c --- /dev/null +++ b/client-session/src/main/java/com/iluwatar/client/session/Session.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.client.session; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * The Session class. Each client get assigned a Session which is then used for further + * communications. + */ +@Data +@AllArgsConstructor +public class Session { + + /** Session id. */ + private String id; + + /** Client name. */ + private String clientName; +} diff --git a/client-session/src/test/java/com/iluwatar/client/session/AppTest.java b/client-session/src/test/java/com/iluwatar/client/session/AppTest.java new file mode 100644 index 000000000000..63951ae48ae3 --- /dev/null +++ b/client-session/src/test/java/com/iluwatar/client/session/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.client.session; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void appStartsWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java b/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java new file mode 100644 index 000000000000..0037ca6339fb --- /dev/null +++ b/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.client.session; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class ServerTest { + + @Test + void checkGetSession() { + Server server = new Server("localhost", 8080); + Session session = server.getSession("Session"); + assertEquals("Session", session.getClientName()); + } +} diff --git a/collecting-parameter/README.md b/collecting-parameter/README.md new file mode 100644 index 000000000000..89c37e79bfb8 --- /dev/null +++ b/collecting-parameter/README.md @@ -0,0 +1,161 @@ +--- +title: "Collecting Parameter Pattern in Java: Mastering Efficient Parameter Handling" +shortTitle: Collecting Parameter +description: "Discover how the Collecting Parameter design pattern simplifies Java method calls by aggregating multiple parameters into a single collection object. Enhance code readability and maintainability with practical examples and real-world applications." +category: Behavioral +language: en +tag: + - Accumulation + - Data processing + - Data transfer + - Generic +--- + +## Also known as + +* Collector +* Accumulator + +## Intent of Collecting Parameter Design Pattern + +The Collecting Parameter pattern in Java design patterns aims to simplify method calls by aggregating multiple parameters into a single collection object. This pattern is particularly effective for methods that collect information by passing a single collection object through various method calls. Each method can then add results to this collection, instead of creating its own collection. This approach enhances code readability and maintainability, optimizing the process of information collection in Java programming. + +## Detailed Explanation of Collecting Parameter Pattern with Real-World Examples + +Real-world example + +> In software development, the Collecting Parameter pattern provides significant benefits by optimizing method calls and improving code maintainability. +> +> Imagine a scenario in a restaurant where a waiter needs to take an order from a customer. Instead of noting down each item separately (e.g., appetizer, main course, dessert, drink), the waiter uses an order form that collects all the items into a single document. This order form simplifies the communication between the waiter and the kitchen staff by aggregating all the details into one place. Similarly, in software, the Collecting Parameter pattern aggregates multiple parameters into a single object, streamlining method calls and improving code readability and maintainability. + +In plain words + +> The Collecting Parameter pattern simplifies method calls by encapsulating multiple parameters into a single object. + +Wikipedia says + +> In the Collecting Parameter idiom a collection (list, map, etc.) is passed repeatedly as a parameter to a method which adds items to the collection. + +Flowchart + +![Collecting Parameter flowchart](./etc/collecting-parameter-flowchart.png) + +## Programmatic Example of Collecting Parameter Pattern in Java + +Within a large corporate building, there exists a global printer queue that is a collection of all the printing jobs that are currently pending. Various floors contain different models of printers, each having a different printing policy. We must construct a program that can continually add appropriate printing jobs to a collection, which is called the collecting parameter. + +The following business rules are implemented: + +* If an A4 paper is coloured, it must also be single-sided. All other non-coloured papers are accepted +* A3 papers must be non-coloured and single-sided +* A2 papers must be single-page, single-sided, and non-coloured + +Let's see the implementation first and explain afterward. + +```java +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + + public static void main(String[] args) { + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A2, 5, false, false)); + + var result = new LinkedList(); + + addValidA4Papers(result); + addValidA3Papers(result); + addValidA2Papers(result); + } + + public static void addValidA4Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A4)) { + var isColouredAndSingleSided = nextItem.isColour && !nextItem.isDoubleSided; + if (isColouredAndSingleSided || !nextItem.isColour) { + printerItemsCollection.add(nextItem); + } + } + } + } + + public static void addValidA3Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A3)) { + var isNotColouredAndSingleSided = !nextItem.isColour && !nextItem.isDoubleSided; + if (isNotColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } + } + } + } + + public static void addValidA2Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A2)) { + var isNotColouredSingleSidedAndOnePage = nextItem.pageCount == 1 && !nextItem.isDoubleSided + && !nextItem.isColour; + if (isNotColouredSingleSidedAndOnePage) { + printerItemsCollection.add(nextItem); + } + } + } + } +} +``` + +This `App` class is the main entry point of the application. It uses the Collecting Parameter design pattern to filter print jobs based on certain policies. + +1. **Initialization**: The `printerQueue` is initialized with three print jobs of different paper sizes (A4, A3, A2). + +2. **Creating the Collecting Parameter**: A `LinkedList` named `result` is created to store the print jobs that meet the policy requirements. + +3. **Adding Valid Jobs to the Collecting Parameter**: The `addValidA4Papers`, `addValidA3Papers`, and `addValidA2Papers` methods are called. These methods iterate over the `printerQueue` and add the print jobs that meet the policy requirements to the `result` list. + +The `result` list, which is the collecting parameter, accumulates the valid print jobs as it is passed from method to method. This is the essence of the Collecting Parameter design pattern. + +Utilizing the Collecting Parameter pattern in Java design patterns leads to more efficient method calls and improved overall code structure. + +## When to Use the Collecting Parameter Pattern in Java + +This pattern is useful for managing parameters in Java coding practices, ensuring efficient code refactoring and enhanced readability. + +* Use when a method needs to accept a large number of parameters, making the method signature unwieldy. +* Use when the same group of parameters is passed to multiple methods, reducing redundancy and potential errors. +* Use to improve the readability and maintainability of the code. + +## Collecting Parameter Pattern Java Tutorials + +* [Refactoring To Patterns (Joshua Kerivsky)](http://www.tarrani.net/RefactoringToPatterns.pdf) +* [Smalltalk Best Practice Patterns (Kent Beck)](https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf) + +## Real-World Applications of Collecting Parameter Pattern in Java + +* Use when a method needs to accept a large number of parameters, making the method signature unwieldy. +* Use when the same group of parameters is passed to multiple methods, reducing redundancy and potential errors. +* Use to improve the readability and maintainability of the code. + +## Benefits and Trade-offs of Collecting Parameter Pattern + +Benefits: + +* Improves code readability by reducing the number of parameters in method signatures. +* Facilitates the reuse of parameter sets across different methods. +* Enhances maintainability by centralizing the parameter structure. + +Trade-offs: + +* Introduces an additional class, which may increase complexity if not managed properly. +* Can lead to over-generalization if the parameter object becomes too large or unwieldy. + +## Related Java Design Patterns + +* [Command](https://java-design-patterns.com/patterns/command/): Commands may utilize Collecting Parameter to aggregate results from multiple operations executed by the command objects. +* [Composite](https://java-design-patterns.com/patterns/composite/): Can be used in tandem with Collecting Parameter when dealing with hierarchical structures, allowing results to be collected across a composite structure. +* [Visitor](https://java-design-patterns.com/patterns/visitor/): Often used together, where Visitor handles traversal and operations on a structure, and Collecting Parameter accumulates the results. + +## References and Credits + +* [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/4aApLP0) +* [Refactoring: Improving the Design of Existing Code](https://amzn.to/3TVEgaB) +* [Collecting Parameter (WikiWikiWeb)](https://wiki.c2.com/?CollectingParameter) diff --git a/collecting-parameter/etc/collecting-parameter-flowchart.png b/collecting-parameter/etc/collecting-parameter-flowchart.png new file mode 100644 index 000000000000..dcab61c2eb5d Binary files /dev/null and b/collecting-parameter/etc/collecting-parameter-flowchart.png differ diff --git a/collecting-parameter/etc/collecting-parameter.urm.png b/collecting-parameter/etc/collecting-parameter.urm.png new file mode 100644 index 000000000000..785d6ecc2da1 Binary files /dev/null and b/collecting-parameter/etc/collecting-parameter.urm.png differ diff --git a/collecting-parameter/etc/collecting-parameter.urm.puml b/collecting-parameter/etc/collecting-parameter.urm.puml new file mode 100644 index 000000000000..06320fa022ee --- /dev/null +++ b/collecting-parameter/etc/collecting-parameter.urm.puml @@ -0,0 +1,39 @@ +@startuml +package com.iluwatar.collectingparameter { + class App { + ~ printerQueue : PrinterQueue {static} + + App() + + addValidA2Papers(printerItemsCollection : Queue) {static} + + addValidA3Papers(printerItemsCollection : Queue) {static} + + addValidA4Papers(printerItemsCollection : Queue) {static} + + main(args : String[]) {static} + } + ~enum PaperSizes { + + A2 {static} + + A3 {static} + + A4 {static} + + valueOf(name : String) : PaperSizes {static} + + values() : PaperSizes[] {static} + } + class PrinterItem { + ~ isColour : boolean + ~ isDoubleSided : boolean + ~ pageCount : int + ~ paperSize : PaperSizes + + PrinterItem(paperSize : PaperSizes, pageCount : int, isDoubleSided : boolean, isColour : boolean) + } + class PrinterQueue { + ~ currentInstance : PrinterQueue {static} + - printerItemQueue : Queue + - PrinterQueue() + + addPrinterItem(printerItem : PrinterItem) + + emptyQueue() + + getInstance() : PrinterQueue {static} + + getPrinterQueue() : Queue + } +} +PrinterQueue --> "-currentInstance" PrinterQueue +PrinterQueue --> "-printerItemQueue" PrinterItem +App --> "-printerQueue" PrinterQueue +PrinterItem --> "-paperSize" PaperSizes +@enduml \ No newline at end of file diff --git a/collecting-parameter/pom.xml b/collecting-parameter/pom.xml new file mode 100644 index 000000000000..8c5c015468a4 --- /dev/null +++ b/collecting-parameter/pom.xml @@ -0,0 +1,62 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + collecting-parameter + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.collectingparameter.App + + + + + + + + + diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java new file mode 100644 index 000000000000..d505970fb84f --- /dev/null +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java @@ -0,0 +1,140 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectingparameter; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * The Collecting Parameter Design Pattern aims to return a result that is the collaborative result + * of several methods. This design pattern uses a 'collecting parameter' that is passed to several + * functions, accumulating results as it travels from method-to-method. This is different to the + * Composed Method design pattern, where a single collection is modified via several methods. + * + *

    This example is inspired by Kent Beck's example in his book, 'Smalltalk Best Practice + * Patterns'. The context for this situation is that there is a single printer queue {@link + * PrinterQueue} that holds numerous print jobs {@link PrinterItem} that must be distributed to + * various print centers. Each print center has its own requirements and printing limitations. In + * this example, the following requirements are: If an A4 document is coloured, it must also be + * single-sided. All other non-coloured A4 documents are accepted. All A3 documents must be + * non-coloured and single sided. All A2 documents must be a single page, single sided, and + * non-coloured. + * + *

    A collecting parameter (the result variable) is used to filter the global printer queue so + * that it meets the requirements for this centre, + */ +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + /* + Initialising the printer queue with jobs + */ + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A2, 5, false, false)); + + /* + This variable is the collecting parameter, and will store the policy abiding print jobs. + */ + var result = new LinkedList(); + + /* + Adding A4, A3, and A2 papers that obey the policy + */ + addValidA4Papers(result); + addValidA3Papers(result); + addValidA2Papers(result); + } + + /** + * Adds A4 document jobs to the collecting parameter according to some policy that can be whatever + * the client (the print center) wants. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addValidA4Papers(Queue printerItemsCollection) { + /* + Iterate through the printer queue, and add A4 papers according to the correct policy to the collecting parameter, + which is 'printerItemsCollection' in this case. + */ + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A4)) { + var isColouredAndSingleSided = nextItem.isColour && !nextItem.isDoubleSided; + if (isColouredAndSingleSided || !nextItem.isColour) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A3 document jobs to the collecting parameter according to some policy that can be whatever + * the client (the print center) wants. The code is similar to the 'addA4Papers' method. The code + * can be changed to accommodate the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addValidA3Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A3)) { + + // Encoding the policy into a Boolean: the A3 paper cannot be coloured and double-sided at + // the same time + var isNotColouredAndSingleSided = !nextItem.isColour && !nextItem.isDoubleSided; + if (isNotColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A2 document jobs to the collecting parameter according to some policy that can be whatever + * the client (the print center) wants. The code is similar to the 'addA4Papers' method. The code + * can be changed to accommodate the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addValidA2Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A2)) { + + // Encoding the policy into a Boolean: the A2 paper must be single page, single-sided, and + // non-coloured. + var isNotColouredSingleSidedAndOnePage = + nextItem.pageCount == 1 && !nextItem.isDoubleSided && !nextItem.isColour; + if (isNotColouredSingleSidedAndOnePage) { + printerItemsCollection.add(nextItem); + } + } + } + } +} diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PaperSizes.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PaperSizes.java new file mode 100644 index 000000000000..cf706acd8872 --- /dev/null +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PaperSizes.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectingparameter; + +enum PaperSizes { + A2, + A3, + A4 +} diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java new file mode 100644 index 000000000000..5669f744dd84 --- /dev/null +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectingparameter; + +import java.util.Objects; + +/** This class represents a Print Item, that should be added to the queue. */ +public class PrinterItem { + PaperSizes paperSize; + int pageCount; + boolean isDoubleSided; + boolean isColour; + + /** The {@link PrinterItem} constructor. */ + public PrinterItem(PaperSizes paperSize, int pageCount, boolean isDoubleSided, boolean isColour) { + if (!Objects.isNull(paperSize)) { + this.paperSize = paperSize; + } else { + throw new IllegalArgumentException(); + } + + if (pageCount > 0) { + this.pageCount = pageCount; + } else { + throw new IllegalArgumentException(); + } + + this.isColour = isColour; + this.isDoubleSided = isDoubleSided; + } +} diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java new file mode 100644 index 000000000000..8cdfc84107a3 --- /dev/null +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java @@ -0,0 +1,73 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectingparameter; + +import java.util.LinkedList; +import java.util.Objects; +import java.util.Queue; + +/** + * This class represents a singleton Printer Queue. It contains a queue that can be filled up with + * {@link PrinterItem}. + */ +public class PrinterQueue { + + static PrinterQueue currentInstance = null; + private final Queue printerItemQueue; + + /** + * This class is a singleton. The getInstance method will ensure that only one instance exists at + * a time. + */ + public static PrinterQueue getInstance() { + if (Objects.isNull(currentInstance)) { + currentInstance = new PrinterQueue(); + } + return currentInstance; + } + + /** Empty the printer queue. */ + public void emptyQueue() { + currentInstance.getPrinterQueue().clear(); + } + + /** Private constructor prevents instantiation, unless using the getInstance() method. */ + private PrinterQueue() { + printerItemQueue = new LinkedList<>(); + } + + public Queue getPrinterQueue() { + return currentInstance.printerItemQueue; + } + + /** + * Adds a single print job to the queue. + * + * @param printerItem The printing job to be added to the queue + */ + public void addPrinterItem(PrinterItem printerItem) { + currentInstance.getPrinterQueue().add(printerItem); + } +} diff --git a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java new file mode 100644 index 000000000000..8597c4d6f2cb --- /dev/null +++ b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectingparameter; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + /** Checks whether {@link App} executes without throwing exception */ + @Test + void executesWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java new file mode 100644 index 000000000000..c53c5ac2c0ed --- /dev/null +++ b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java @@ -0,0 +1,78 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectingparameter; + +import java.util.LinkedList; +import java.util.Queue; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +class CollectingParameterTest { + + @Test + @Timeout(1000) + void testCollectingParameter() { + PrinterQueue printerQueue = PrinterQueue.getInstance(); + printerQueue.emptyQueue(); + + PrinterItem item1 = new PrinterItem(PaperSizes.A4, 1, false, true); + PrinterItem item2 = new PrinterItem(PaperSizes.A4, 10, true, false); + PrinterItem item3 = new PrinterItem(PaperSizes.A4, 4, true, true); + PrinterItem item4 = new PrinterItem(PaperSizes.A3, 9, false, false); + PrinterItem item5 = new PrinterItem(PaperSizes.A3, 3, true, true); + PrinterItem item6 = new PrinterItem(PaperSizes.A3, 3, false, true); + PrinterItem item7 = new PrinterItem(PaperSizes.A3, 3, true, false); + PrinterItem item8 = new PrinterItem(PaperSizes.A2, 1, false, false); + PrinterItem item9 = new PrinterItem(PaperSizes.A2, 2, false, false); + PrinterItem item10 = new PrinterItem(PaperSizes.A2, 1, true, false); + PrinterItem item11 = new PrinterItem(PaperSizes.A2, 1, false, true); + + printerQueue.addPrinterItem(item1); + printerQueue.addPrinterItem(item2); + printerQueue.addPrinterItem(item3); + printerQueue.addPrinterItem(item4); + printerQueue.addPrinterItem(item5); + printerQueue.addPrinterItem(item6); + printerQueue.addPrinterItem(item7); + printerQueue.addPrinterItem(item8); + printerQueue.addPrinterItem(item9); + printerQueue.addPrinterItem(item10); + printerQueue.addPrinterItem(item11); + + Queue result = new LinkedList<>(); + App.addValidA4Papers(result); + App.addValidA3Papers(result); + App.addValidA2Papers(result); + + Queue testResult = new LinkedList<>(); + testResult.add(item1); + testResult.add(item2); + testResult.add(item4); + testResult.add(item8); + + Assertions.assertArrayEquals(testResult.toArray(), result.toArray()); + } +} diff --git a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java new file mode 100644 index 000000000000..8c03eea90c95 --- /dev/null +++ b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java @@ -0,0 +1,56 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectingparameter; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +class PrinterQueueTest { + + @Test + @Timeout(1000) + void singletonTest() { + PrinterQueue printerQueue1 = PrinterQueue.getInstance(); + PrinterQueue printerQueue2 = PrinterQueue.getInstance(); + assertSame(printerQueue1, printerQueue2); + } + + @Test() + @Timeout(1000) + void negativePageCount() throws IllegalArgumentException { + Assertions.assertThrows( + IllegalArgumentException.class, () -> new PrinterItem(PaperSizes.A4, -1, true, true)); + } + + @Test() + @Timeout(1000) + void nullPageSize() throws IllegalArgumentException { + Assertions.assertThrows( + IllegalArgumentException.class, () -> new PrinterItem(null, 1, true, true)); + } +} diff --git a/collection-pipeline/README.md b/collection-pipeline/README.md new file mode 100644 index 000000000000..33d207922828 --- /dev/null +++ b/collection-pipeline/README.md @@ -0,0 +1,126 @@ +--- +title: "Collection Pipeline Pattern in Java: Streamlining Data Manipulation" +shortTitle: Collection Pipeline +description: "Learn how the Collection Pipeline design pattern in Java enhances data processing by chaining operations in a sequence. This pattern promotes a declarative approach, improving code readability, maintainability, and performance." +category: Functional +language: en +tag: + - Functional decomposition + - Data processing + - Data transformation + - Reactive +--- + +## Intent of Collection Pipeline Design Pattern + +The Collection Pipeline design pattern in Java processes collections of data by chaining operations in a sequence. Utilizing the Java Stream API, it transforms data declaratively, focusing on what should be done rather than how. + +## Detailed Explanation of Collection Pipeline Pattern with Real-World Examples + +Real-world example + +> Imagine a real-world example of a factory assembly line for manufacturing cars. In this assembly line, each station performs a specific task on the car chassis, such as installing the engine, painting the body, attaching the wheels, and inspecting the final product. Each station takes the output from the previous station and adds its own processing step. This sequence of operations is analogous to the Collection Pipeline design pattern, where each step in the pipeline transforms the data and passes it on to the next step, ensuring an efficient and organized workflow. + +In plain words + +> The Collection Pipeline pattern in Java involves processing data through a series of operations using the Stream API. Each operation transforms the data in sequence, akin to an assembly line in a factory, promoting functional programming principles. + +Wikipedia says + +> In software engineering, a pipeline consists of a chain of processing elements (processes, threads, coroutines, functions, etc.), arranged so that the output of each element is the input of the next; the name is by analogy to a physical pipeline. Usually some amount of buffering is provided between consecutive elements. The information that flows in these pipelines is often a stream of records, bytes, or bits, and the elements of a pipeline may be called filters; this is also called the pipe(s) and filters design pattern. Connecting elements into a pipeline is analogous to function composition. + +Flowchart + +![Collection Pipeline flowchart](./etc/collection-pipeline-flowchart.png) + +## Programmatic Example of Collection Pipeline Pattern in Java + +The Collection Pipeline is a programming pattern where you organize some computation as a sequence of operations which compose by taking a collection as output of one operation and feeding it into the next. + +Here's a programmatic example of the Collection Pipeline design pattern: + +**Step 1: Filtering** + +We start with a list of `Car` objects and we want to filter out those that were manufactured after the year 2000. This is done using the `stream()` method to create a stream from the list, the `filter()` method to filter out the cars we want, and the `collect()` method to collect the results into a new list. + +```java +public static List getModelsAfter2000(List cars){ + return cars.stream() + .filter(car -> car.getYear() > 2000) // Filter cars manufactured after 2000 + .sorted(comparing(Car::getYear)) // Sort the cars by year + .map(Car::getModel) // Get the model of each car + .collect(toList()); // Collect the results into a new list +} +``` + +**Step 2: Grouping** + +Next, we want to group the cars by their category. This is done using the `groupingBy` collector. + +```java +public static Map> getGroupingOfCarsByCategory(List cars){ + return cars.stream() + .collect(groupingBy(Car::getCategory)); // Group cars by category +} +``` + +**Step 3: Filtering, Sorting and Transforming** + +Finally, we want to filter the cars owned by a person to only include sedans, sort them by date, and then transform the sorted cars into a list of `Car` objects. + +```java +public static List getSedanCarsOwnedSortedByDate(List persons){ + return persons.stream() + .flatMap(person -> person.getCars().stream()) // Flatten the list of cars owned by each person + .filter(car -> Category.SEDAN.equals(car.getCategory())) // Filter to only include sedans + .sorted(comparing(Car::getDate)) // Sort the cars by date + .collect(toList()); // Collect the results into a new list +} +``` + +In each of these methods, the Collection Pipeline pattern is used to perform a series of operations on the collection of cars in a declarative manner, which improves readability and maintainability. + +## When to Use the Collection Pipeline Pattern in Java + +The Collection Pipeline pattern is ideal for Java developers handling bulk data operations, including filtering, mapping, sorting, and reducing collections, particularly with Java 8+ Stream API. + +Use the Collection Pipeline pattern: + +* When you need to perform a series of transformations on a collection of data. +* When you want to improve readability and maintainability of complex data processing code. +* When working with large datasets where intermediate results should not be stored in memory. + +## Real-World Applications of Collection Pipeline Pattern in Java + +* LINQ in .NET +* Stream API in Java 8+ +* Collections in modern functional languages (e.g., Haskell, Scala) +* Database query builders and ORM frameworks + +## Benefits and Trade-offs of Collection Pipeline Pattern + +Benefits: + +* Readability: The code is more readable and declarative, making it easier to understand the sequence of operations. +* Maintainability: Easier to modify or extend the pipeline with additional operations. +* Reusability: Common operations can be abstracted into reusable functions. +* Lazy Evaluation: Some implementations allow for operations to be lazily evaluated, improving performance. + +Trade-offs: + +* Performance Overhead: Chaining multiple operations can introduce overhead compared to traditional loops, especially for short pipelines or very large collections. +* Debugging Difficulty: Debugging a chain of operations might be more challenging due to the lack of intermediate variables. +* Limited to Collections: Primarily focused on collections, and its utility might be limited outside of collection processing. + +## Related Java Design Patterns + +* [Builder](https://java-design-patterns.com/patterns/builder/): Similar fluent interface style but used for object construction. +* [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Conceptually similar in chaining handlers, but applied to object requests rather than data collection processing. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Can be used within a pipeline stage to encapsulate different algorithms that can be selected at runtime. + +## References and Credits + +* [Functional Programming in Scala](https://amzn.to/4cEo6K2) +* [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3THp4wy) +* [Refactoring: Improving the Design of Existing Code](https://amzn.to/3VDMWDO) +* [Collection Pipeline (Martin Fowler)](https://martinfowler.com/articles/collection-pipeline/) diff --git a/collection-pipeline/etc/collection-pipeline-flowchart.png b/collection-pipeline/etc/collection-pipeline-flowchart.png new file mode 100644 index 000000000000..48ee51002129 Binary files /dev/null and b/collection-pipeline/etc/collection-pipeline-flowchart.png differ diff --git a/collection-pipeline/etc/collection-pipeline.urm.png b/collection-pipeline/etc/collection-pipeline.urm.png new file mode 100644 index 000000000000..074dffe7b14e Binary files /dev/null and b/collection-pipeline/etc/collection-pipeline.urm.png differ diff --git a/collection-pipeline/etc/collection-pipeline.urm.puml b/collection-pipeline/etc/collection-pipeline.urm.puml new file mode 100644 index 000000000000..8cd51c44656b --- /dev/null +++ b/collection-pipeline/etc/collection-pipeline.urm.puml @@ -0,0 +1,52 @@ +@startuml +package com.iluwatar.collectionpipeline { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Car { + - category : Category + - make : String + - model : String + - year : int + + Car(make : String, model : String, yearOfMake : int, category : Category) + + equals(obj : Object) : boolean + + getCategory() : Category + + getMake() : String + + getModel() : String + + getYear() : int + + hashCode() : int + } + class CarFactory { + - CarFactory() + + createCars() : List {static} + } + enum Category { + + CONVERTIBLE {static} + + JEEP {static} + + SEDAN {static} + + valueOf(name : String) : Category {static} + + values() : Category[] {static} + } + class FunctionalProgramming { + - FunctionalProgramming() + + getGroupingOfCarsByCategory(cars : List) : Map> {static} + + getModelsAfter2000(cars : List) : List {static} + + getSedanCarsOwnedSortedByDate(persons : List) : List {static} + } + class ImperativeProgramming { + - ImperativeProgramming() + + getGroupingOfCarsByCategory(cars : List) : Map> {static} + + getModelsAfter2000(cars : List) : List {static} + + getSedanCarsOwnedSortedByDate(persons : List) : List {static} + } + class Person { + - cars : List + + Person(cars : List) + + getCars() : List + } +} +Person --> "-cars" Car +Car --> "-category" Category +@enduml \ No newline at end of file diff --git a/collection-pipeline/pom.xml b/collection-pipeline/pom.xml new file mode 100644 index 000000000000..b3c36cf06ef6 --- /dev/null +++ b/collection-pipeline/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + collection-pipeline + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.collectionpipeline.App + + + + + + + + + diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java new file mode 100644 index 000000000000..73a79f826cc1 --- /dev/null +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java @@ -0,0 +1,69 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectionpipeline; + +import java.util.List; +import lombok.extern.slf4j.Slf4j; + +/** + * In imperative-style programming, it is common to use for and while loops for most kinds of data + * processing. Function composition is a simple technique that lets you sequence modular functions + * to create more complex operations. When you run data through the sequence, you have a collection + * pipeline. Together, the Function Composition and Collection Pipeline patterns enable you to + * create sophisticated programs where data flow from upstream to downstream and is passed through a + * series of transformations. + */ +@Slf4j +public class App { + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + var cars = CarFactory.createCars(); + + var modelsImperative = ImperativeProgramming.getModelsAfter2000(cars); + LOGGER.info(modelsImperative.toString()); + + var modelsFunctional = FunctionalProgramming.getModelsAfter2000(cars); + LOGGER.info(modelsFunctional.toString()); + + var groupingByCategoryImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); + LOGGER.info(groupingByCategoryImperative.toString()); + + var groupingByCategoryFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); + LOGGER.info(groupingByCategoryFunctional.toString()); + + var john = new Person(cars); + + var sedansOwnedImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); + LOGGER.info(sedansOwnedImperative.toString()); + + var sedansOwnedFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); + LOGGER.info(sedansOwnedFunctional.toString()); + } +} diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java new file mode 100644 index 000000000000..7b4537800437 --- /dev/null +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java @@ -0,0 +1,29 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectionpipeline; + +/** A Car class that has the properties of make, model, year and category. */ +public record Car(String make, String model, int year, Category category) {} diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java new file mode 100644 index 000000000000..2bfaa676060e --- /dev/null +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java @@ -0,0 +1,47 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectionpipeline; + +import java.util.List; + +/** A factory class to create a collection of {@link Car} instances. */ +public class CarFactory { + private CarFactory() {} + + /** + * Factory method to create a {@link List} of {@link Car} instances. + * + * @return {@link List} of {@link Car} + */ + public static List createCars() { + return List.of( + new Car("Jeep", "Wrangler", 2011, Category.JEEP), + new Car("Jeep", "Comanche", 1990, Category.JEEP), + new Car("Dodge", "Avenger", 2010, Category.SEDAN), + new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), + new Car("Ford", "Focus", 2012, Category.SEDAN), + new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE)); + } +} diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java new file mode 100644 index 000000000000..9de7e4da3b50 --- /dev/null +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectionpipeline; + +/** Enum for the category of car. */ +public enum Category { + JEEP, + SEDAN, + CONVERTIBLE +} diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java new file mode 100644 index 000000000000..dfe2d9ea5697 --- /dev/null +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java @@ -0,0 +1,88 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectionpipeline; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Iterating and sorting with a collection pipeline + * + *

    In functional programming, it's common to sequence complex operations through a series of + * smaller modular functions or operations. The series is called a composition of functions, or a + * function composition. When a collection of data flows through a function composition, it becomes + * a collection pipeline. Function Composition and Collection Pipeline are two design patterns + * frequently used in functional-style programming. + * + *

    Instead of passing a lambda expression to the map method, we passed the method reference + * Car::getModel. Likewise, instead of passing the lambda expression car -> car.getYear() to the + * comparing method, we passed the method reference Car::getYear. Method references are short, + * concise, and expressive. It is best to use them wherever possible. + */ +public class FunctionalProgramming { + private FunctionalProgramming() {} + + /** + * Method to get models using for collection pipeline. + * + * @param cars {@link List} of {@link Car} to be used for filtering + * @return {@link List} of {@link String} representing models built after year 2000 + */ + public static List getModelsAfter2000(List cars) { + return cars.stream() + .filter(car -> car.year() > 2000) + .sorted(Comparator.comparing(Car::year)) + .map(Car::model) + .toList(); + } + + /** + * Method to group cars by category using groupingBy. + * + * @param cars {@link List} of {@link Car} to be used for grouping + * @return {@link Map} with category as key and cars belonging to that category as value + */ + public static Map> getGroupingOfCarsByCategory(List cars) { + return cars.stream().collect(Collectors.groupingBy(Car::category)); + } + + /** + * Method to get all Sedan cars belonging to a group of persons sorted by year of manufacture. + * + * @param persons {@link List} of {@link Person} to be used + * @return {@link List} of {@link Car} to belonging to the group + */ + public static List getSedanCarsOwnedSortedByDate(List persons) { + return persons.stream() + .map(Person::cars) + .flatMap(List::stream) + .filter(car -> Category.SEDAN.equals(car.category())) + .sorted(Comparator.comparing(Car::year)) + .toList(); + } +} diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java new file mode 100644 index 000000000000..24c0b965e4da --- /dev/null +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java @@ -0,0 +1,135 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectionpipeline; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Imperative-style programming to iterate over the list and get the names of cars made later than + * the year 2000. We then sort the models in ascending order by year. + * + *

    As you can see, there's a lot of looping in this code. First, the getModelsAfter2000UsingFor + * method takes a list of cars as its parameter. It extracts or filters out cars made after the year + * 2000, putting them into a new list named carsSortedByYear. Next, it sorts that list in ascending + * order by year-of-make. Finally, it loops through the list carsSortedByYear to get the model names + * and returns them in a list. + * + *

    This short example demonstrates what I call the effect of statements. While functions and + * methods in general can be used as expressions, the {@link Collections} sort method doesn't return + * a result. Because it is used as a statement, it mutates the list given as argument. Both of the + * for loops also mutate lists as they iterate. Being statements, that's just how these elements + * work. As a result, the code contains unnecessary garbage variables + */ +public class ImperativeProgramming { + private ImperativeProgramming() {} + + /** + * Method to return the car models built after year 2000 using for loops. + * + * @param cars {@link List} of {@link Car} to iterate over + * @return {@link List} of {@link String} of car models built after year 2000 + */ + public static List getModelsAfter2000(List cars) { + List carsSortedByYear = new ArrayList<>(); + + for (Car car : cars) { + if (car.year() > 2000) { + carsSortedByYear.add(car); + } + } + + Collections.sort( + carsSortedByYear, + new Comparator() { + @Override + public int compare(Car car1, Car car2) { + return car1.year() - car2.year(); + } + }); + + List models = new ArrayList<>(); + for (Car car : carsSortedByYear) { + models.add(car.model()); + } + + return models; + } + + /** + * Method to group cars by category using for loops. + * + * @param cars {@link List} of {@link Car} to be used for grouping + * @return {@link Map} with category as key and cars belonging to that category as value + */ + public static Map> getGroupingOfCarsByCategory(List cars) { + Map> groupingByCategory = new HashMap<>(); + for (Car car : cars) { + if (groupingByCategory.containsKey(car.category())) { + groupingByCategory.get(car.category()).add(car); + } else { + List categoryCars = new ArrayList<>(); + categoryCars.add(car); + groupingByCategory.put(car.category(), categoryCars); + } + } + return groupingByCategory; + } + + /** + * Method to get all Sedan cars belonging to a group of persons sorted by year of manufacture + * using for loops. + * + * @param persons {@link List} of {@link Person} to be used + * @return {@link List} of {@link Car} to belonging to the group + */ + public static List getSedanCarsOwnedSortedByDate(List persons) { + List cars = new ArrayList<>(); + for (Person person : persons) { + cars.addAll(person.cars()); + } + + List sedanCars = new ArrayList<>(); + for (Car car : cars) { + if (Category.SEDAN.equals(car.category())) { + sedanCars.add(car); + } + } + + sedanCars.sort( + new Comparator() { + @Override + public int compare(Car o1, Car o2) { + return o1.year() - o2.year(); + } + }); + + return sedanCars; + } +} diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java new file mode 100644 index 000000000000..a84dc7f72a31 --- /dev/null +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectionpipeline; + +import java.util.List; + +/** A Person class that has the list of cars that the person owns and use. */ +public record Person(List cars) {} diff --git a/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java b/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java new file mode 100644 index 000000000000..9a990b09ec15 --- /dev/null +++ b/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java @@ -0,0 +1,87 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.collectionpipeline; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; + +/** Tests that Collection Pipeline methods work as expected. */ +@Slf4j +class AppTest { + + private final List cars = CarFactory.createCars(); + + @Test + void testGetModelsAfter2000UsingFor() { + var models = ImperativeProgramming.getModelsAfter2000(cars); + assertEquals(List.of("Avenger", "Wrangler", "Focus", "Cascada"), models); + } + + @Test + void testGetModelsAfter2000UsingPipeline() { + var models = FunctionalProgramming.getModelsAfter2000(cars); + assertEquals(List.of("Avenger", "Wrangler", "Focus", "Cascada"), models); + } + + @Test + void testGetGroupingOfCarsByCategory() { + var modelsExpected = + Map.of( + Category.CONVERTIBLE, + List.of( + new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), + new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE)), + Category.SEDAN, + List.of( + new Car("Dodge", "Avenger", 2010, Category.SEDAN), + new Car("Ford", "Focus", 2012, Category.SEDAN)), + Category.JEEP, + List.of( + new Car("Jeep", "Wrangler", 2011, Category.JEEP), + new Car("Jeep", "Comanche", 1990, Category.JEEP))); + var modelsFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); + var modelsImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); + LOGGER.info("Category " + modelsFunctional); + assertEquals(modelsExpected, modelsFunctional); + assertEquals(modelsExpected, modelsImperative); + } + + @Test + void testGetSedanCarsOwnedSortedByDate() { + var john = new Person(cars); + var modelsExpected = + List.of( + new Car("Dodge", "Avenger", 2010, Category.SEDAN), + new Car("Ford", "Focus", 2012, Category.SEDAN)); + var modelsFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); + var modelsImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); + assertEquals(modelsExpected, modelsFunctional); + assertEquals(modelsExpected, modelsImperative); + } +} diff --git a/combinator/README.md b/combinator/README.md new file mode 100644 index 000000000000..93aa7792fb58 --- /dev/null +++ b/combinator/README.md @@ -0,0 +1,242 @@ +--- +title: "Combinator Pattern in Java: Crafting Flexible Code Compositions" +shortTitle: Combinator +description: "Learn how to use the Combinator pattern in Java with real-world examples and comprehensive explanations. Enhance your Java design skills with this detailed guide." +category: Functional +language: en +tag: + - Abstraction + - Code simplification + - Functional decomposition + - Idiom + - Reactive +--- + +## Also known as + +* Function Composition +* Functional Combinator + +## Intent of Combinator Design Pattern + +The Combinator pattern, a functional programming technique widely used in Java, is essential for combining functions to build complex behaviors. This pattern allows developers to combine multiple smaller functions or operations into a single, more complex operation, promoting flexible and reusable code. By leveraging higher-order functions, the Combinator pattern enhances code reuse and maintainability in Java applications, making it a valuable tool in software design. This approach fosters the creation of modular, scalable solutions in Java development. + +## Detailed Explanation of Combinator Pattern with Real-World Examples + +Real-world example + +> In the real world, the combinator design pattern can be likened to a meal preparation process in a kitchen. Imagine a chef who has a set of simple operations: chopping vegetables, boiling water, cooking rice, grilling chicken, and mixing ingredients. Each of these operations is a standalone function. The chef can combine these operations in various sequences to create different dishes. For example, to prepare a chicken rice bowl, the chef can combine the operations of cooking rice, grilling chicken, and mixing them with vegetables. By reusing these basic operations and combining them in different ways, the chef can efficiently prepare a wide variety of meals. Similarly, in software, the combinator pattern allows developers to combine simple, reusable functions to create more complex behaviors. + +In plain words + +> The combinator design pattern combines simple, reusable functions to create more complex and flexible operations. + +Wikipedia says + +> A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments. + +Flowchart + +![Combinator flowchart](./etc/combinator-flowchart.png) + +## Programmatic Example of Combinator Pattern in Java + +In software design, combinatory logic is pivotal for creating reusable and modular code components. By leveraging higher-order functions, the Combinator pattern promotes code reuse and maintainability in Java applications. + +In this Java example, we demonstrate the implementation of combinators such as `contains`, `not`, `or`, and `and` to create complex finders. + +```java +// Functional interface to find lines in text. +public interface Finder { + + // The function to find lines in text. + List find(String text); + + // Simple implementation of function {@link #find(String)}. + static Finder contains(String word) { + return txt -> Stream.of(txt.split("\n")) + .filter(line -> line.toLowerCase().contains(word.toLowerCase())) + .collect(Collectors.toList()); + } + + // combinator not. + default Finder not(Finder notFinder) { + return txt -> { + List res = this.find(txt); + res.removeAll(notFinder.find(txt)); + return res; + }; + } + + // combinator or. + default Finder or(Finder orFinder) { + return txt -> { + List res = this.find(txt); + res.addAll(orFinder.find(txt)); + return res; + }; + } + + // combinator and. + default Finder and(Finder andFinder) { + return + txt -> this + .find(txt) + .stream() + .flatMap(line -> andFinder.find(line).stream()) + .collect(Collectors.toList()); + } + // Other properties and methods... +} +``` + +Then we have also another combinator for some complex finders `advancedFinder`, `filteredFinder`, `specializedFinder` and `expandedFinder`. + +```java +// Complex finders consisting of simple finder. +public class Finders { + + private Finders() { + } + + // Finder to find a complex query. + public static Finder advancedFinder(String query, String orQuery, String notQuery) { + return + Finder.contains(query) + .or(Finder.contains(orQuery)) + .not(Finder.contains(notQuery)); + } + + // Filtered finder looking a query with excluded queries as well. + public static Finder filteredFinder(String query, String... excludeQueries) { + var finder = Finder.contains(query); + + for (String q : excludeQueries) { + finder = finder.not(Finder.contains(q)); + } + return finder; + } + + // Specialized query. Every next query is looked in previous result. + public static Finder specializedFinder(String... queries) { + var finder = identMult(); + + for (String query : queries) { + finder = finder.and(Finder.contains(query)); + } + return finder; + } + + // Expanded query. Looking for alternatives. + public static Finder expandedFinder(String... queries) { + var finder = identSum(); + + for (String query : queries) { + finder = finder.or(Finder.contains(query)); + } + return finder; + } + // Other properties and methods... +} +``` + +Now that we have created the interface and methods for combinators, let's see how an application works with them. + +```java +public class CombinatorApp { + + private static final String TEXT = """ + It was many and many a year ago, + In a kingdom by the sea, + That a maiden there lived whom you may know + By the name of ANNABEL LEE; + And this maiden she lived with no other thought + Than to love and be loved by me. + I was a child and she was a child, + In this kingdom by the sea; + But we loved with a love that was more than love- + I and my Annabel Lee; + With a love that the winged seraphs of heaven + Coveted her and me."""; + + public static void main(String[] args) { + var queriesOr = new String[]{"many", "Annabel"}; + var finder = Finders.expandedFinder(queriesOr); + var res = finder.find(text()); + LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res); + + var queriesAnd = new String[]{"Annabel", "my"}; + finder = Finders.specializedFinder(queriesAnd); + res = finder.find(text()); + LOGGER.info("the result of specialized(and) query[{}] is {}", queriesAnd, res); + + finder = Finders.advancedFinder("it was", "kingdom", "sea"); + res = finder.find(text()); + LOGGER.info("the result of advanced query is {}", res); + + res = Finders.filteredFinder(" was ", "many", "child").find(text()); + LOGGER.info("the result of filtered query is {}", res); + } + + private static String text() { + return TEXT; + } +} +``` + +Program output: + +``` +20:03:52.746 [main] INFO com.iluwatar.combinator.CombinatorApp -- the result of expanded(or) query[[many, Annabel]] is [It was many and many a year ago,, By the name of ANNABEL LEE;, I and my Annabel Lee;] +20:03:52.749 [main] INFO com.iluwatar.combinator.CombinatorApp -- the result of specialized(and) query[[Annabel, my]] is [I and my Annabel Lee;] +20:03:52.750 [main] INFO com.iluwatar.combinator.CombinatorApp -- the result of advanced query is [It was many and many a year ago,] +20:03:52.750 [main] INFO com.iluwatar.combinator.CombinatorApp -- the result of filtered query is [But we loved with a love that was more than love-] +``` + +Now we can design our app to with the queries finding feature `expandedFinder`, `specializedFinder`, `advancedFinder`, `filteredFinder` which are all derived from `contains`, `or`, `not`, `and`. + +## When to Use the Combinator Pattern in Java + +The Combinator pattern is particularly useful in functional programming where complex values are built from simpler, reusable components. + +The applicable scenarios include: + +* The solution to a problem can be constructed from simple, reusable components. +* There is a need for high modularity and reusability of functions. +* The programming environment supports first-class functions and higher-order functions. + +## Real-World Applications of Combinator Pattern in Java + +* Functional programming languages like Haskell and Scala extensively use combinators for tasks ranging from parsing to UI construction. +* In domain-specific languages, particularly those involved in parsing, such as parsing expression grammars. +* In libraries for functional programming in languages like JavaScript, Python, and Ruby. +* java.util.function.Function#compose +* java.util.function.Function#andThen + +## Benefits and Trade-offs of Combinator Pattern + +Benefits: + +* Enhances developer productivity by using domain-specific terms and facilitates parallel execution in Java applications. +* Enhances modularity and reusability by breaking down complex tasks into simpler, composable functions. +* Promotes readability and maintainability by using a declarative style of programming. +* Facilitates lazy evaluation and potentially more efficient execution through function composition. + +Trade-offs: + +* Can lead to a steep learning curve for those unfamiliar with functional programming principles. +* May result in performance overhead due to the creation of intermediate functions. +* Debugging can be challenging due to the abstract nature of function compositions. + +## Related Java Design Patterns + +* [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Relies on chaining objects, whereas Combinator chains functions. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar to Combinator in enhancing functionality, but Decorator focuses on object augmentation. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Both involve selecting an algorithm at runtime, but Combinator uses composition of functions. + +## References and Credits + +* [Functional Programming in Scala](https://amzn.to/4cEo6K2) +* [Haskell: The Craft of Functional Programming](https://amzn.to/4axxtcF) +* [Structure and Interpretation of Computer Programs](https://amzn.to/3PJwVsf) +* [Combinator Pattern with Java 8 (Gregor Trefs)](https://gtrefs.github.io/code/combinator-pattern/) diff --git a/combinator/etc/combinator-flowchart.png b/combinator/etc/combinator-flowchart.png new file mode 100644 index 000000000000..9cc8b341395d Binary files /dev/null and b/combinator/etc/combinator-flowchart.png differ diff --git a/combinator/etc/combinator.urm.png b/combinator/etc/combinator.urm.png new file mode 100644 index 000000000000..80fdd36340bb Binary files /dev/null and b/combinator/etc/combinator.urm.png differ diff --git a/combinator/etc/combinator.urm.puml b/combinator/etc/combinator.urm.puml new file mode 100644 index 000000000000..83feec1ae782 --- /dev/null +++ b/combinator/etc/combinator.urm.puml @@ -0,0 +1,26 @@ +@startuml +package com.iluwatar.combinator { + class CombinatorApp { + - LOGGER : Logger {static} + + CombinatorApp() + + main(args : String[]) {static} + - text() : String {static} + } + interface Finder { + + and(andFinder : Finder) : Finder + + contains(word : String) : Finder {static} + + find(String) : List {abstract} + + not(notFinder : Finder) : Finder + + or(orFinder : Finder) : Finder + } + class Finders { + - Finders() + + advancedFinder(query : String, orQuery : String, notQuery : String) : Finder {static} + + expandedFinder(queries : String[]) : Finder {static} + + filteredFinder(query : String, excludeQueries : String[]) : Finder {static} + - identMult() : Finder {static} + - identSum() : Finder {static} + + specializedFinder(queries : String[]) : Finder {static} + } +} +@enduml \ No newline at end of file diff --git a/combinator/pom.xml b/combinator/pom.xml new file mode 100644 index 000000000000..d366b383a187 --- /dev/null +++ b/combinator/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + combinator + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.combinator.CombinatorApp + + + + + + + + + diff --git a/combinator/src/main/java/com/iluwatar/combinator/CombinatorApp.java b/combinator/src/main/java/com/iluwatar/combinator/CombinatorApp.java new file mode 100644 index 000000000000..bf1ec4a017de --- /dev/null +++ b/combinator/src/main/java/com/iluwatar/combinator/CombinatorApp.java @@ -0,0 +1,84 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.combinator; + +import lombok.extern.slf4j.Slf4j; + +/** + * The functional pattern representing a style of organizing libraries centered around the idea of + * combining functions. Putting it simply, there is some type T, some functions for constructing + * "primitive" values of type T, and some "combinators" which can combine values of type T in + * various ways to build up more complex values of type T. The class {@link Finder} defines a simple + * function {@link Finder#find(String)} and connected functions {@link Finder#or(Finder)}, {@link + * Finder#not(Finder)}, {@link Finder#and(Finder)} Using them the became possible to get more + * complex functions {@link Finders} + */ +@Slf4j +public class CombinatorApp { + + private static final String TEXT = + """ + It was many and many a year ago, + In a kingdom by the sea, + That a maiden there lived whom you may know + By the name of ANNABEL LEE; + And this maiden she lived with no other thought + Than to love and be loved by me. + I was a child and she was a child, + In this kingdom by the sea; + But we loved with a love that was more than love- + I and my Annabel Lee; + With a love that the winged seraphs of heaven + Coveted her and me."""; + + /** + * main. + * + * @param args args + */ + public static void main(String[] args) { + var queriesOr = new String[] {"many", "Annabel"}; + var finder = Finders.expandedFinder(queriesOr); + var res = finder.find(text()); + LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res); + + var queriesAnd = new String[] {"Annabel", "my"}; + finder = Finders.specializedFinder(queriesAnd); + res = finder.find(text()); + LOGGER.info("the result of specialized(and) query[{}] is {}", queriesAnd, res); + + finder = Finders.advancedFinder("it was", "kingdom", "sea"); + res = finder.find(text()); + LOGGER.info("the result of advanced query is {}", res); + + res = Finders.filteredFinder(" was ", "many", "child").find(text()); + LOGGER.info("the result of filtered query is {}", res); + } + + private static String text() { + + return TEXT; + } +} diff --git a/combinator/src/main/java/com/iluwatar/combinator/Finder.java b/combinator/src/main/java/com/iluwatar/combinator/Finder.java new file mode 100644 index 000000000000..cc2d5ce84918 --- /dev/null +++ b/combinator/src/main/java/com/iluwatar/combinator/Finder.java @@ -0,0 +1,95 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.combinator; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** Functional interface to find lines in text. */ +public interface Finder { + + /** + * The function to find lines in text. + * + * @param text full tet + * @return result of searching + */ + List find(String text); + + /** + * Simple implementation of function {@link #find(String)}. + * + * @param word for searching + * @return this + */ + static Finder contains(String word) { + return txt -> + Stream.of(txt.split("\n")) + .filter(line -> line.toLowerCase().contains(word.toLowerCase())) + .collect(Collectors.toList()); + } + + /** + * combinator not. + * + * @param notFinder finder to combine + * @return new finder including previous finders + */ + default Finder not(Finder notFinder) { + return txt -> { + List res = this.find(txt); + res.removeAll(notFinder.find(txt)); + return res; + }; + } + + /** + * combinator or. + * + * @param orFinder finder to combine + * @return new finder including previous finders + */ + default Finder or(Finder orFinder) { + return txt -> { + List res = this.find(txt); + res.addAll(orFinder.find(txt)); + return res; + }; + } + + /** + * combinator and. + * + * @param andFinder finder to combine + * @return new finder including previous finders + */ + default Finder and(Finder andFinder) { + return txt -> + this.find(txt).stream() + .flatMap(line -> andFinder.find(line).stream()) + .collect(Collectors.toList()); + } +} diff --git a/combinator/src/main/java/com/iluwatar/combinator/Finders.java b/combinator/src/main/java/com/iluwatar/combinator/Finders.java new file mode 100644 index 000000000000..a6f8dd7cac79 --- /dev/null +++ b/combinator/src/main/java/com/iluwatar/combinator/Finders.java @@ -0,0 +1,100 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.combinator; + +import java.util.ArrayList; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** Complex finders consisting of simple finder. */ +public class Finders { + private Finders() {} + + /** + * Finder to find a complex query. + * + * @param query to find + * @param orQuery alternative to find + * @param notQuery exclude from search + * @return new finder + */ + public static Finder advancedFinder(String query, String orQuery, String notQuery) { + return Finder.contains(query).or(Finder.contains(orQuery)).not(Finder.contains(notQuery)); + } + + /** + * Filtered finder looking a query with excluded queries as well. + * + * @param query to find + * @param excludeQueries to exclude + * @return new finder + */ + public static Finder filteredFinder(String query, String... excludeQueries) { + var finder = Finder.contains(query); + + for (String q : excludeQueries) { + finder = finder.not(Finder.contains(q)); + } + return finder; + } + + /** + * Specialized query. Every next query is looked in previous result. + * + * @param queries array with queries + * @return new finder + */ + public static Finder specializedFinder(String... queries) { + var finder = identMult(); + + for (String query : queries) { + finder = finder.and(Finder.contains(query)); + } + return finder; + } + + /** + * Expanded query. Looking for alternatives. + * + * @param queries array with queries. + * @return new finder + */ + public static Finder expandedFinder(String... queries) { + var finder = identSum(); + + for (String query : queries) { + finder = finder.or(Finder.contains(query)); + } + return finder; + } + + private static Finder identMult() { + return txt -> Stream.of(txt.split("\n")).collect(Collectors.toList()); + } + + private static Finder identSum() { + return txt -> new ArrayList<>(); + } +} diff --git a/combinator/src/test/java/com/iluwatar/combinator/CombinatorAppTest.java b/combinator/src/test/java/com/iluwatar/combinator/CombinatorAppTest.java new file mode 100644 index 000000000000..4a7a6fff7a4e --- /dev/null +++ b/combinator/src/test/java/com/iluwatar/combinator/CombinatorAppTest.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.combinator; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class CombinatorAppTest { + + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * CombinatorApp#main(String[])} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> CombinatorApp.main(new String[] {})); + } +} diff --git a/combinator/src/test/java/com/iluwatar/combinator/FinderTest.java b/combinator/src/test/java/com/iluwatar/combinator/FinderTest.java new file mode 100644 index 000000000000..c4a505df075d --- /dev/null +++ b/combinator/src/test/java/com/iluwatar/combinator/FinderTest.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.combinator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class FinderTest { + + @Test + void contains() { + var example = """ + the first one + the second one\s + """; + + var result = Finder.contains("second").find(example); + assertEquals(1, result.size()); + assertEquals("the second one ", result.get(0)); + } +} diff --git a/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java b/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java new file mode 100644 index 000000000000..f8a23927c33e --- /dev/null +++ b/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java @@ -0,0 +1,83 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.combinator; + +import static com.iluwatar.combinator.Finders.advancedFinder; +import static com.iluwatar.combinator.Finders.expandedFinder; +import static com.iluwatar.combinator.Finders.filteredFinder; +import static com.iluwatar.combinator.Finders.specializedFinder; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class FindersTest { + + @Test + void advancedFinderTest() { + var res = advancedFinder("it was", "kingdom", "sea").find(text()); + assertEquals(1, res.size()); + assertEquals("It was many and many a year ago,", res.get(0)); + } + + @Test + void filteredFinderTest() { + var res = filteredFinder(" was ", "many", "child").find(text()); + assertEquals(1, res.size()); + assertEquals("But we loved with a love that was more than love-", res.get(0)); + } + + @Test + void specializedFinderTest() { + var res = specializedFinder("love", "heaven").find(text()); + assertEquals(1, res.size()); + assertEquals("With a love that the winged seraphs of heaven", res.get(0)); + } + + @Test + void expandedFinderTest() { + var res = expandedFinder("It was", "kingdom").find(text()); + assertEquals(3, res.size()); + assertEquals("It was many and many a year ago,", res.get(0)); + assertEquals("In a kingdom by the sea,", res.get(1)); + assertEquals("In this kingdom by the sea;", res.get(2)); + } + + private String text() { + return """ + It was many and many a year ago, + In a kingdom by the sea, + That a maiden there lived whom you may know + By the name of ANNABEL LEE; + And this maiden she lived with no other thought + Than to love and be loved by me. + I was a child and she was a child, + In this kingdom by the sea; + But we loved with a love that was more than love- + I and my Annabel Lee; + With a love that the winged seraphs of heaven + Coveted her and me."""; + } +} diff --git a/command-query-responsibility-segregation/README.md b/command-query-responsibility-segregation/README.md new file mode 100644 index 000000000000..bc1de83fc681 --- /dev/null +++ b/command-query-responsibility-segregation/README.md @@ -0,0 +1,143 @@ +--- +title: "Command Query Responsibility Segregation in Java: Optimizing Data Interaction for Scalability" +shortTitle: Command Query Responsibility Segregation (CQRS) +description: "Learn about the Command Query Responsibility Segregation (CQRS) pattern in Java. Discover how segregating commands and queries can enhance the scalability, performance, and maintainability of your software systems." +category: Architectural +language: en +tag: + - Event-driven + - Performance + - Scalability +--- + +## Also known as + +* CQRS + +## Intent of Command Query Responsibility Segregation Design Pattern + +Command Query Responsibility Segregation (CQRS) aims to segregate the operations that modify the state of an application (commands) from the operations that read the state (queries). This separation enhances scalability, performance, and maintainability in complex software systems. + +## Detailed Explanation of Command Query Responsibility Segregation Pattern with Real-World Examples + +Real-world example + +> Imagine a modern library where the tasks of borrowing and returning books (commands) are handled at the front desk, while the task of searching for books and reading them (queries) happens in the reading area. The front desk optimizes for transaction efficiency and record-keeping, ensuring books are properly checked in and out. Meanwhile, the reading area is optimized for comfort and accessibility, making it easy for readers to find and engage with the books. This separation improves the library's overall efficiency and user experience, much like the CQRS pattern enhances a software system's performance and maintainability. + +In plain words + +> The CQRS design pattern separates the actions of modifying data (commands) from the actions of retrieving data (queries) to enhance performance, scalability, and maintainability in software systems. By implementing CQRS, you can optimize your system's read and write operations independently, allowing for more efficient data handling and improved overall system performance. + +Microsoft's documentation says + +> CQRS separates reads and writes into different models, using commands to update data, and queries to read data. + +Architecture diagram + +![CQRS Architecture Diagram](./etc/cqrs-architecture-diagram.png) + +## Programmatic Example of CQRS Pattern in Java + +One way to implement the Command Query Responsibility Segregation (CQRS) pattern is to separate the read and write operations into different services. + +Let's see the code implementation first and explain how it works afterward. + +```java +public static void main(String[] args) { + + // Create Authors and Books using CommandService + var commands = new CommandServiceImpl(); + + commands.authorCreated(AppConstants.E_EVANS, "Eric Evans", "evans@email.com"); + commands.authorCreated(AppConstants.J_BLOCH, "Joshua Bloch", "jBloch@email.com"); + commands.authorCreated(AppConstants.M_FOWLER, "Martin Fowler", "mFowler@email.com"); + + commands.bookAddedToAuthor("Domain-Driven Design", 60.08, AppConstants.E_EVANS); + commands.bookAddedToAuthor("Effective Java", 40.54, AppConstants.J_BLOCH); + commands.bookAddedToAuthor("Java Puzzlers", 39.99, AppConstants.J_BLOCH); + commands.bookAddedToAuthor("Java Concurrency in Practice", 29.40, AppConstants.J_BLOCH); + commands.bookAddedToAuthor("Patterns of Enterprise" + + " Application Architecture", 54.01, AppConstants.M_FOWLER); + commands.bookAddedToAuthor("Domain Specific Languages", 48.89, AppConstants.M_FOWLER); + commands.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans"); + + // Query the database using QueryService + var queries = new QueryServiceImpl(); + + var nullAuthor = queries.getAuthorByUsername("username"); + var evans = queries.getAuthorByUsername(AppConstants.E_EVANS); + var blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH); + var authorsCount = queries.getAuthorsCount(); + var dddBook = queries.getBook("Domain-Driven Design"); + var blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH); + + LOGGER.info("Author username : {}", nullAuthor); + LOGGER.info("Author evans : {}", evans); + LOGGER.info("jBloch number of books : {}", blochBooksCount); + LOGGER.info("Number of authors : {}", authorsCount); + LOGGER.info("DDD book : {}", dddBook); + LOGGER.info("jBloch books : {}", blochBooks); + + HibernateUtil.getSessionFactory().close(); +} +``` + +1. Command Service: The `CommandServiceImpl` class is used for write operations. It provides methods to create authors and books, and to add books to authors. + +2. Query Service: The `QueryServiceImpl` class is used for read operations. It provides methods to get author and book details. + +This separation of concerns allows for flexibility in how the application handles data access and manipulation, and is a key aspect of the CQRS pattern. + +Program output: + +``` +17:37:56.040 [main] INFO com.iluwatar.cqrs.app.App - Author username : null +17:37:56.040 [main] INFO com.iluwatar.cqrs.app.App - Author evans : Author(name=Eric J. Evans, email=evans@email.com, username=eEvans) +17:37:56.041 [main] INFO com.iluwatar.cqrs.app.App - jBloch number of books : 3 +17:37:56.041 [main] INFO com.iluwatar.cqrs.app.App - Number of authors : 3 +17:37:56.041 [main] INFO com.iluwatar.cqrs.app.App - DDD book : Book(title=Domain-Driven Design, price=60.08) +17:37:56.042 [main] INFO com.iluwatar.cqrs.app.App - jBloch books : [Book(title=Effective Java, price=40.54), Book(title=Java Puzzlers, price=39.99), Book(title=Java Concurrency in Practice, price=29.4)] +``` + +## When to Use the Command Query Responsibility Segregation Pattern in Java + +* Systems requiring distinct models for read and write operations for scalability and maintainability, such as e-commerce platforms and high-traffic websites. +* Complex domain models, like financial services or healthcare applications, where the task of updating objects differs significantly from the task of reading object data. +* Scenarios where performance optimization for read operations is crucial, and the system can benefit from different data models or databases for reads and writes, enhancing data retrieval speed and accuracy. + +## Real-World Applications of CQRS Pattern in Java + +* Distributed Systems and Microservices Architecture, where different services manage read and write responsibilities. +* Event-Sourced Systems, where changes to the application state are stored as a sequence of events. +* High-Performance Web Applications, segregating read and write databases to optimize load handling. + +## Benefits and Trade-offs of Command Query Responsibility Segregation Pattern + +Benefits: + +* Scalability: By separating read and write models, each can be scaled independently according to their specific demands. +* Optimization: Allows for the optimization of read models for query efficiency and write models for transactional integrity. +* Maintainability: Reduces complexity by separating the concerns, leading to cleaner, more maintainable code. +* Flexibility: Offers the flexibility to choose different technologies for the read and write sides according to their requirements. + +Trade-Offs: + +* Complexity: Introduces complexity due to synchronization between read and write models, especially in consistency maintenance. +* Overhead: Might be an overkill for simple systems where the benefits do not outweigh the additional complexity. +* Learning Curve: Requires a deeper understanding and careful design to implement effectively, increasing the initial learning curve. + +## Related Java Design Patterns + +* [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Often used in conjunction with CQRS, where changes to the application state are stored as a sequence of events. +* Domain-Driven Design (DDD): CQRS fits well within the DDD context, providing clear boundaries and separation of concerns. +* [Repository](https://java-design-patterns.com/patterns/repository/): Can be used to abstract the data layer, providing a more seamless integration between the command and query sides. + +## References and Credits + +* [Implementing Domain-Driven Design](https://amzn.to/3TJN2HH) +* [Microsoft .NET: Architecting Applications for the Enterprise](https://amzn.to/4aktRes) +* [Patterns, Principles, and Practices of Domain-Driven Design](https://amzn.to/3vNV4Hm) +* [CQRS, Task Based UIs, Event Sourcing agh! (Greg Young)](http://codebetter.com/gregyoung/2010/02/16/cqrs-task-based-uis-event-sourcing-agh/) +* [CQRS (Martin Fowler)](https://martinfowler.com/bliki/CQRS.html) +* [CQRS for Great Good (Oliver Wolf)](https://www.youtube.com/watch?v=Ge53swja9Dw) +* [CQRS pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs) diff --git a/command-query-responsibility-segregation/etc/command-query-responsibility-segregation.urm.puml b/command-query-responsibility-segregation/etc/command-query-responsibility-segregation.urm.puml new file mode 100644 index 000000000000..aef8eef5c1d2 --- /dev/null +++ b/command-query-responsibility-segregation/etc/command-query-responsibility-segregation.urm.puml @@ -0,0 +1,136 @@ +@startuml +package com.iluwatar.cqrs.util { + class HibernateUtil { + - LOGGER : Logger {static} + - SESSIONFACTORY : SessionFactory {static} + + HibernateUtil() + - buildSessionFactory() : SessionFactory {static} + + getSessionFactory() : SessionFactory {static} + } +} +package com.iluwatar.cqrs.app { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } +} +package com.iluwatar.cqrs.dto { + class Author { + - email : String + - name : String + - username : String + + Author() + + Author(name : String, email : String, username : String) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getEmail() : String + + getName() : String + + getUsername() : String + + hashCode() : int + + toString() : String + } + class Book { + - price : double + - title : String + + Book() + + Book(title : String, price : double) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getPrice() : double + + getTitle() : String + + hashCode() : int + + toString() : String + } +} +package com.iluwatar.cqrs.commandes { + interface CommandService { + + authorCreated(String, String, String) {abstract} + + authorEmailUpdated(String, String) {abstract} + + authorNameUpdated(String, String) {abstract} + + authorUsernameUpdated(String, String) {abstract} + + bookAddedToAuthor(String, double, String) {abstract} + + bookPriceUpdated(String, double) {abstract} + + bookTitleUpdated(String, String) {abstract} + } + class CommandServiceImpl { + - sessionFactory : SessionFactory + + CommandServiceImpl() + + authorCreated(username : String, name : String, email : String) + + authorEmailUpdated(username : String, email : String) + + authorNameUpdated(username : String, name : String) + + authorUsernameUpdated(oldUsername : String, newUsername : String) + + bookAddedToAuthor(title : String, price : double, username : String) + + bookPriceUpdated(title : String, price : double) + + bookTitleUpdated(oldTitle : String, newTitle : String) + - getAuthorByUsername(username : String) : Author + - getBookByTitle(title : String) : Book + } +} +package com.iluwatar.cqrs.queries { + interface QueryService { + + getAuthorBooks(String) : List {abstract} + + getAuthorBooksCount(String) : BigInteger {abstract} + + getAuthorByUsername(String) : Author {abstract} + + getAuthorsCount() : BigInteger {abstract} + + getBook(String) : Book {abstract} + } + class QueryServiceImpl { + - sessionFactory : SessionFactory + + QueryServiceImpl() + + getAuthorBooks(username : String) : List + + getAuthorBooksCount(username : String) : BigInteger + + getAuthorByUsername(username : String) : Author + + getAuthorsCount() : BigInteger + + getBook(title : String) : Book + } +} +package com.iluwatar.cqrs.constants { + class AppConstants { + + E_EVANS : String {static} + + J_BLOCH : String {static} + + M_FOWLER : String {static} + + USER_NAME : String {static} + + AppConstants() + } +} +package com.iluwatar.cqrs.domain.model { + class Author { + - email : String + - id : long + - name : String + - username : String + # Author() + + Author(username : String, name : String, email : String) + + getEmail() : String + + getId() : long + + getName() : String + + getUsername() : String + + setEmail(email : String) + + setId(id : long) + + setName(name : String) + + setUsername(username : String) + + toString() : String + } + class Book { + - author : Author + - id : long + - price : double + - title : String + # Book() + + Book(title : String, price : double, author : Author) + + getAuthor() : Author + + getId() : long + + getPrice() : double + + getTitle() : String + + setAuthor(author : Author) + + setId(id : long) + + setPrice(price : double) + + setTitle(title : String) + + toString() : String + } +} +Book --> "-author" Author +CommandServiceImpl ..|> CommandService +QueryServiceImpl ..|> QueryService +@enduml \ No newline at end of file diff --git a/command-query-responsibility-segregation/etc/cqrs-architecture-diagram.png b/command-query-responsibility-segregation/etc/cqrs-architecture-diagram.png new file mode 100644 index 000000000000..7391582c245c Binary files /dev/null and b/command-query-responsibility-segregation/etc/cqrs-architecture-diagram.png differ diff --git a/cqrs/etc/cqrs.png b/command-query-responsibility-segregation/etc/cqrs.png similarity index 100% rename from cqrs/etc/cqrs.png rename to command-query-responsibility-segregation/etc/cqrs.png diff --git a/cqrs/etc/cqrs.ucls b/command-query-responsibility-segregation/etc/cqrs.ucls similarity index 100% rename from cqrs/etc/cqrs.ucls rename to command-query-responsibility-segregation/etc/cqrs.ucls diff --git a/command-query-responsibility-segregation/etc/cqrs.urm.puml b/command-query-responsibility-segregation/etc/cqrs.urm.puml new file mode 100644 index 000000000000..2b06980983c5 --- /dev/null +++ b/command-query-responsibility-segregation/etc/cqrs.urm.puml @@ -0,0 +1,134 @@ +@startuml +package com.iluwatar.cqrs.util { + class HibernateUtil { + - LOGGER : Logger {static} + - SESSIONFACTORY : SessionFactory {static} + + HibernateUtil() + - buildSessionFactory() : SessionFactory {static} + + getSessionFactory() : SessionFactory {static} + } +} +package com.iluwatar.cqrs.app { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } +} +package com.iluwatar.cqrs.dto { + class Author { + - email : String + - name : String + - username : String + + Author() + + Author(name : String, email : String, username : String) + + equals(obj : Object) : boolean + + getEmail() : String + + getName() : String + + getUsername() : String + + hashCode() : int + + toString() : String + } + class Book { + - price : double + - title : String + + Book() + + Book(title : String, price : double) + + equals(obj : Object) : boolean + + getPrice() : double + + getTitle() : String + + hashCode() : int + + toString() : String + } +} +package com.iluwatar.cqrs.commandes { + class CommandServiceImpl { + - sessionFactory : SessionFactory + + CommandServiceImpl() + + authorCreated(username : String, name : String, email : String) + + authorEmailUpdated(username : String, email : String) + + authorNameUpdated(username : String, name : String) + + authorUsernameUpdated(oldUsername : String, newUsername : String) + + bookAddedToAuthor(title : String, price : double, username : String) + + bookPriceUpdated(title : String, price : double) + + bookTitleUpdated(oldTitle : String, newTitle : String) + - getAuthorByUsername(username : String) : Author + - getBookByTitle(title : String) : Book + } + interface ICommandService { + + authorCreated(String, String, String) {abstract} + + authorEmailUpdated(String, String) {abstract} + + authorNameUpdated(String, String) {abstract} + + authorUsernameUpdated(String, String) {abstract} + + bookAddedToAuthor(String, double, String) {abstract} + + bookPriceUpdated(String, double) {abstract} + + bookTitleUpdated(String, String) {abstract} + } +} +package com.iluwatar.cqrs.queries { + interface IQueryService { + + getAuthorBooks(String) : List {abstract} + + getAuthorBooksCount(String) : BigInteger {abstract} + + getAuthorByUsername(String) : Author {abstract} + + getAuthorsCount() : BigInteger {abstract} + + getBook(String) : Book {abstract} + } + class QueryServiceImpl { + - sessionFactory : SessionFactory + + QueryServiceImpl() + + getAuthorBooks(username : String) : List + + getAuthorBooksCount(username : String) : BigInteger + + getAuthorByUsername(username : String) : Author + + getAuthorsCount() : BigInteger + + getBook(title : String) : Book + } +} +package com.iluwatar.cqrs.constants { + class AppConstants { + + E_EVANS : String {static} + + J_BLOCH : String {static} + + M_FOWLER : String {static} + + USER_NAME : String {static} + + AppConstants() + } +} +package com.iluwatar.cqrs.domain.model { + class Author { + - email : String + - id : long + - name : String + - username : String + # Author() + + Author(username : String, name : String, email : String) + + getEmail() : String + + getId() : long + + getName() : String + + getUsername() : String + + setEmail(email : String) + + setId(id : long) + + setName(name : String) + + setUsername(username : String) + + toString() : String + } + class Book { + - author : Author + - id : long + - price : double + - title : String + # Book() + + Book(title : String, price : double, author : Author) + + getAuthor() : Author + + getId() : long + + getPrice() : double + + getTitle() : String + + setAuthor(author : Author) + + setId(id : long) + + setPrice(price : double) + + setTitle(title : String) + + toString() : String + } +} +Book --> "-author" Author +CommandServiceImpl ..|> ICommandService +QueryServiceImpl ..|> IQueryService +@enduml \ No newline at end of file diff --git a/command-query-responsibility-segregation/pom.xml b/command-query-responsibility-segregation/pom.xml new file mode 100644 index 000000000000..c3c277dd0b80 --- /dev/null +++ b/command-query-responsibility-segregation/pom.xml @@ -0,0 +1,89 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + command-query-responsibility-segregation + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + com.h2database + h2 + + + org.hibernate + hibernate-core + 5.6.15.Final + + + org.glassfish.jaxb + jaxb-runtime + 2.3.3 + + + javax.xml.bind + jaxb-api + 2.3.1 + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.cqrs.app.App + + + + + + + + + diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/app/App.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/app/App.java new file mode 100644 index 000000000000..62317638955c --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/app/App.java @@ -0,0 +1,89 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.app; + +import com.iluwatar.cqrs.commandes.CommandServiceImpl; +import com.iluwatar.cqrs.constants.AppConstants; +import com.iluwatar.cqrs.queries.QueryServiceImpl; +import com.iluwatar.cqrs.util.HibernateUtil; +import lombok.extern.slf4j.Slf4j; + +/** + * CQRS : Command Query Responsibility Segregation. A pattern used to separate query services from + * commands or writes services. The pattern is very simple, but it has many consequences. For + * example, it can be used to tackle down a complex domain, or to use other architectures that were + * hard to implement with the classical way. + * + *

    This implementation is an example of managing books and authors in a library. The persistence + * of books and authors is done according to the CQRS architecture. A command side that deals with a + * data model to persist(insert,update,delete) objects to a database. And a query side that uses + * native queries to get data from the database and return objects as DTOs (Data transfer Objects). + */ +@Slf4j +public class App { + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + + // Create Authors and Books using CommandService + var commands = new CommandServiceImpl(); + + commands.authorCreated(AppConstants.E_EVANS, "Eric Evans", "evans@email.com"); + commands.authorCreated(AppConstants.J_BLOCH, "Joshua Bloch", "jBloch@email.com"); + commands.authorCreated(AppConstants.M_FOWLER, "Martin Fowler", "mFowler@email.com"); + + commands.bookAddedToAuthor("Domain-Driven Design", 60.08, AppConstants.E_EVANS); + commands.bookAddedToAuthor("Effective Java", 40.54, AppConstants.J_BLOCH); + commands.bookAddedToAuthor("Java Puzzlers", 39.99, AppConstants.J_BLOCH); + commands.bookAddedToAuthor("Java Concurrency in Practice", 29.40, AppConstants.J_BLOCH); + commands.bookAddedToAuthor( + "Patterns of Enterprise" + " Application Architecture", 54.01, AppConstants.M_FOWLER); + commands.bookAddedToAuthor("Domain Specific Languages", 48.89, AppConstants.M_FOWLER); + commands.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans"); + + // Query the database using QueryService + var queries = new QueryServiceImpl(); + + var nullAuthor = queries.getAuthorByUsername("username"); + var evans = queries.getAuthorByUsername(AppConstants.E_EVANS); + var blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH); + var authorsCount = queries.getAuthorsCount(); + var dddBook = queries.getBook("Domain-Driven Design"); + var blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH); + + LOGGER.info("Author username : {}", nullAuthor); + LOGGER.info("Author evans : {}", evans); + LOGGER.info("jBloch number of books : {}", blochBooksCount); + LOGGER.info("Number of authors : {}", authorsCount); + LOGGER.info("DDD book : {}", dddBook); + LOGGER.info("jBloch books : {}", blochBooks); + + HibernateUtil.getSessionFactory().close(); + } +} diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandService.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandService.java new file mode 100644 index 000000000000..9cf8c52cbb09 --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandService.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.commandes; + +/** This interface represents the commands of the CQRS pattern. */ +public interface CommandService { + + void authorCreated(String username, String name, String email); + + void bookAddedToAuthor(String title, double price, String username); + + void authorNameUpdated(String username, String name); + + void authorUsernameUpdated(String oldUsername, String newUsername); + + void authorEmailUpdated(String username, String email); + + void bookTitleUpdated(String oldTitle, String newTitle); + + void bookPriceUpdated(String title, double price); +} diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java new file mode 100644 index 000000000000..b4a368c98319 --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java @@ -0,0 +1,143 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.commandes; + +import com.iluwatar.cqrs.domain.model.Author; +import com.iluwatar.cqrs.domain.model.Book; +import com.iluwatar.cqrs.util.HibernateUtil; +import org.hibernate.SessionFactory; + +/** + * This class is an implementation of {@link CommandService} interface. It uses Hibernate as an api + * for persistence. + */ +public class CommandServiceImpl implements CommandService { + + private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); + + private Author getAuthorByUsername(String username) { + Author author; + try (var session = sessionFactory.openSession()) { + var query = session.createQuery("from Author where username=:username"); + query.setParameter("username", username); + author = (Author) query.uniqueResult(); + } + if (author == null) { + HibernateUtil.getSessionFactory().close(); + throw new NullPointerException("Author " + username + " doesn't exist!"); + } + return author; + } + + private Book getBookByTitle(String title) { + Book book; + try (var session = sessionFactory.openSession()) { + var query = session.createQuery("from Book where title=:title"); + query.setParameter("title", title); + book = (Book) query.uniqueResult(); + } + if (book == null) { + HibernateUtil.getSessionFactory().close(); + throw new NullPointerException("Book " + title + " doesn't exist!"); + } + return book; + } + + @Override + public void authorCreated(String username, String name, String email) { + var author = new Author(username, name, email); + try (var session = sessionFactory.openSession()) { + session.beginTransaction(); + session.save(author); + session.getTransaction().commit(); + } + } + + @Override + public void bookAddedToAuthor(String title, double price, String username) { + var author = getAuthorByUsername(username); + var book = new Book(title, price, author); + try (var session = sessionFactory.openSession()) { + session.beginTransaction(); + session.save(book); + session.getTransaction().commit(); + } + } + + @Override + public void authorNameUpdated(String username, String name) { + var author = getAuthorByUsername(username); + author.setName(name); + try (var session = sessionFactory.openSession()) { + session.beginTransaction(); + session.update(author); + session.getTransaction().commit(); + } + } + + @Override + public void authorUsernameUpdated(String oldUsername, String newUsername) { + var author = getAuthorByUsername(oldUsername); + author.setUsername(newUsername); + try (var session = sessionFactory.openSession()) { + session.beginTransaction(); + session.update(author); + session.getTransaction().commit(); + } + } + + @Override + public void authorEmailUpdated(String username, String email) { + var author = getAuthorByUsername(username); + author.setEmail(email); + try (var session = sessionFactory.openSession()) { + session.beginTransaction(); + session.update(author); + session.getTransaction().commit(); + } + } + + @Override + public void bookTitleUpdated(String oldTitle, String newTitle) { + var book = getBookByTitle(oldTitle); + book.setTitle(newTitle); + try (var session = sessionFactory.openSession()) { + session.beginTransaction(); + session.update(book); + session.getTransaction().commit(); + } + } + + @Override + public void bookPriceUpdated(String title, double price) { + var book = getBookByTitle(title); + book.setPrice(price); + try (var session = sessionFactory.openSession()) { + session.beginTransaction(); + session.update(book); + session.getTransaction().commit(); + } + } +} diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java new file mode 100644 index 000000000000..71d266f43c35 --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java @@ -0,0 +1,34 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.constants; + +/** Class to define the constants. */ +public class AppConstants { + + public static final String E_EVANS = "eEvans"; + public static final String J_BLOCH = "jBloch"; + public static final String M_FOWLER = "mFowler"; + public static final String USER_NAME = "username"; +} diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Author.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Author.java new file mode 100644 index 000000000000..03155d67a30b --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Author.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.domain.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** This is an Author entity. It is used by Hibernate for persistence. */ +@ToString +@Getter +@Setter +@Entity +public class Author { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String username; + private String name; + private String email; + + /** + * Constructor. + * + * @param username username of the author + * @param name name of the author + * @param email email of the author + */ + public Author(String username, String name, String email) { + this.username = username; + this.name = name; + this.email = email; + } + + protected Author() {} +} diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Book.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Book.java new file mode 100644 index 000000000000..2e2c356528e9 --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Book.java @@ -0,0 +1,67 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.domain.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * This is a Book entity. It is used by Hibernate for persistence. Many books can be written by one + * {@link Author} + */ +@ToString +@Setter +@Getter +@Entity +public class Book { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String title; + private double price; + @ManyToOne private Author author; + + /** + * Constructor. + * + * @param title title of the book + * @param price price of the book + * @param author author of the book + */ + public Book(String title, double price, Author author) { + this.title = title; + this.price = price; + this.author = author; + } + + protected Book() {} +} diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Author.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Author.java new file mode 100644 index 000000000000..58074e6dafe2 --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Author.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.dto; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; + +/** This is a DTO (Data Transfer Object) author, contains only useful information to be returned. */ +@ToString +@EqualsAndHashCode +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class Author { + + private String name; + private String email; + private String username; +} diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Book.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Book.java new file mode 100644 index 000000000000..72ce5b8c249b --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Book.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.dto; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; + +/** This is a DTO (Data Transfer Object) book, contains only useful information to be returned. */ +@ToString +@EqualsAndHashCode +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class Book { + + private String title; + private double price; +} diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryService.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryService.java new file mode 100644 index 000000000000..b37c1dad05a9 --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryService.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.queries; + +import com.iluwatar.cqrs.dto.Author; +import com.iluwatar.cqrs.dto.Book; +import java.math.BigInteger; +import java.util.List; + +/** This interface represents the query methods of the CQRS pattern. */ +public interface QueryService { + + Author getAuthorByUsername(String username); + + Book getBook(String title); + + List getAuthorBooks(String username); + + BigInteger getAuthorBooksCount(String username); + + BigInteger getAuthorsCount(); +} diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java new file mode 100644 index 000000000000..60847d1c6db6 --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java @@ -0,0 +1,111 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.queries; + +import com.iluwatar.cqrs.constants.AppConstants; +import com.iluwatar.cqrs.dto.Author; +import com.iluwatar.cqrs.dto.Book; +import com.iluwatar.cqrs.util.HibernateUtil; +import java.math.BigInteger; +import java.util.List; +import org.hibernate.SessionFactory; +import org.hibernate.query.Query; + +/** + * This class is an implementation of {@link QueryService}. It uses Hibernate native queries to + * return DTOs from the database. + */ +public class QueryServiceImpl implements QueryService { + + private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); + + @Override + public Author getAuthorByUsername(String username) { + Author authorDto; + try (var session = sessionFactory.openSession()) { + Query sqlQuery = + session.createQuery( + "select new com.iluwatar.cqrs.dto.Author(a.name, a.email, a.username)" + + " from com.iluwatar.cqrs.domain.model.Author a where a.username=:username"); + sqlQuery.setParameter(AppConstants.USER_NAME, username); + authorDto = sqlQuery.uniqueResult(); + } + return authorDto; + } + + @Override + public Book getBook(String title) { + Book bookDto; + try (var session = sessionFactory.openSession()) { + Query sqlQuery = + session.createQuery( + "select new com.iluwatar.cqrs.dto.Book(b.title, b.price)" + + " from com.iluwatar.cqrs.domain.model.Book b where b.title=:title"); + sqlQuery.setParameter("title", title); + bookDto = sqlQuery.uniqueResult(); + } + return bookDto; + } + + @Override + public List getAuthorBooks(String username) { + List bookDtos; + try (var session = sessionFactory.openSession()) { + Query sqlQuery = + session.createQuery( + "select new com.iluwatar.cqrs.dto.Book(b.title, b.price)" + + " from com.iluwatar.cqrs.domain.model.Author a, com.iluwatar.cqrs.domain.model.Book b " + + "where b.author.id = a.id and a.username=:username"); + sqlQuery.setParameter(AppConstants.USER_NAME, username); + bookDtos = sqlQuery.list(); + } + return bookDtos; + } + + @Override + public BigInteger getAuthorBooksCount(String username) { + BigInteger bookcount; + try (var session = sessionFactory.openSession()) { + var sqlQuery = + session.createNativeQuery( + "SELECT count(b.title)" + + " FROM Book b, Author a" + + " where b.author_id = a.id and a.username=:username"); + sqlQuery.setParameter(AppConstants.USER_NAME, username); + bookcount = (BigInteger) sqlQuery.uniqueResult(); + } + return bookcount; + } + + @Override + public BigInteger getAuthorsCount() { + BigInteger authorcount; + try (var session = sessionFactory.openSession()) { + var sqlQuery = session.createNativeQuery("SELECT count(id) from Author"); + authorcount = (BigInteger) sqlQuery.uniqueResult(); + } + return authorcount; + } +} diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java new file mode 100644 index 000000000000..0b777fc59b1f --- /dev/null +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs.util; + +import lombok.extern.slf4j.Slf4j; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; + +/** + * This class simply returns one instance of {@link SessionFactory} initialized when the application + * is started. + */ +@Slf4j +public class HibernateUtil { + + private static final SessionFactory SESSIONFACTORY = buildSessionFactory(); + + private static SessionFactory buildSessionFactory() { + + // configures settings from hibernate.cfg.xml + final var registry = new StandardServiceRegistryBuilder().configure().build(); + try { + return new MetadataSources(registry).buildMetadata().buildSessionFactory(); + } catch (Exception ex) { + StandardServiceRegistryBuilder.destroy(registry); + LOGGER.error("Initial SessionFactory creation failed.", ex); + throw new ExceptionInInitializerError(ex); + } + } + + public static SessionFactory getSessionFactory() { + return SESSIONFACTORY; + } +} diff --git a/command-query-responsibility-segregation/src/main/resources/hibernate.cfg.xml b/command-query-responsibility-segregation/src/main/resources/hibernate.cfg.xml new file mode 100644 index 000000000000..b06dc63ba041 --- /dev/null +++ b/command-query-responsibility-segregation/src/main/resources/hibernate.cfg.xml @@ -0,0 +1,37 @@ + + + + + + org.hibernate.dialect.H2Dialect + org.h2.Driver + jdbc:h2:mem:test + sa + create + + + + diff --git a/command-query-responsibility-segregation/src/main/resources/logback.xml b/command-query-responsibility-segregation/src/main/resources/logback.xml new file mode 100644 index 000000000000..e47ba5f8d781 --- /dev/null +++ b/command-query-responsibility-segregation/src/main/resources/logback.xml @@ -0,0 +1,35 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + diff --git a/command-query-responsibility-segregation/src/test/java/com/iluwatar/cqrs/IntegrationTest.java b/command-query-responsibility-segregation/src/test/java/com/iluwatar/cqrs/IntegrationTest.java new file mode 100644 index 000000000000..a4fb9ed3bb7a --- /dev/null +++ b/command-query-responsibility-segregation/src/test/java/com/iluwatar/cqrs/IntegrationTest.java @@ -0,0 +1,108 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.cqrs.commandes.CommandServiceImpl; +import com.iluwatar.cqrs.dto.Author; +import com.iluwatar.cqrs.dto.Book; +import com.iluwatar.cqrs.queries.QueryService; +import com.iluwatar.cqrs.queries.QueryServiceImpl; +import java.math.BigInteger; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** Integration test of IQueryService and ICommandService with h2 data */ +class IntegrationTest { + + private static QueryService queryService; + + @BeforeAll + static void initializeAndPopulateDatabase() { + var commandService = new CommandServiceImpl(); + queryService = new QueryServiceImpl(); + + // create first author1 + commandService.authorCreated("username1", "name1", "email1"); + + // create author1 and update all its data + commandService.authorCreated("username2", "name2", "email2"); + commandService.authorEmailUpdated("username2", "new_email2"); + commandService.authorNameUpdated("username2", "new_name2"); + commandService.authorUsernameUpdated("username2", "new_username2"); + + // add book1 to author1 + commandService.bookAddedToAuthor("title1", 10, "username1"); + + // add book2 to author1 and update all its data + commandService.bookAddedToAuthor("title2", 20, "username1"); + commandService.bookPriceUpdated("title2", 30); + commandService.bookTitleUpdated("title2", "new_title2"); + } + + @Test + void testGetAuthorByUsername() { + var author = queryService.getAuthorByUsername("username1"); + assertEquals("username1", author.getUsername()); + assertEquals("name1", author.getName()); + assertEquals("email1", author.getEmail()); + } + + @Test + void testGetUpdatedAuthorByUsername() { + var author = queryService.getAuthorByUsername("new_username2"); + var expectedAuthor = new Author("new_name2", "new_email2", "new_username2"); + assertEquals(expectedAuthor, author); + } + + @Test + void testGetBook() { + var book = queryService.getBook("title1"); + assertEquals("title1", book.getTitle()); + assertEquals(10, book.getPrice(), 0.01); + } + + @Test + void testGetAuthorBooks() { + var books = queryService.getAuthorBooks("username1"); + assertEquals(2, books.size()); + assertTrue(books.contains(new Book("title1", 10))); + assertTrue(books.contains(new Book("new_title2", 30))); + } + + @Test + void testGetAuthorBooksCount() { + var bookCount = queryService.getAuthorBooksCount("username1"); + assertEquals(new BigInteger("2"), bookCount); + } + + @Test + void testGetAuthorsCount() { + var authorCount = queryService.getAuthorsCount(); + assertEquals(new BigInteger("2"), authorCount); + } +} diff --git a/command-query-responsibility-segregation/src/test/resources/hibernate.cfg.xml b/command-query-responsibility-segregation/src/test/resources/hibernate.cfg.xml new file mode 100644 index 000000000000..b06dc63ba041 --- /dev/null +++ b/command-query-responsibility-segregation/src/test/resources/hibernate.cfg.xml @@ -0,0 +1,37 @@ + + + + + + org.hibernate.dialect.H2Dialect + org.h2.Driver + jdbc:h2:mem:test + sa + create + + + + diff --git a/command-query-responsibility-segregation/src/test/resources/logback.xml b/command-query-responsibility-segregation/src/test/resources/logback.xml new file mode 100644 index 000000000000..e47ba5f8d781 --- /dev/null +++ b/command-query-responsibility-segregation/src/test/resources/logback.xml @@ -0,0 +1,35 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + diff --git a/command/README.md b/command/README.md index 614654f5bbb6..761267c04019 100644 --- a/command/README.md +++ b/command/README.md @@ -1,51 +1,223 @@ --- -layout: pattern -title: Command -folder: command -permalink: /patterns/command/ -categories: Behavioral -tags: - - Java - - Gang Of Four - - Difficulty-Intermediate - - Functional +title: "Command Pattern in Java: Empowering Flexible Command Execution" +shortTitle: Command +description: "Learn about the Command design pattern in Java with real-world examples, detailed explanations, and practical use cases. Understand how this pattern encapsulates requests as objects to support undo operations and more." +category: Behavioral +language: en +tag: + - Decoupling + - Extensibility + - Gang of Four + - Undo --- ## Also known as -Action, Transaction -## Intent -Encapsulate a request as an object, thereby letting you -parameterize clients with different requests, queue or log requests, and -support undoable operations. +* Action +* Transaction -![alt text](./etc/command.png "Command") +## Intent of Command Design Pattern -## Applicability -Use the Command pattern when you want to +The Command design pattern is a behavioral pattern used in Java programming. It encapsulates a request as an object, allowing for parameterization of clients with queues, requests, and operations. This pattern also supports undoable operations, enhancing flexibility in managing and executing commands. -* parameterize objects by an action to perform. You can express such parameterization in a procedural language with a callback function, that is, a function that's registered somewhere to be called at a later point. Commands are an object-oriented replacement for callbacks. -* specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the original request. If the receiver of a request can be represented in an address space-independent way, then you can transfer a command object for the request to a different process and fulfill the request there -* support undo. The Command's execute operation can store state for reversing its effects in the command itself. The Command interface must have an added Unexecute operation that reverses the effects of a previous call to execute. Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling unexecute and execute, respectively -* support logging changes so that they can be reapplied in case of a system crash. By augmenting the Command interface with load and store operations, you can keep a persistent log of changes. Recovering from a crash involves reloading logged commands from disk and re-executing them with the execute operation -* structure a system around high-level operations build on primitive operations. Such a structure is common in information systems that support transactions. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions the same way. The pattern also makes it easy to extend the system with new transactions +## Detailed Explanation of Command Pattern with Real-World Examples -## Typical Use Case +Real-world example -* to keep a history of requests -* implement callback functionality -* implement the undo functionality +> Imagine a smart home system where you can control devices such as lights, thermostats, and security cameras through a central application. Each command to operate these devices is encapsulated as an object, enabling the system to queue, execute sequentially, and undo commands if necessary. This approach decouples control logic from device implementation, allowing easy addition of new devices or features without altering the core application. This flexibility and functionality illustrate the practical application of the Command design pattern in Java programming. -## Presentations +In plain words -* [Command Pattern](etc/presentation.html) +> Storing requests as command objects allows performing an action or undoing it at a later time. -## Real world examples +Wikipedia says +> In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. + +Sequence diagram + +![Command sequence diagram](./etc/command-sequence-diagram.png) + +## Programmatic Example of Command Pattern in Java + +In the Command pattern, objects are used to encapsulate all information needed to perform an action or trigger an event at a later time. This pattern is particularly useful for implementing undo functionality in applications. + +In our example, a `Wizard` casts spells on a `Goblin`. Each spell is a command object that can be executed and undone, demonstrating the core principles of the Command pattern in Java. The spells are executed on the goblin one by one. The first spell shrinks the goblin and the second makes him invisible. Then the wizard reverses the spells one by one. Each spell here is a command object that can be undone. + +Let's start from the `Wizard` class. + +```java + +@Slf4j +public class Wizard { + + private final Deque undoStack = new LinkedList<>(); + private final Deque redoStack = new LinkedList<>(); + + public Wizard() { + } + + public void castSpell(Runnable runnable) { + runnable.run(); + undoStack.offerLast(runnable); + } + + public void undoLastSpell() { + if (!undoStack.isEmpty()) { + var previousSpell = undoStack.pollLast(); + redoStack.offerLast(previousSpell); + previousSpell.run(); + } + } + + public void redoLastSpell() { + if (!redoStack.isEmpty()) { + var previousSpell = redoStack.pollLast(); + undoStack.offerLast(previousSpell); + previousSpell.run(); + } + } + + @Override + public String toString() { + return "Wizard"; + } +} +``` + +Next, we have the `Goblin` who's the `Target` of the spells. + +```java +@Slf4j +@Getter +@Setter +public abstract class Target { + + private Size size; + + private Visibility visibility; + + public void printStatus() { + LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); + } + + public void changeSize() { + var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL; + setSize(oldSize); + } + + public void changeVisibility() { + var visible = getVisibility() == Visibility.INVISIBLE + ? Visibility.VISIBLE : Visibility.INVISIBLE; + setVisibility(visible); + } +} +``` + +```java +public class Goblin extends Target { + + public Goblin() { + setSize(Size.NORMAL); + setVisibility(Visibility.VISIBLE); + } + + @Override + public String toString() { + return "Goblin"; + } +} +``` + +Finally, we can show the full example of `Wizard` casting spells. + +```java +public static void main(String[] args) { + var wizard = new Wizard(); + var goblin = new Goblin(); + + goblin.printStatus(); + + wizard.castSpell(goblin::changeSize); + goblin.printStatus(); + + wizard.castSpell(goblin::changeVisibility); + goblin.printStatus(); + + wizard.undoLastSpell(); + goblin.printStatus(); + + wizard.undoLastSpell(); + goblin.printStatus(); + + wizard.redoLastSpell(); + goblin.printStatus(); + + wizard.redoLastSpell(); + goblin.printStatus(); +} +``` + +Here's the program output: + +``` +20:13:38.406 [main] INFO com.iluwatar.command.Target -- Goblin, [size=normal] [visibility=visible] +20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=visible] +20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=invisible] +20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=visible] +20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=normal] [visibility=visible] +20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=visible] +20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=invisible] +``` + +## When to Use the Command Pattern in Java + +The Command design pattern is applicable when you need to parameterize objects with actions, support undo operations, or structure a system around high-level operations built on primitive ones. It is commonly used in GUI buttons, database transactions, and macro recording. + +Use the Command pattern when you want to: + +* Parameterize objects with actions to perform, offering an object-oriented alternative to callbacks found in procedural languages. Commands can be registered and executed later. +* Specify, queue, and execute requests at different times, allowing commands to exist independently of the original request and even be transferred across processes. +* Support undo functionality, where the Command’s execute operation stores state and includes an un-execute operation to reverse previous actions. This allows for unlimited undo and redo capabilities by maintaining a history list. +* Log changes to reapply them after a system crash. By adding load and store operations to the Command interface, you can maintain a persistent log of changes and recover by reloading and re-executing commands from this log. +* Structure a system around high-level operations built on primitive operations, which is common in transaction-based systems. The Command pattern models transactions by providing a common interface for invoking and extending operations. +* Keep a history of requests. +* Implement callback functionality. +* Implement undo functionality. + +## Real-World Applications of Command Pattern in Java + +* GUI Buttons and menu items in desktop applications. +* Operations in database systems and transactional systems that support rollback. +* Macro recording in applications like text editors and spreadsheets. * [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) +* [org.junit.runners.model.Statement](https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/model/Statement.java) * [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki) * [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html) -## Credits +## Benefits and Trade-offs of Command Pattern + +Benefits: + +* Decouples the object that invokes the operation from the one that knows how to perform it. +* It's easy to add new Commands, because you don't have to change existing classes. +* You can assemble a set of commands into a composite command. + +Trade-offs: + +* Increases the number of classes for each individual command. +* Can complicate the design by adding multiple layers between senders and receivers. + +## Related Java Design Patterns + +* [Composite](https://java-design-patterns.com/patterns/composite/): Commands can be composed using the Composite pattern to create macro commands. +* [Memento](https://java-design-patterns.com/patterns/memento/): Can be used for implementing undo mechanisms. +* [Observer](https://java-design-patterns.com/patterns/observer/): The pattern can be observed for changes that trigger commands. + +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3PFUqSY) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/command/etc/command-sequence-diagram.png b/command/etc/command-sequence-diagram.png new file mode 100644 index 000000000000..845d0a2fde0c Binary files /dev/null and b/command/etc/command-sequence-diagram.png differ diff --git a/command/etc/command.png b/command/etc/command.png index 81b47d6d0a0c..0f026464ecc4 100644 Binary files a/command/etc/command.png and b/command/etc/command.png differ diff --git a/command/etc/command.ucls b/command/etc/command.ucls index f0e0857d266c..afc7e1762f98 100644 --- a/command/etc/command.ucls +++ b/command/etc/command.ucls @@ -1,116 +1,89 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - \ No newline at end of file + diff --git a/command/etc/command.urm.puml b/command/etc/command.urm.puml new file mode 100644 index 000000000000..f85949c566da --- /dev/null +++ b/command/etc/command.urm.puml @@ -0,0 +1,58 @@ +@startuml +package com.iluwatar.command { + class App { + + App() + + main(args : String[]) {static} + } + class Goblin { + + Goblin() + + toString() : String + + changeSize() + + changeVisibility() + } + enum Size { + + NORMAL {static} + + SMALL {static} + - title : String + + toString() : String + + valueOf(name : String) : Size {static} + + values() : Size[] {static} + } + abstract class Target { + - LOGGER : Logger {static} + - size : Size + - visibility : Visibility + + Target() + + getSize() : Size + + getVisibility() : Visibility + + printStatus() + + setSize(size : Size) + + setVisibility(visibility : Visibility) + + toString() : String {abstract} + } + enum Visibility { + + INVISIBLE {static} + + VISIBLE {static} + - title : String + + toString() : String + + valueOf(name : String) : Visibility {static} + + values() : Visibility[] {static} + } + class Wizard { + - LOGGER : Logger {static} + - redoStack : Deque + - undoStack : Deque + + Wizard() + + castSpell(Runnable : runnable) + + redoLastSpell() + + toString() : String + + undoLastSpell() + } +} +Target --> "-size" Size +Wizard --> "-changeSize" Goblin +Wizard --> "-changeVisibility" Goblin +Target --> "-visibility" Visibility +Goblin --|> Target +App --> "castSpell" Wizard +@enduml diff --git a/command/etc/diagram.png b/command/etc/diagram.png deleted file mode 100644 index 1d3494292b82..000000000000 Binary files a/command/etc/diagram.png and /dev/null differ diff --git a/command/etc/presentation.html b/command/etc/presentation.html deleted file mode 100644 index 88a3f0c66581..000000000000 --- a/command/etc/presentation.html +++ /dev/null @@ -1,243 +0,0 @@ - - - - - Design Patterns - Command Presentation - - - - - - - - - \ No newline at end of file diff --git a/command/pom.xml b/command/pom.xml index 68d4b2064d43..83fb68cbf8e3 100644 --- a/command/pom.xml +++ b/command/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT command - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.command.App + + + + + + + + diff --git a/command/src/main/java/com/iluwatar/command/App.java b/command/src/main/java/com/iluwatar/command/App.java index abf2bb4428a3..a8e0edcdf45c 100644 --- a/command/src/main/java/com/iluwatar/command/App.java +++ b/command/src/main/java/com/iluwatar/command/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,43 +25,38 @@ package com.iluwatar.command; /** - * * The Command pattern is a behavioral design pattern in which an object is used to encapsulate all * information needed to perform an action or trigger an event at a later time. This information - * includes the method name, the object that owns the method and values for the method parameters. - *

    - * Four terms always associated with the command pattern are command, receiver, invoker and client. - * A command object (spell) knows about the receiver (target) and invokes a method of the receiver. - * Values for parameters of the receiver method are stored in the command. The receiver then does - * the work. An invoker object (wizard) knows how to execute a command, and optionally does - * bookkeeping about the command execution. The invoker does not know anything about a concrete - * command, it knows only about command interface. Both an invoker object and several command - * objects are held by a client object (app). The client decides which commands to execute at which - * points. To execute a command, it passes the command object to the invoker object. - *

    - * In other words, in this example the wizard casts spells on the goblin. The wizard keeps track of - * the previous spells cast, so it is easy to undo them. In addition, the wizard keeps track of the - * spells undone, so they can be redone. - * - * + * includes the method name, the object that owns the method, and values for the method parameters. + * + *

    Four terms always associated with the command pattern are command, receiver, invoker and + * client. A command object (spell) knows about the receiver (target) and invokes a method of the + * receiver. An invoker object (wizard) receives a reference to the command to be executed and + * optionally does bookkeeping about the command execution. The invoker does not know anything about + * how the command is executed. The client decides which commands to execute at which points. To + * execute a command, it passes a reference of the function to the invoker object. + * + *

    In other words, in this example the wizard casts spells on the goblin. The wizard keeps track + * of the previous spells cast, so it is easy to undo them. In addition, the wizard keeps track of + * the spells undone, so they can be redone. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - Wizard wizard = new Wizard(); - Goblin goblin = new Goblin(); + var wizard = new Wizard(); + var goblin = new Goblin(); goblin.printStatus(); - wizard.castSpell(new ShrinkSpell(), goblin); + wizard.castSpell(goblin::changeSize); goblin.printStatus(); - wizard.castSpell(new InvisibilitySpell(), goblin); + wizard.castSpell(goblin::changeVisibility); goblin.printStatus(); wizard.undoLastSpell(); diff --git a/command/src/main/java/com/iluwatar/command/Command.java b/command/src/main/java/com/iluwatar/command/Command.java deleted file mode 100644 index 13464a9bce3d..000000000000 --- a/command/src/main/java/com/iluwatar/command/Command.java +++ /dev/null @@ -1,41 +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.command; - -/** - * - * Interface for Commands. - * - */ -public abstract class Command { - - public abstract void execute(Target target); - - public abstract void undo(); - - public abstract void redo(); - - @Override - public abstract String toString(); - -} diff --git a/command/src/main/java/com/iluwatar/command/Goblin.java b/command/src/main/java/com/iluwatar/command/Goblin.java index fac7fdcd643d..911983c7b71d 100644 --- a/command/src/main/java/com/iluwatar/command/Goblin.java +++ b/command/src/main/java/com/iluwatar/command/Goblin.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.command; -/** - * - * Goblin is the target of the spells - * - */ +/** Goblin is the target of the spells. */ public class Goblin extends Target { public Goblin() { @@ -38,5 +36,4 @@ public Goblin() { public String toString() { return "Goblin"; } - } diff --git a/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java b/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java deleted file mode 100644 index 0622e0a49a0a..000000000000 --- a/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java +++ /dev/null @@ -1,58 +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.command; - -/** - * - * InvisibilitySpell is a concrete command - * - */ -public class InvisibilitySpell extends Command { - - private Target target; - - @Override - public void execute(Target target) { - target.setVisibility(Visibility.INVISIBLE); - this.target = target; - } - - @Override - public void undo() { - if (target != null) { - target.setVisibility(Visibility.VISIBLE); - } - } - - @Override - public void redo() { - if (target != null) { - target.setVisibility(Visibility.INVISIBLE); - } - } - - @Override - public String toString() { - return "Invisibility spell"; - } -} diff --git a/command/src/main/java/com/iluwatar/command/ShrinkSpell.java b/command/src/main/java/com/iluwatar/command/ShrinkSpell.java deleted file mode 100644 index eec600d4007b..000000000000 --- a/command/src/main/java/com/iluwatar/command/ShrinkSpell.java +++ /dev/null @@ -1,60 +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.command; - -/** - * - * ShrinkSpell is a concrete command - * - */ -public class ShrinkSpell extends Command { - - private Size oldSize; - private Target target; - - @Override - public void execute(Target target) { - oldSize = target.getSize(); - target.setSize(Size.SMALL); - this.target = target; - } - - @Override - public void undo() { - if (oldSize != null && target != null) { - Size temp = target.getSize(); - target.setSize(oldSize); - oldSize = temp; - } - } - - @Override - public void redo() { - undo(); - } - - @Override - public String toString() { - return "Shrink spell"; - } -} diff --git a/command/src/main/java/com/iluwatar/command/Size.java b/command/src/main/java/com/iluwatar/command/Size.java index 25f94a10109b..203f190a89c4 100644 --- a/command/src/main/java/com/iluwatar/command/Size.java +++ b/command/src/main/java/com/iluwatar/command/Size.java @@ -1,44 +1,41 @@ -/** - * 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.command; - -/** - * - * Enumeration for target size. - * - */ -public enum Size { - - SMALL("small"), NORMAL("normal"); - - private String title; - - Size(String title) { - this.title = title; - } - - @Override - public String toString() { - return title; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.command; + +import lombok.RequiredArgsConstructor; + +/** Enumeration for target size. */ +@RequiredArgsConstructor +public enum Size { + SMALL("small"), + NORMAL("normal"); + + private final String title; + + @Override + public String toString() { + return title; + } +} diff --git a/command/src/main/java/com/iluwatar/command/Target.java b/command/src/main/java/com/iluwatar/command/Target.java index 282a4dd469b9..5885e0c4a9a6 100644 --- a/command/src/main/java/com/iluwatar/command/Target.java +++ b/command/src/main/java/com/iluwatar/command/Target.java @@ -1,66 +1,58 @@ -/** - * 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.command; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Base class for spell targets. - * - */ -public abstract class Target { - - private static final Logger LOGGER = LoggerFactory.getLogger(Target.class); - - private Size size; - - private Visibility visibility; - - public Size getSize() { - return size; - } - - public void setSize(Size size) { - this.size = size; - } - - public Visibility getVisibility() { - return visibility; - } - - public void setVisibility(Visibility visibility) { - this.visibility = visibility; - } - - @Override - public abstract String toString(); - - /** - * Print status - */ - public void printStatus() { - LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.command; + +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + +/** Base class for spell targets. */ +@Slf4j +@Getter +@Setter +public abstract class Target { + + private Size size; + + private Visibility visibility; + + /** Print status. */ + public void printStatus() { + LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); + } + + /** Changes the size of the target. */ + public void changeSize() { + var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL; + setSize(oldSize); + } + + /** Changes the visibility of the target. */ + public void changeVisibility() { + var visible = + getVisibility() == Visibility.INVISIBLE ? Visibility.VISIBLE : Visibility.INVISIBLE; + setVisibility(visible); + } +} diff --git a/command/src/main/java/com/iluwatar/command/Visibility.java b/command/src/main/java/com/iluwatar/command/Visibility.java index 8c360d534d2e..a07e7876b609 100644 --- a/command/src/main/java/com/iluwatar/command/Visibility.java +++ b/command/src/main/java/com/iluwatar/command/Visibility.java @@ -1,44 +1,41 @@ -/** - * 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.command; - -/** - * - * Enumeration for target visibility. - * - */ -public enum Visibility { - - VISIBLE("visible"), INVISIBLE("invisible"); - - private String title; - - Visibility(String title) { - this.title = title; - } - - @Override - public String toString() { - return title; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.command; + +import lombok.RequiredArgsConstructor; + +/** Enumeration for target visibility. */ +@RequiredArgsConstructor +public enum Visibility { + VISIBLE("visible"), + INVISIBLE("invisible"); + + private final String title; + + @Override + public String toString() { + return title; + } +} diff --git a/command/src/main/java/com/iluwatar/command/Wizard.java b/command/src/main/java/com/iluwatar/command/Wizard.java index 866ea0e0f0aa..797c41ec04ad 100644 --- a/command/src/main/java/com/iluwatar/command/Wizard.java +++ b/command/src/main/java/com/iluwatar/command/Wizard.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,58 +24,38 @@ */ package com.iluwatar.command; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Deque; import java.util.LinkedList; +import lombok.extern.slf4j.Slf4j; -/** - * - * Wizard is the invoker of the commands - * - */ +/** Wizard is the invoker of the commands. */ +@Slf4j public class Wizard { - private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class); - - private Deque undoStack = new LinkedList<>(); - private Deque redoStack = new LinkedList<>(); - - public Wizard() { - // comment to ignore sonar issue: LEVEL critical - } + private final Deque undoStack = new LinkedList<>(); + private final Deque redoStack = new LinkedList<>(); - /** - * Cast spell - */ - public void castSpell(Command command, Target target) { - LOGGER.info("{} casts {} at {}", this, command, target); - command.execute(target); - undoStack.offerLast(command); + /** Cast spell. */ + public void castSpell(Runnable runnable) { + runnable.run(); + undoStack.offerLast(runnable); } - /** - * Undo last spell - */ + /** Undo last spell. */ public void undoLastSpell() { if (!undoStack.isEmpty()) { - Command previousSpell = undoStack.pollLast(); + var previousSpell = undoStack.pollLast(); redoStack.offerLast(previousSpell); - LOGGER.info("{} undoes {}", this, previousSpell); - previousSpell.undo(); + previousSpell.run(); } } - /** - * Redo last spell - */ + /** Redo last spell. */ public void redoLastSpell() { if (!redoStack.isEmpty()) { - Command previousSpell = redoStack.pollLast(); + var previousSpell = redoStack.pollLast(); undoStack.offerLast(previousSpell); - LOGGER.info("{} redoes {}", this, previousSpell); - previousSpell.redo(); + previousSpell.run(); } } diff --git a/command/src/test/java/com/iluwatar/command/AppTest.java b/command/src/test/java/com/iluwatar/command/AppTest.java index eb0cf0f8a316..874bc3609d91 100644 --- a/command/src/test/java/com/iluwatar/command/AppTest.java +++ b/command/src/test/java/com/iluwatar/command/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,21 @@ */ package com.iluwatar.command; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import java.io.IOException; +import org.junit.jupiter.api.Test; -/** - * Tests that Command example runs without errors. - */ -public class AppTest { +/** Tests that Command example runs without errors. */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. + */ @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/command/src/test/java/com/iluwatar/command/CommandTest.java b/command/src/test/java/com/iluwatar/command/CommandTest.java index b3a3f48d0458..5e41c884697b 100644 --- a/command/src/test/java/com/iluwatar/command/CommandTest.java +++ b/command/src/test/java/com/iluwatar/command/CommandTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,25 +24,25 @@ */ package com.iluwatar.command; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + /** * The Command pattern is a behavioral design pattern in which an object is used to encapsulate all * information needed to perform an action or trigger an event at a later time. This information * includes the method name, the object that owns the method and values for the method parameters. - * - *

    Four terms always associated with the command pattern are command, receiver, invoker and - * client. A command object (spell) knows about the receiver (target) and invokes a method of - * the receiver.Values for parameters of the receiver method are stored in the command. The receiver - * then does the work. An invoker object (wizard) knows how to execute a command, and optionally - * does bookkeeping about the command execution. The invoker does not know anything about a - * concrete command, it knows only about command interface. Both an invoker object and several - * command objects are held by a client object (app). The client decides which commands to execute - * at which points. To execute a command, it passes the command object to the invoker object. + * + *

    Four terms always associated with the command pattern are command, receiver, invoker and + * client. A command object (spell) knows about the receiver (target) and invokes a method of the + * receiver.Values for parameters of the receiver method are stored in the command. The receiver + * then does the work. An invoker object (wizard) knows how to execute a command, and optionally + * does bookkeeping about the command execution. The invoker does not know anything about a concrete + * command, it knows only about command interface. Both an invoker object and several command + * objects are held by a client object (app). The client decides which commands to execute at which + * points. To execute a command, it passes the command object to the invoker object. */ -public class CommandTest { +class CommandTest { private static final String GOBLIN = "Goblin"; @@ -50,15 +52,15 @@ public class CommandTest { * wizard keeps track of the spells undone, so they can be redone. */ @Test - public void testCommand() { + void testCommand() { - Wizard wizard = new Wizard(); - Goblin goblin = new Goblin(); + var wizard = new Wizard(); + var goblin = new Goblin(); - wizard.castSpell(new ShrinkSpell(), goblin); + wizard.castSpell(goblin::changeSize); verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.VISIBLE); - wizard.castSpell(new InvisibilitySpell(), goblin); + wizard.castSpell(goblin::changeVisibility); verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.INVISIBLE); wizard.undoLastSpell(); @@ -83,11 +85,13 @@ public void testCommand() { * @param expectedSize expected size of the goblin * @param expectedVisibility expected visibility of the goblin */ - private void verifyGoblin(Goblin goblin, String expectedName, Size expectedSize, - Visibility expectedVisibility) { + private void verifyGoblin( + Goblin goblin, String expectedName, Size expectedSize, Visibility expectedVisibility) { assertEquals(expectedName, goblin.toString(), "Goblin's name must be same as expectedName"); assertEquals(expectedSize, goblin.getSize(), "Goblin's size must be same as expectedSize"); - assertEquals(expectedVisibility, goblin.getVisibility(), - "Goblin's visibility must be same as expectedVisibility"); + assertEquals( + expectedVisibility, + goblin.getVisibility(), + "Goblin's visibility must be same as expectedVisibility"); } } diff --git a/commander/README.md b/commander/README.md new file mode 100644 index 000000000000..cb5215296bcf --- /dev/null +++ b/commander/README.md @@ -0,0 +1,123 @@ +--- +title: "Commander Pattern in Java: Orchestrating Complex Commands with Ease" +shortTitle: Commander +description: "Learn about the Commander design pattern in Java, a powerful approach for managing distributed transactions across multiple services. Ensure data consistency and reliability in your microservices architecture with practical examples and use cases." +category: Behavioral +language: en +tag: + - Cloud distributed + - Microservices + - Transactions +head: + - - meta + - name: keywords + content: +--- + +## Also known as + +* Distributed Transaction Commander +* Transaction Coordinator + +## Intent of Commander Design Pattern + +The intent of the Commander pattern in Java, especially in the context of distributed transactions, is to manage and coordinate complex transactions across multiple distributed components or services. This pattern ensures data consistency and integrity in distributed systems, making it crucial for microservices architecture. It encapsulates transaction commands and coordination logic, facilitating the implementation of distributed transaction protocols like two-phase commit or Saga. + +## Detailed Explanation of Commander Pattern with Real-World Examples + +Real-world example + +> Imagine organizing a large international music festival where various bands from around the world are scheduled to perform. Each band's arrival, soundcheck, and performance are akin to individual transactions in a distributed system. This scenario mirrors the Commander pattern in Java, where the "Commander" coordinates distributed transactions to maintain overall consistency and reliability. The festival organizer acts as the "Commander," coordinating these transactions to ensure that if a band's flight is delayed (akin to a transaction failure), there's a backup plan, such as rescheduling or swapping time slots with another band (compensating actions), to keep the overall schedule intact. This setup mirrors the Commander pattern in distributed transactions, where various components must be coordinated to achieve a successful outcome despite individual failures. + +In plain words + +> The Commander pattern turns a request into a stand-alone object, allowing for the parameterization of commands, queueing of actions, and the implementation of undo operations. + +Sequence diagram + +![Commander sequence diagram](./etc/commander-sequence-diagram.png) + +## Programmatic Example of Commander Pattern in Java + +Managing transactions across different services in a distributed system, such as an e-commerce platform with separate `Payment` and `Shipping` microservices, requires careful coordination. Using the Commander pattern in Java for transaction coordination helps ensure data consistency and reliability, even when services experience partial failures. + +A strategy to address this involves using a `Commander` component that orchestrates the process. Initially, the order is processed by the available service (`Shipping` in this case). The `Commander` then attempts to synchronize the order with the currently unavailable service (`Payment`) by storing the order details in a database or queueing it for future processing. This queueing system must also account for possible failures in adding requests to the queue. + +The `Commander` repeatedly tries to process the queued orders to ensure both services eventually reflect the same transaction data. This process involves ensuring idempotence, meaning that even if the same order synchronization request is made multiple times, it will only be executed once, preventing duplicate transactions. The goal is to achieve eventual consistency across services, where all systems are synchronized over time despite initial failures or delays. + +Here's a simplified example of how the `Commander` class is used in the `AppAllCases` class: + +```java +public class AppAllCases { + // ... other methods ... + + // Shipping Database Fail Cases + void itemUnavailableCase() { + var ps = new PaymentService(new PaymentDatabase()); + var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); + var ms = new MessagingService(new MessagingDatabase()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = new QueueDatabase(); + // Create a Commander instance + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + // Use the Commander instance to place an order + c.placeOrder(order); + } + + // ... other methods ... +} +``` + +In the `itemUnavailableCase` method, a `Commander` instance is created with the respective services and their databases. Then, a `User` and an `Order` are created, and the `placeOrder` method of the `Commander` instance is called with the order. This triggers the process of placing the order and handling any failures according to the Commander pattern. + +The `Commander` class encapsulates the logic for handling the order placement and any potential failures. This separation of concerns makes the code easier to understand and maintain, and it allows for the reuse of the `Commander` class in different parts of the application. In a real-world application, the `Commander` class would be more complex and would include additional logic for handling different types of failures, retrying failed operations, and coordinating transactions across multiple services. + +Here is the output from executing the `itemUnavailableCase`: + +``` +09:10:13.894 [main] DEBUG com.iluwatar.commander.Commander -- Order YN3V8B7IL2PI: Error in creating shipping request.. +09:10:13.896 [main] INFO com.iluwatar.commander.Commander -- This item is currently unavailable. We will inform you as soon as the item becomes available again. +09:10:13.896 [main] INFO com.iluwatar.commander.Commander -- Order YN3V8B7IL2PI: Item book unavailable, trying to add problem to employee handle.. +09:10:13.897 [Thread-0] INFO com.iluwatar.commander.Commander -- Order YN3V8B7IL2PI: Added order to employee database +``` + +## When to Use the Commander Pattern in Java + +Use the Commander pattern in Java for distributed transactions when: + +* You need to ensure data consistency across distributed services in the event of partial system failures. +* Transactions span multiple microservices or distributed components requiring coordinated commit or rollback. +* You are implementing long-lived transactions requiring compensating actions for rollback. + +## Real-World Applications of Commander Pattern in Java + +* Two-Phase Commit (2PC) Protocols: Coordinating commit or rollback across distributed databases or services. +* Saga Pattern Implementations: Managing long-lived business processes that span multiple microservices, with each step having a compensating action for rollback. +* Distributed Transactions in Microservices Architecture: Coordinating complex operations across microservices while maintaining data integrity and consistency. + +## Benefits and Trade-offs of Commander Pattern + +Benefits: + +* Provides a clear mechanism for managing complex distributed transactions, enhancing system reliability. +* Enables the implementation of compensating transactions, which are crucial for maintaining consistency in long-lived transactions. +* Facilitates the integration of heterogeneous systems within a transactional context. + +Trade-offs: + +* Increases complexity, especially in failure scenarios, due to the need for coordinated rollback mechanisms. +* Potentially impacts performance due to the overhead of coordination and consistency checks. +* Saga-based implementations can lead to increased complexity in understanding the overall business process flow. + +## Related Java Design Patterns + +* [Saga Pattern](https://java-design-patterns.com/patterns/saga/): Often discussed in tandem with the Commander pattern for distributed transactions, focusing on long-lived transactions with compensating actions. + +## References and Credits + +* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/4aATcRe) +* [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/4axHwOV) +* [Microservices Patterns: With examples in Java](https://amzn.to/4axjnYW) +* [Distributed Transactions: The Icebergs of Microservices (Graham Lea)](https://www.grahamlea.com/2016/08/distributed-transactions-microservices-icebergs/) diff --git a/commander/etc/commander-sequence-diagram.png b/commander/etc/commander-sequence-diagram.png new file mode 100644 index 000000000000..00d6eee0779c Binary files /dev/null and b/commander/etc/commander-sequence-diagram.png differ diff --git a/commander/etc/commander.urm.png b/commander/etc/commander.urm.png new file mode 100644 index 000000000000..6b5ebba75bd6 Binary files /dev/null and b/commander/etc/commander.urm.png differ diff --git a/commander/etc/commander.urm.puml b/commander/etc/commander.urm.puml new file mode 100644 index 000000000000..959fbfadcf88 --- /dev/null +++ b/commander/etc/commander.urm.puml @@ -0,0 +1,329 @@ +@startuml +package com.iluwatar.commander.queue { + class Queue { + - front : Queue.Node + - rear : Queue.Node + - size : int + ~ Queue() + ~ dequeue() : T + ~ enqueue(obj : T) + ~ isEmpty() : boolean + ~ peek() : T + } + ~class Node { + ~ next : Queue.Node + ~ value : V + ~ Node(obj : V, b : Queue.Node) + } + class QueueDatabase { + - data : Queue + + exceptionsList : List + + QueueDatabase(exc : Exception[]) + + add(t : QueueTask) : QueueTask + + dequeue() : QueueTask + + get(taskId : String) : QueueTask + + peek() : QueueTask + } + class QueueTask { + + firstAttemptTime : long + + messageType : int + + order : Order + + taskType : TaskType + + QueueTask(o : Order, t : TaskType, messageType : int) + + getType() : String + } + enum TaskType { + + EmployeeDb {static} + + Messaging {static} + + Payment {static} + + valueOf(name : String) : TaskType {static} + + values() : TaskType[] {static} + } +} +package com.iluwatar.commander.messagingservice { + class MessagingDatabase { + - data : Hashtable + + MessagingDatabase() + + add(r : MessageRequest) : MessageRequest + + get(requestId : String) : MessageRequest + } + class MessagingService { + - LOGGER : Logger {static} + + MessagingService(db : MessagingDatabase, exc : Exception[]) + + receiveRequest(parameters : Object[]) : String + ~ sendMessage(m : MessageToSend) : String + # updateDb(parameters : Object[]) : String + } + ~class MessageRequest { + ~ msg : MessageToSend + ~ reqId : String + ~ MessageRequest(this$0 : String, reqId : MessageToSend) + } + ~enum MessageToSend { + + PaymentFail {static} + + PaymentSuccessful {static} + + PaymentTrying {static} + + valueOf(name : String) : MessageToSend {static} + + values() : MessageToSend[] {static} + } +} +package com.iluwatar.commander { + class AppEmployeeDbFailCases { + - employeeTime : long + - messageTime : long + - numOfRetries : int + - paymentTime : long + - queueTaskTime : long + - queueTime : long + - retryDuration : long + + AppEmployeeDbFailCases() + ~ employeeDatabaseUnavailableCase() + ~ employeeDbSuccessCase() + + main(args : String[]) {static} + } + class AppMessagingFailCases { + - employeeTime : long + - messageTime : long + - numOfRetries : int + - paymentTime : long + - queueTaskTime : long + - queueTime : long + - retryDuration : long + + AppMessagingFailCases() + + main(args : String[]) {static} + ~ messagingDatabaseUnavailableCasePaymentError() + ~ messagingDatabaseUnavailableCasePaymentFailure() + ~ messagingDatabaseUnavailableCasePaymentSuccess() + ~ messagingSuccessCase() + } + class AppPaymentFailCases { + - employeeTime : long + - messageTime : long + - numOfRetries : int + - paymentTime : long + - queueTaskTime : long + - queueTime : long + - retryDuration : long + + AppPaymentFailCases() + + main(args : String[]) {static} + ~ paymentDatabaseUnavailableCase() + ~ paymentNotPossibleCase() + ~ paymentSuccessCase() + } + class AppQueueFailCases { + - employeeTime : long + - messageTime : long + - numOfRetries : int + - paymentTime : long + - queueTaskTime : long + - queueTime : long + - retryDuration : long + + AppQueueFailCases() + + main(args : String[]) {static} + ~ queueEmployeeDbTaskDatabaseUnavailableCase() + ~ queueMessageTaskDatabaseUnavailableCase() + ~ queuePaymentTaskDatabaseUnavailableCase() + ~ queueSuccessCase() + } + class AppShippingFailCases { + - employeeTime : long + - messageTime : long + - numOfRetries : int + - paymentTime : long + - queueTaskTime : long + - queueTime : long + - retryDuration : long + + AppShippingFailCases() + ~ itemUnavailableCase() + + main(args : String[]) {static} + ~ shippingDatabaseUnavailableCase() + ~ shippingNotPossibleCase() + ~ shippingSuccessCase() + } + class Commander { + - LOG : Logger {static} + - employeeDb : EmployeeHandle + - employeeTime : long + - finalSiteMsgShown : boolean + - messageTime : long + - messagingService : MessagingService + - numOfRetries : int + - paymentService : PaymentService + - paymentTime : long + - queue : QueueDatabase + - queueItems : int + - queueTaskTime : long + - queueTime : long + - retryDuration : long + - shippingService : ShippingService + ~ Commander(empDb : EmployeeHandle, paymentService : PaymentService, shippingService : ShippingService, messagingService : MessagingService, qdb : QueueDatabase, numOfRetries : int, retryDuration : long, queueTime : long, queueTaskTime : long, paymentTime : long, messageTime : long, employeeTime : long) + - doTasksInQueue() + - employeeHandleIssue(order : Order) + ~ placeOrder(order : Order) + - sendPaymentFailureMessage(order : Order) + - sendPaymentPossibleErrorMsg(order : Order) + - sendPaymentRequest(order : Order) + - sendShippingRequest(order : Order) + - sendSuccessMessage(order : Order) + - tryDequeue() + - tryDoingTasksInQueue() + - updateQueue(qt : QueueTask) + } + abstract class Database { + + Database() + + add(T) : T {abstract} + + get(String) : T {abstract} + } + class Order { + - ALL_CHARS : String {static} + - RANDOM : Random {static} + - USED_IDS : Hashtable {static} + ~ addedToEmployeeHandle : boolean + ~ createdTime : long + + id : String + ~ item : String + ~ messageSent : MessageSent + ~ paid : PaymentStatus + ~ price : float + ~ user : User + ~ Order(user : User, item : String, price : float) + - createUniqueId() : String + } + ~enum MessageSent { + + NoneSent {static} + + PaymentFail {static} + + PaymentSuccessful {static} + + PaymentTrying {static} + + valueOf(name : String) : MessageSent {static} + + values() : MessageSent[] {static} + } + ~enum PaymentStatus { + + Done {static} + + NotDone {static} + + Trying {static} + + valueOf(name : String) : PaymentStatus {static} + + values() : PaymentStatus[] {static} + } + class Retry { + - RANDOM : Random {static} + - attempts : AtomicInteger + - errors : List + - handleError : Retry.HandleErrorIssue + - maxAttempts : int + - maxDelay : long + - op : Operation + - test : Predicate + ~ Retry(op : Operation, handleError : Retry.HandleErrorIssue, maxAttempts : int, maxDelay : long, ignoreTests : Predicate[]) + + perform(list : List, obj : T) + } + interface HandleErrorIssue { + + handleIssue(T, Exception) {abstract} + } + interface Operation { + + operation(List) {abstract} + } + abstract class Service { + - ALL_CHARS : String {static} + - RANDOM : Random {static} + - USED_IDS : Hashtable {static} + # database : Database + + exceptionsList : ArrayList + # Service(db : Database, exc : Exception[]) + # generateId() : String + + receiveRequest(Object[]) : String {abstract} + # updateDb(Object[]) : String {abstract} + } + class User { + ~ address : String + ~ name : String + ~ User(name : String, address : String) + } +} +package com.iluwatar.commander.shippingservice { + class ShippingDatabase { + - data : Hashtable + + ShippingDatabase() + + add(r : ShippingRequest) : ShippingRequest + + get(trasnactionId : String) : ShippingRequest + } + class ShippingService { + + ShippingService(db : ShippingDatabase, exc : Exception[]) + + receiveRequest(parameters : Object[]) : String + # updateDb(parameters : Object[]) : String + } + ~class ShippingRequest { + ~ address : String + ~ item : String + ~ transactionId : String + ~ ShippingRequest(transactionId : String, item : String, address : String) + } +} +package com.iluwatar.commander.paymentservice { + class PaymentDatabase { + - data : Hashtable + + PaymentDatabase() + + add(r : PaymentRequest) : PaymentRequest + + get(requestId : String) : PaymentRequest + } + class PaymentService { + + PaymentService(db : PaymentDatabase, exc : Exception[]) + + receiveRequest(parameters : Object[]) : String + # updateDb(parameters : Object[]) : String + } + ~class PaymentRequest { + ~ paid : boolean + ~ payment : float + ~ transactionId : String + ~ PaymentRequest(this$0 : String, transactionId : float) + } +} +package com.iluwatar.commander.employeehandle { + class EmployeeDatabase { + - data : Hashtable + + EmployeeDatabase() + + add(o : Order) : Order + + get(orderId : String) : Order + } + class EmployeeHandle { + + EmployeeHandle(db : EmployeeDatabase, exc : Exception[]) + + receiveRequest(parameters : Object[]) : String + # updateDb(parameters : Object[]) : String + } +} +Order --> "-messageSent" MessageSent +MessageSent ..+ Order +MessageToSend ..+ MessagingService +Retry --> "-op" Operation +Operation ..+ Retry +Service --> "-database" Database +Node --> "-next" Node +PaymentRequest --+ PaymentService +Commander --> "-messagingService" MessagingService +ShippingRequest ..+ ShippingService +Commander --> "-shippingService" ShippingService +Commander --> "-paymentService" PaymentService +MessageRequest --+ MessagingService +Commander --> "-employeeDb" EmployeeHandle +HandleErrorIssue ..+ Retry +Retry --> "-handleError" HandleErrorIssue +QueueTask --> "-taskType" TaskType +TaskType ..+ QueueTask +Order --> "-user" User +MessageRequest --> "-msg" MessageToSend +QueueTask --> "-order" Order +Commander --> "-queue" QueueDatabase +QueueDatabase --> "-data" Queue +Queue --> "-front" Node +Node ..+ Queue +Order --> "-paid" PaymentStatus +PaymentStatus ..+ Order +EmployeeDatabase --|> Database +EmployeeHandle --|> Service +MessagingDatabase --|> Database +MessagingService --|> Service +PaymentDatabase --|> Database +PaymentService --|> Service +QueueDatabase --|> Database +ShippingDatabase --|> Database +ShippingService --|> Service +@enduml \ No newline at end of file diff --git a/commander/pom.xml b/commander/pom.xml new file mode 100644 index 000000000000..1dbe2dc89de5 --- /dev/null +++ b/commander/pom.xml @@ -0,0 +1,75 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + commander + + 2.0.17 + 1.5.6 + + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + + allCases + + + + com.iluwatar.commander.AppAllCases + + + ${project.artifactId}-AllCases + + + + + + + + diff --git a/commander/src/main/java/com/iluwatar/commander/AppAllCases.java b/commander/src/main/java/com/iluwatar/commander/AppAllCases.java new file mode 100644 index 000000000000..51fa1fed4f34 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/AppAllCases.java @@ -0,0 +1,517 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +import com.iluwatar.commander.employeehandle.EmployeeDatabase; +import com.iluwatar.commander.employeehandle.EmployeeHandle; +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import com.iluwatar.commander.exceptions.ItemUnavailableException; +import com.iluwatar.commander.exceptions.PaymentDetailsErrorException; +import com.iluwatar.commander.messagingservice.MessagingDatabase; +import com.iluwatar.commander.messagingservice.MessagingService; +import com.iluwatar.commander.paymentservice.PaymentDatabase; +import com.iluwatar.commander.paymentservice.PaymentService; +import com.iluwatar.commander.queue.QueueDatabase; +import com.iluwatar.commander.shippingservice.ShippingDatabase; +import com.iluwatar.commander.shippingservice.ShippingService; + +/** + * The {@code AppAllCases} class tests various scenarios for the microservices involved in the order + * placement process. This class consolidates previously separated cases into a single class to + * manage different success and failure scenarios for each service. + * + *

    The application consists of abstract classes {@link Database} and {@link Service} which are + * extended by all the databases and services. Each service has a corresponding database to be + * updated and receives requests from an external user through the {@link Commander} class. There + * are 5 microservices: + * + *

      + *
    • {@link ShippingService} + *
    • {@link PaymentService} + *
    • {@link MessagingService} + *
    • {@link EmployeeHandle} + *
    • {@link QueueDatabase} + *
    + * + *

    Retries are managed using the {@link Retry} class, ensuring idempotence by performing checks + * before making requests to services and updating the {@link Order} class fields upon request + * success or definitive failure. + * + *

    This class tests the following scenarios: + * + *

      + *
    • Employee database availability and unavailability + *
    • Payment service success and failures + *
    • Messaging service database availability and unavailability + *
    • Queue database availability and unavailability + *
    • Shipping service success and failures + *
    + * + *

    Each scenario is encapsulated in a corresponding method that sets up the service conditions + * and tests the order placement process. + * + *

    The main method executes all success and failure cases to verify the application's behavior + * under different conditions. + * + *

    Usage: + * + *

    {@code
    + * public static void main(String[] args) {
    + *     AppAllCases app = new AppAllCases();
    + *     app.testAllScenarios();
    + * }
    + * }
    + */ +public class AppAllCases { + private static final RetryParams retryParams = RetryParams.DEFAULT; + private static final TimeLimits timeLimits = TimeLimits.DEFAULT; + + // Employee Database Fail Case + void employeeDatabaseUnavailableCase() { + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var ss = new ShippingService(new ShippingDatabase()); + var ms = new MessagingService(new MessagingDatabase()); + var eh = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + // Employee Database Success Case + void employeeDbSuccessCase() { + var ps = new PaymentService(new PaymentDatabase()); + var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); + var ms = new MessagingService(new MessagingDatabase()); + var eh = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = new QueueDatabase(); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + // Messaging Database Fail Cases + void messagingDatabaseUnavailableCasePaymentSuccess() { + var ps = new PaymentService(new PaymentDatabase()); + var ss = new ShippingService(new ShippingDatabase()); + var ms = + new MessagingService( + new MessagingDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = new QueueDatabase(); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + void messagingDatabaseUnavailableCasePaymentError() { + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var ss = new ShippingService(new ShippingDatabase()); + var ms = + new MessagingService( + new MessagingDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = new QueueDatabase(); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + void messagingDatabaseUnavailableCasePaymentFailure() { + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var ss = new ShippingService(new ShippingDatabase()); + var ms = + new MessagingService( + new MessagingDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + // Messaging Database Success Case + void messagingSuccessCase() { + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var ss = new ShippingService(new ShippingDatabase()); + var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = new QueueDatabase(); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + // Payment Database Fail Cases + void paymentNotPossibleCase() { + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new PaymentDetailsErrorException()); + var ss = new ShippingService(new ShippingDatabase()); + var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = new QueueDatabase(new DatabaseUnavailableException()); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + void paymentDatabaseUnavailableCase() { + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var ss = new ShippingService(new ShippingDatabase()); + var ms = new MessagingService(new MessagingDatabase()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = new QueueDatabase(); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + // Payment Database Success Case + void paymentSuccessCase() { + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var ss = new ShippingService(new ShippingDatabase()); + var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = new QueueDatabase(new DatabaseUnavailableException()); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + // Queue Database Fail Cases + void queuePaymentTaskDatabaseUnavailableCase() { + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var ss = new ShippingService(new ShippingDatabase()); + var ms = new MessagingService(new MessagingDatabase()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + void queueMessageTaskDatabaseUnavailableCase() { + var ps = new PaymentService(new PaymentDatabase()); + var ss = new ShippingService(new ShippingDatabase()); + var ms = + new MessagingService( + new MessagingDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + void queueEmployeeDbTaskDatabaseUnavailableCase() { + var ps = new PaymentService(new PaymentDatabase()); + var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); + var ms = new MessagingService(new MessagingDatabase()); + var eh = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + // Queue Database Success Cases + void queueSuccessCase() { + var ps = new PaymentService(new PaymentDatabase()); + var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); + var ms = new MessagingService(new MessagingDatabase()); + var eh = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = new QueueDatabase(); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + // Shipping Database Fail Cases + void itemUnavailableCase() { + var ps = new PaymentService(new PaymentDatabase()); + var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); + var ms = new MessagingService(new MessagingDatabase()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = new QueueDatabase(); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + void shippingDatabaseUnavailableCase() { + var ps = new PaymentService(new PaymentDatabase()); + var ss = + new ShippingService( + new ShippingDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var ms = new MessagingService(new MessagingDatabase()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = new QueueDatabase(); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + void shippingItemNotPossibleCase() { + var ps = new PaymentService(new PaymentDatabase()); + var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); + var ms = new MessagingService(new MessagingDatabase()); + var eh = new EmployeeHandle(new EmployeeDatabase()); + var qdb = new QueueDatabase(); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + // Shipping Database Success Cases + void shippingSuccessCase() { + var ps = new PaymentService(new PaymentDatabase()); + var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); + var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + var eh = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = new QueueDatabase(); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + c.placeOrder(order); + } + + /** + * Program entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + AppAllCases app = new AppAllCases(); + + // Employee Database cases + app.employeeDatabaseUnavailableCase(); + app.employeeDbSuccessCase(); + + // Messaging Database cases + app.messagingDatabaseUnavailableCasePaymentSuccess(); + app.messagingDatabaseUnavailableCasePaymentError(); + app.messagingDatabaseUnavailableCasePaymentFailure(); + app.messagingSuccessCase(); + + // Payment Database cases + app.paymentNotPossibleCase(); + app.paymentDatabaseUnavailableCase(); + app.paymentSuccessCase(); + + // Queue Database cases + app.queuePaymentTaskDatabaseUnavailableCase(); + app.queueMessageTaskDatabaseUnavailableCase(); + app.queueEmployeeDbTaskDatabaseUnavailableCase(); + app.queueSuccessCase(); + + // Shipping Database cases + app.itemUnavailableCase(); + app.shippingDatabaseUnavailableCase(); + app.shippingItemNotPossibleCase(); + app.shippingSuccessCase(); + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/Commander.java b/commander/src/main/java/com/iluwatar/commander/Commander.java new file mode 100644 index 000000000000..b25e1c128c6d --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/Commander.java @@ -0,0 +1,746 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +import com.iluwatar.commander.Order.MessageSent; +import com.iluwatar.commander.Order.PaymentStatus; +import com.iluwatar.commander.employeehandle.EmployeeHandle; +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import com.iluwatar.commander.exceptions.IsEmptyException; +import com.iluwatar.commander.exceptions.ItemUnavailableException; +import com.iluwatar.commander.exceptions.PaymentDetailsErrorException; +import com.iluwatar.commander.exceptions.ShippingNotPossibleException; +import com.iluwatar.commander.messagingservice.MessagingService; +import com.iluwatar.commander.paymentservice.PaymentService; +import com.iluwatar.commander.queue.QueueDatabase; +import com.iluwatar.commander.queue.QueueTask; +import com.iluwatar.commander.queue.QueueTask.TaskType; +import com.iluwatar.commander.shippingservice.ShippingService; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Commander pattern is used to handle all issues that can come up while making a distributed + * transaction. The idea is to have a commander, which coordinates the execution of all instructions + * and ensures proper completion using retries and taking care of idempotence. By queueing + * instructions while they haven't been done, we can ensure a state of 'eventual consistency'. + * + *

    In our example, we have an e-commerce application. When the user places an order, the shipping + * service is intimated first. If the service does not respond for some reason, the order is not + * placed. If response is received, the commander then calls for the payment service to be + * intimated. If this fails, the shipping still takes place (order converted to COD) and the item is + * queued. If the queue is also found to be unavailable, the payment is noted to be not done and + * this is added to an employee database. Three types of messages are sent to the user - one, if + * payment succeeds; two, if payment fails definitively; and three, if payment fails in the first + * attempt. If the message is not sent, this is also queued and is added to employee db. We also + * have a time limit for each instruction to be completed, after which, the instruction is not + * executed, thereby ensuring that resources are not held for too long. In the rare occasion in + * which everything fails, an individual would have to step in to figure out how to solve the issue. + * + *

    We have abstract classes {@link Database} and {@link Service} which are extended by all the + * databases and services. Each service has a database to be updated, and receives request from an + * outside user (the {@link Commander} class here). There are 5 microservices - {@link + * ShippingService}, {@link PaymentService}, {@link MessagingService}, {@link EmployeeHandle} and a + * {@link QueueDatabase}. We use retries to execute any instruction using {@link Retry} class, and + * idempotence is ensured by going through some checks before making requests to services and making + * change in {@link Order} class fields if request succeeds or definitively fails. There is a single + * class {@link AppAllCases} that looks at the different scenarios that may be encountered during + * the placing of an order, including both success and failure cases for each service. + */ +public class Commander { + + private final QueueDatabase queue; + private final EmployeeHandle employeeDb; + private final PaymentService paymentService; + private final ShippingService shippingService; + private final MessagingService messagingService; + private int queueItems = + 0; // keeping track here only so don't need access to queue db to get this + private final int numOfRetries; + private final long retryDuration; + private final long queueTime; + private final long queueTaskTime; + private final long paymentTime; + private final long messageTime; + private final long employeeTime; + private boolean finalSiteMsgShown; + + private static final Logger LOG = LoggerFactory.getLogger(Commander.class); + // we could also have another db where it stores all orders + + private static final String ORDER_ID = "Order {}"; + private static final String REQUEST_ID = " request Id: {}"; + private static final String ERROR_CONNECTING_MSG_SVC = + ": Error in connecting to messaging service "; + private static final String TRY_CONNECTING_MSG_SVC = ": Trying to connect to messaging service.."; + + private static final String DEFAULT_EXCEPTION_MESSAGE = "An exception occurred"; + + Commander( + EmployeeHandle empDb, + PaymentService paymentService, + ShippingService shippingService, + MessagingService messagingService, + QueueDatabase qdb, + RetryParams retryParams, + TimeLimits timeLimits) { + this.paymentService = paymentService; + this.shippingService = shippingService; + this.messagingService = messagingService; + this.employeeDb = empDb; + this.queue = qdb; + this.numOfRetries = retryParams.numOfRetries(); + this.retryDuration = retryParams.retryDuration(); + this.queueTime = timeLimits.queueTime(); + this.queueTaskTime = timeLimits.queueTaskTime(); + this.paymentTime = timeLimits.paymentTime(); + this.messageTime = timeLimits.messageTime(); + this.employeeTime = timeLimits.employeeTime(); + this.finalSiteMsgShown = false; + } + + void placeOrder(Order order) { + sendShippingRequest(order); + } + + private void sendShippingRequest(Order order) { + var list = shippingService.exceptionsList; + Retry.Operation op = + l -> { + if (!l.isEmpty()) { + if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { + LOG.debug( + ORDER_ID + ": Error in connecting to shipping service, " + "trying again..", + order.id); + } else { + LOG.debug(ORDER_ID + ": Error in creating shipping request..", order.id); + } + throw l.remove(0); + } + String transactionId = shippingService.receiveRequest(order.item, order.user.address); + // could save this transaction id in a db too + LOG.info( + ORDER_ID + ": Shipping placed successfully, transaction id: {}", + order.id, + transactionId); + LOG.info( + "Order has been placed and will be shipped to you. Please wait while we make your" + + " payment... "); + sendPaymentRequest(order); + }; + Retry.HandleErrorIssue handleError = + (o, err) -> { + if (ShippingNotPossibleException.class.isAssignableFrom(err.getClass())) { + LOG.info( + "Shipping is currently not possible to your address. We are working on the problem" + + " and will get back to you asap."); + finalSiteMsgShown = true; + LOG.info( + ORDER_ID + + ": Shipping not possible to address, trying to add problem " + + "to employee db..", + order.id); + employeeHandleIssue(o); + } else if (ItemUnavailableException.class.isAssignableFrom(err.getClass())) { + LOG.info( + "This item is currently unavailable. We will inform you as soon as the item " + + "becomes available again."); + finalSiteMsgShown = true; + LOG.info( + ORDER_ID + + ": Item {}" + + " unavailable, trying to add " + + "problem to employee handle..", + order.id, + order.item); + employeeHandleIssue(o); + } else { + LOG.info("Sorry, there was a problem in creating your order. Please try later."); + LOG.error(ORDER_ID + ": Shipping service unavailable, order not placed..", order.id); + finalSiteMsgShown = true; + } + }; + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + r.perform(list, order); + } + + private void sendPaymentRequest(Order order) { + if (System.currentTimeMillis() - order.createdTime >= this.paymentTime) { + if (order.paid.equals(PaymentStatus.TRYING)) { + order.paid = PaymentStatus.NOT_DONE; + sendPaymentFailureMessage(order); + LOG.error(ORDER_ID + ": Payment time for order over, failed and returning..", order.id); + } // if succeeded or failed, would have been dequeued, no attempt to make payment + return; + } + var list = paymentService.exceptionsList; + var t = + new Thread( + () -> { + Retry.Operation op = getRetryOperation(order); + + Retry.HandleErrorIssue handleError = getRetryHandleErrorIssue(order); + + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, order); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); + + t.start(); + } + + private Retry.HandleErrorIssue getRetryHandleErrorIssue(Order order) { + return (o, err) -> { + if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) { + handlePaymentDetailsError(order.id, o); + } else { + if (o.messageSent.equals(MessageSent.NONE_SENT)) { + handlePaymentError(order.id, o); + } + if (o.paid.equals(PaymentStatus.TRYING) + && System.currentTimeMillis() - o.createdTime < paymentTime) { + var qt = new QueueTask(o, TaskType.PAYMENT, -1); + updateQueue(qt); + } + } + }; + } + + private void handlePaymentError(String orderId, Order o) { + if (!finalSiteMsgShown) { + LOG.info( + "There was an error in payment. We are on it, and will get back to you " + + "asap. Don't worry, your order has been placed and will be shipped."); + finalSiteMsgShown = true; + } + LOG.warn(ORDER_ID + ": Payment error, going to queue..", orderId); + sendPaymentPossibleErrorMsg(o); + } + + private void handlePaymentDetailsError(String orderId, Order o) { + if (!finalSiteMsgShown) { + LOG.info( + "There was an error in payment. Your account/card details " + + "may have been incorrect. " + + "Meanwhile, your order has been converted to COD and will be shipped."); + finalSiteMsgShown = true; + } + LOG.error(ORDER_ID + ": Payment details incorrect, failed..", orderId); + o.paid = PaymentStatus.NOT_DONE; + sendPaymentFailureMessage(o); + } + + private Retry.Operation getRetryOperation(Order order) { + return l -> { + if (!l.isEmpty()) { + if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { + LOG.debug( + ORDER_ID + ": Error in connecting to payment service," + " trying again..", order.id); + } else { + LOG.debug(ORDER_ID + ": Error in creating payment request..", order.id); + } + throw l.remove(0); + } + if (order.paid.equals(PaymentStatus.TRYING)) { + var transactionId = paymentService.receiveRequest(order.price); + order.paid = PaymentStatus.DONE; + LOG.info(ORDER_ID + ": Payment successful, transaction Id: {}", order.id, transactionId); + if (!finalSiteMsgShown) { + LOG.info("Payment made successfully, thank you for shopping with us!!"); + finalSiteMsgShown = true; + } + sendSuccessMessage(order); + } + }; + } + + private void updateQueue(QueueTask qt) { + if (System.currentTimeMillis() - qt.order.createdTime >= this.queueTime) { + // since payment time is lesser than queuetime it would have already failed.. + // additional check not needed + LOG.trace(ORDER_ID + ": Queue time for order over, failed..", qt.order.id); + return; + } else if (qt.taskType.equals(TaskType.PAYMENT) && !qt.order.paid.equals(PaymentStatus.TRYING) + || qt.taskType.equals(TaskType.MESSAGING) + && (qt.messageType == 1 && !qt.order.messageSent.equals(MessageSent.NONE_SENT) + || qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL) + || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) + || qt.taskType.equals(TaskType.EMPLOYEE_DB) && qt.order.addedToEmployeeHandle) { + LOG.trace(ORDER_ID + ": Not queueing task since task already done..", qt.order.id); + return; + } + var list = queue.exceptionsList; + Thread t = + new Thread( + () -> { + Retry.Operation op = + list1 -> { + if (!list1.isEmpty()) { + LOG.warn( + ORDER_ID + ": Error in connecting to queue db, trying again..", + qt.order.id); + throw list1.remove(0); + } + queue.add(qt); + queueItems++; + LOG.info(ORDER_ID + ": {}" + " task enqueued..", qt.order.id, qt.getType()); + tryDoingTasksInQueue(); + }; + Retry.HandleErrorIssue handleError = + (qt1, err) -> { + if (qt1.taskType.equals(TaskType.PAYMENT)) { + qt1.order.paid = PaymentStatus.NOT_DONE; + sendPaymentFailureMessage(qt1.order); + LOG.error( + ORDER_ID + ": Unable to enqueue payment task," + " payment failed..", + qt1.order.id); + } + LOG.error( + ORDER_ID + + ": Unable to enqueue task of type {}" + + ", trying to add to employee handle..", + qt1.order.id, + qt1.getType()); + employeeHandleIssue(qt1.order); + }; + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, qt); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); + t.start(); + } + + private void tryDoingTasksInQueue() { // commander controls operations done to queue + var list = queue.exceptionsList; + var t2 = + new Thread( + () -> { + Retry.Operation op = + list1 -> { + if (!list1.isEmpty()) { + LOG.warn("Error in accessing queue db to do tasks, trying again.."); + throw list1.remove(0); + } + doTasksInQueue(); + }; + Retry.HandleErrorIssue handleError = (o, err) -> {}; + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, null); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); + t2.start(); + } + + private void tryDequeue() { + var list = queue.exceptionsList; + var t3 = + new Thread( + () -> { + Retry.Operation op = + list1 -> { + if (!list1.isEmpty()) { + LOG.warn("Error in accessing queue db to dequeue task, trying again.."); + throw list1.remove(0); + } + queue.dequeue(); + queueItems--; + }; + Retry.HandleErrorIssue handleError = (o, err) -> {}; + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, null); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); + t3.start(); + } + + private void sendSuccessMessage(Order order) { + if (System.currentTimeMillis() - order.createdTime >= this.messageTime) { + LOG.trace(ORDER_ID + ": Message time for order over, returning..", order.id); + return; + } + var list = messagingService.exceptionsList; + Thread t = + new Thread( + () -> { + Retry.Operation op = handleSuccessMessageRetryOperation(order); + Retry.HandleErrorIssue handleError = + (o, err) -> handleSuccessMessageErrorIssue(order, o); + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, order); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); + t.start(); + } + + private void handleSuccessMessageErrorIssue(Order order, Order o) { + if ((o.messageSent.equals(MessageSent.NONE_SENT) + || o.messageSent.equals(MessageSent.PAYMENT_TRYING)) + && System.currentTimeMillis() - o.createdTime < messageTime) { + var qt = new QueueTask(order, TaskType.MESSAGING, 2); + updateQueue(qt); + LOG.info( + ORDER_ID + + ": Error in sending Payment Success message, trying to" + + " queue task and add to employee handle..", + order.id); + employeeHandleIssue(order); + } + } + + private Retry.Operation handleSuccessMessageRetryOperation(Order order) { + return l -> { + if (!l.isEmpty()) { + if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { + LOG.debug( + ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Success msg), trying again..", + order.id); + } else { + LOG.debug( + ORDER_ID + ": Error in creating Payment Success" + " messaging request..", order.id); + } + throw l.remove(0); + } + if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL) + && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { + var requestId = messagingService.receiveRequest(2); + order.messageSent = MessageSent.PAYMENT_SUCCESSFUL; + LOG.info(ORDER_ID + ": Payment Success message sent," + REQUEST_ID, order.id, requestId); + } + }; + } + + private void sendPaymentFailureMessage(Order order) { + if (System.currentTimeMillis() - order.createdTime >= this.messageTime) { + LOG.trace(ORDER_ID + ": Message time for order over, returning..", order.id); + return; + } + var list = messagingService.exceptionsList; + var t = + new Thread( + () -> { + Retry.Operation op = l -> handlePaymentFailureRetryOperation(order, l); + Retry.HandleErrorIssue handleError = + (o, err) -> handlePaymentErrorIssue(order, o); + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, order); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); + t.start(); + } + + private void handlePaymentErrorIssue(Order order, Order o) { + if ((o.messageSent.equals(MessageSent.NONE_SENT) + || o.messageSent.equals(MessageSent.PAYMENT_TRYING)) + && System.currentTimeMillis() - o.createdTime < messageTime) { + var qt = new QueueTask(order, TaskType.MESSAGING, 0); + updateQueue(qt); + LOG.warn( + ORDER_ID + + ": Error in sending Payment Failure message, " + + "trying to queue task and add to employee handle..", + order.id); + employeeHandleIssue(o); + } + } + + private void handlePaymentFailureRetryOperation(Order order, List l) + throws IndexOutOfBoundsException, DatabaseUnavailableException { + if (!l.isEmpty()) { + if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { + LOG.debug( + ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Failure msg), trying again..", + order.id); + } else { + LOG.debug( + ORDER_ID + ": Error in creating Payment Failure" + " message request..", order.id); + } + throw new IndexOutOfBoundsException(); + } + if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL) + && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { + var requestId = messagingService.receiveRequest(0); + order.messageSent = MessageSent.PAYMENT_FAIL; + LOG.info( + ORDER_ID + ": Payment Failure message sent successfully," + REQUEST_ID, + order.id, + requestId); + } + } + + private void sendPaymentPossibleErrorMsg(Order order) { + if (System.currentTimeMillis() - order.createdTime >= this.messageTime) { + LOG.trace("Message time for order over, returning.."); + return; + } + var list = messagingService.exceptionsList; + var t = + new Thread( + () -> { + Retry.Operation op = l -> handlePaymentPossibleErrorMsgRetryOperation(order, l); + Retry.HandleErrorIssue handleError = + (o, err) -> handlePaymentPossibleErrorMsgErrorIssue(order, o); + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, order); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); + t.start(); + } + + private void handlePaymentPossibleErrorMsgErrorIssue(Order order, Order o) { + if (o.messageSent.equals(MessageSent.NONE_SENT) + && order.paid.equals(PaymentStatus.TRYING) + && System.currentTimeMillis() - o.createdTime < messageTime) { + var qt = new QueueTask(order, TaskType.MESSAGING, 1); + updateQueue(qt); + LOG.warn( + "Order {}: Error in sending Payment Error message, trying to queue task and add to employee handle..", + order.id); + employeeHandleIssue(o); + } + } + + private void handlePaymentPossibleErrorMsgRetryOperation(Order order, List l) + throws IndexOutOfBoundsException, DatabaseUnavailableException { + if (!l.isEmpty()) { + if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { + LOG.debug( + ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Error msg), trying again..", order.id); + } else { + LOG.debug( + ORDER_ID + ": Error in creating Payment Error" + " messaging request..", order.id); + } + throw new IndexOutOfBoundsException(); + } + if (order.paid.equals(PaymentStatus.TRYING) + && order.messageSent.equals(MessageSent.NONE_SENT)) { + var requestId = messagingService.receiveRequest(1); + order.messageSent = MessageSent.PAYMENT_TRYING; + LOG.info( + ORDER_ID + ": Payment Error message sent successfully," + REQUEST_ID, + order.id, + requestId); + } + } + + private void employeeHandleIssue(Order order) { + if (System.currentTimeMillis() - order.createdTime >= this.employeeTime) { + LOG.trace(ORDER_ID + ": Employee handle time for order over, returning..", order.id); + return; + } + var list = employeeDb.exceptionsList; + var t = + new Thread( + () -> { + Retry.Operation op = + l -> { + if (!l.isEmpty()) { + LOG.warn( + ORDER_ID + + ": Error in connecting to employee handle," + + " trying again..", + order.id); + throw l.remove(0); + } + if (!order.addedToEmployeeHandle) { + employeeDb.receiveRequest(order); + order.addedToEmployeeHandle = true; + LOG.info(ORDER_ID + ": Added order to employee database", order.id); + } + }; + Retry.HandleErrorIssue handleError = + (o, err) -> { + if (!o.addedToEmployeeHandle + && System.currentTimeMillis() - order.createdTime < employeeTime) { + var qt = new QueueTask(order, TaskType.EMPLOYEE_DB, -1); + updateQueue(qt); + LOG.warn( + ORDER_ID + + ": Error in adding to employee db," + + " trying to queue task..", + order.id); + } + }; + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, order); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); + t.start(); + } + + private void doTasksInQueue() throws IsEmptyException, InterruptedException { + if (queueItems != 0) { + var qt = queue.peek(); // this should probably be cloned here + // this is why we have retry for doTasksInQueue + LOG.trace(ORDER_ID + ": Started doing task of type {}", qt.order.id, qt.getType()); + if (qt.isFirstAttempt()) { + qt.setFirstAttemptTime(System.currentTimeMillis()); + } + if (System.currentTimeMillis() - qt.getFirstAttemptTime() >= queueTaskTime) { + tryDequeue(); + LOG.trace( + ORDER_ID + + ": This queue task of type {}" + + " does not need to be done anymore (timeout), dequeue..", + qt.order.id, + qt.getType()); + } else { + switch (qt.taskType) { + case PAYMENT -> doPaymentTask(qt); + case MESSAGING -> doMessagingTask(qt); + case EMPLOYEE_DB -> doEmployeeDbTask(qt); + default -> throw new IllegalArgumentException("Unknown task type"); + } + } + } + if (queueItems == 0) { + LOG.trace("Queue is empty, returning.."); + } else { + Thread.sleep(queueTaskTime / 3); + tryDoingTasksInQueue(); + } + } + + private void doEmployeeDbTask(QueueTask qt) { + if (qt.order.addedToEmployeeHandle) { + tryDequeue(); + LOG.trace(ORDER_ID + ": This employee handle task already done," + " dequeue..", qt.order.id); + } else { + employeeHandleIssue(qt.order); + LOG.debug(ORDER_ID + ": Trying to connect to employee handle..", qt.order.id); + } + } + + private void doMessagingTask(QueueTask qt) { + if (qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL) + || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { + tryDequeue(); + LOG.trace(ORDER_ID + ": This messaging task already done, dequeue..", qt.order.id); + } else if (qt.messageType == 1 + && (!qt.order.messageSent.equals(MessageSent.NONE_SENT) + || !qt.order.paid.equals(PaymentStatus.TRYING))) { + tryDequeue(); + LOG.trace( + ORDER_ID + ": This messaging task does not need to be done," + " dequeue..", qt.order.id); + } else if (qt.messageType == 0) { + sendPaymentFailureMessage(qt.order); + LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); + } else if (qt.messageType == 1) { + sendPaymentPossibleErrorMsg(qt.order); + LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); + } else if (qt.messageType == 2) { + sendSuccessMessage(qt.order); + LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); + } + } + + private void doPaymentTask(QueueTask qt) { + if (!qt.order.paid.equals(PaymentStatus.TRYING)) { + tryDequeue(); + LOG.trace(ORDER_ID + ": This payment task already done, dequeueing..", qt.order.id); + } else { + sendPaymentRequest(qt.order); + LOG.debug(ORDER_ID + ": Trying to connect to payment service..", qt.order.id); + } + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/Database.java b/commander/src/main/java/com/iluwatar/commander/Database.java new file mode 100644 index 000000000000..a3e3da1693a8 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/Database.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; + +/** + * Database abstract class is extended by all databases in our example. The add and get methods are + * used by the respective service to add to database or get from database. + * + * @param T is the type of object being held by database. + */ +public abstract class Database { + public abstract T add(T obj) throws DatabaseUnavailableException; + + public abstract T get(String id) throws DatabaseUnavailableException; +} diff --git a/commander/src/main/java/com/iluwatar/commander/Order.java b/commander/src/main/java/com/iluwatar/commander/Order.java new file mode 100644 index 000000000000..b998a02974f1 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/Order.java @@ -0,0 +1,85 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.Map; + +/** Order class holds details of the order. */ +public class Order { // can store all transactions ids also + + enum PaymentStatus { + NOT_DONE, + TRYING, + DONE + } + + enum MessageSent { + NONE_SENT, + PAYMENT_FAIL, + PAYMENT_TRYING, + PAYMENT_SUCCESSFUL + } + + final User user; + final String item; + public final String id; + final float price; + final long createdTime; + private static final SecureRandom RANDOM = new SecureRandom(); + private static final String ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + private static final Map USED_IDS = new HashMap<>(); + PaymentStatus paid; + MessageSent messageSent; // to avoid sending error msg on page and text more than once + boolean addedToEmployeeHandle; // to avoid creating more to enqueue + + Order(User user, String item, float price) { + this.createdTime = System.currentTimeMillis(); + this.user = user; + this.item = item; + this.price = price; + String id = createUniqueId(); + if (USED_IDS.get(id) != null) { + while (USED_IDS.get(id)) { + id = createUniqueId(); + } + } + this.id = id; + USED_IDS.put(this.id, true); + this.paid = PaymentStatus.TRYING; + this.messageSent = MessageSent.NONE_SENT; + this.addedToEmployeeHandle = false; + } + + private String createUniqueId() { + StringBuilder random = new StringBuilder(); + while (random.length() < 12) { // length of the random string. + int index = (int) (RANDOM.nextFloat() * ALL_CHARS.length()); + random.append(ALL_CHARS.charAt(index)); + } + return random.toString(); + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/Retry.java b/commander/src/main/java/com/iluwatar/commander/Retry.java new file mode 100644 index 000000000000..661f479174a3 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/Retry.java @@ -0,0 +1,108 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; + +/** + * Retry pattern. + * + * @param is the type of object passed into HandleErrorIssue as a parameter. + */ +public class Retry { + + /** Operation Interface will define method to be implemented. */ + public interface Operation { + void operation(List list) throws Exception; + } + + /** + * HandleErrorIssue defines how to handle errors. + * + * @param is the type of object to be passed into the method as parameter. + */ + public interface HandleErrorIssue { + void handleIssue(T obj, Exception e); + } + + private static final SecureRandom RANDOM = new SecureRandom(); + + private final Operation op; + private final HandleErrorIssue handleError; + private final int maxAttempts; + private final long maxDelay; + private final AtomicInteger attempts; + private final Predicate test; + private final List errors; + + Retry( + Operation op, + HandleErrorIssue handleError, + int maxAttempts, + long maxDelay, + Predicate... ignoreTests) { + this.op = op; + this.handleError = handleError; + this.maxAttempts = maxAttempts; + this.maxDelay = maxDelay; + this.attempts = new AtomicInteger(); + this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false); + this.errors = new ArrayList<>(); + } + + /** + * Performing the operation with retries. + * + * @param list is the exception list + * @param obj is the parameter to be passed into handleIsuue method + */ + public void perform(List list, T obj) { + do { + try { + op.operation(list); + return; + } catch (Exception e) { + this.errors.add(e); + if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) { + this.handleError.handleIssue(obj, e); + return; // return here... don't go further + } + try { + long testDelay = + (long) Math.pow(2, this.attempts.intValue()) * 1000 + RANDOM.nextInt(1000); + long delay = Math.min(testDelay, this.maxDelay); + Thread.sleep(delay); + } catch (InterruptedException f) { + // ignore + } + } + } while (true); + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/RetryParams.java b/commander/src/main/java/com/iluwatar/commander/RetryParams.java new file mode 100644 index 000000000000..9988af8a42e8 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/RetryParams.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +/** + * Record to hold the parameters related to retries. + * + * @param numOfRetries number of retries + * @param retryDuration retry duration + */ +public record RetryParams(int numOfRetries, long retryDuration) { + public static final RetryParams DEFAULT = new RetryParams(3, 30000L); +} diff --git a/commander/src/main/java/com/iluwatar/commander/Service.java b/commander/src/main/java/com/iluwatar/commander/Service.java new file mode 100644 index 000000000000..06aa9a3ce103 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/Service.java @@ -0,0 +1,72 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; + +/** + * Service class is an abstract class extended by all services in this example. They all have a + * public receiveRequest method to receive requests, which could also contain details of the user + * other than the implementation details (though we are not doing that here) and updateDb method + * which adds to their respective databases. There is a method to generate transaction/request id + * for the transactions/requests, which are then sent back. These could be stored by the {@link + * Commander} class in a separate database for reference (though we are not doing that here). + */ +public abstract class Service { + + protected final Database database; + public ArrayList exceptionsList; + private static final SecureRandom RANDOM = new SecureRandom(); + private static final String ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + private static final Hashtable USED_IDS = new Hashtable<>(); + + protected Service(Database db, Exception... exc) { + this.database = db; + this.exceptionsList = new ArrayList<>(List.of(exc)); + } + + public abstract String receiveRequest(Object... parameters) throws DatabaseUnavailableException; + + protected abstract String updateDb(Object... parameters) throws DatabaseUnavailableException; + + protected String generateId() { + StringBuilder random = new StringBuilder(); + while (random.length() < 12) { // length of the random string. + int index = (int) (RANDOM.nextFloat() * ALL_CHARS.length()); + random.append(ALL_CHARS.charAt(index)); + } + String id = random.toString(); + if (USED_IDS.get(id) != null) { + while (USED_IDS.get(id)) { + id = generateId(); + } + } + return id; + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/TimeLimits.java b/commander/src/main/java/com/iluwatar/commander/TimeLimits.java new file mode 100644 index 000000000000..9051fdf29d1a --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/TimeLimits.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +/** + * Record to hold parameters related to time limit for various tasks. + * + * @param queueTime time limit for queue + * @param queueTaskTime time limit for queuing task + * @param paymentTime time limit for payment error message + * @param messageTime time limit for message time order + * @param employeeTime time limit for employee handle time + */ +public record TimeLimits( + long queueTime, long queueTaskTime, long paymentTime, long messageTime, long employeeTime) { + + public static final TimeLimits DEFAULT = + new TimeLimits(240000L, 60000L, 120000L, 150000L, 240000L); +} diff --git a/commander/src/main/java/com/iluwatar/commander/User.java b/commander/src/main/java/com/iluwatar/commander/User.java new file mode 100644 index 000000000000..e32d0024af02 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/User.java @@ -0,0 +1,34 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +import lombok.AllArgsConstructor; + +/** User class contains details of user who places order. */ +@AllArgsConstructor +public class User { + String name; + String address; +} diff --git a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java new file mode 100644 index 000000000000..a139ab323556 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.employeehandle; + +import com.iluwatar.commander.Database; +import com.iluwatar.commander.Order; +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import java.util.HashMap; +import java.util.Map; + +/** The Employee Database is where orders which have encountered some issue(s) are added. */ +public class EmployeeDatabase extends Database { + private final Map data = new HashMap<>(); + + @Override + public Order add(Order o) throws DatabaseUnavailableException { + return data.put(o.id, o); + } + + @Override + public Order get(String orderId) throws DatabaseUnavailableException { + return data.get(orderId); + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java new file mode 100644 index 000000000000..745b71d90114 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.employeehandle; + +import com.iluwatar.commander.Order; +import com.iluwatar.commander.Service; +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; + +/** + * The EmployeeHandle class is the middle-man between {@link com.iluwatar.commander.Commander} and + * {@link EmployeeDatabase}. + */ +public class EmployeeHandle extends Service { + + public EmployeeHandle(EmployeeDatabase db, Exception... exc) { + super(db, exc); + } + + public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { + return updateDb(parameters[0]); + } + + protected String updateDb(Object... parameters) throws DatabaseUnavailableException { + var o = (Order) parameters[0]; + if (database.get(o.id) == null) { + database.add(o); + return o.id; // true rcvd - change addedToEmployeeHandle to true else don't do anything + } + return null; + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java new file mode 100644 index 000000000000..51f27832f481 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.exceptions; + +/** + * DatabaseUnavailableException is thrown when database is unavailable and nothing can be added or + * retrieved. + */ +public class DatabaseUnavailableException extends Exception { + private static final long serialVersionUID = 2459603L; +} diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/IsEmptyException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/IsEmptyException.java new file mode 100644 index 000000000000..5cb06214f527 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/IsEmptyException.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.exceptions; + +/** IsEmptyException is thrown when it is attempted to dequeue from an empty queue. */ +public class IsEmptyException extends Exception { + private static final long serialVersionUID = 123546L; +} diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/ItemUnavailableException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/ItemUnavailableException.java new file mode 100644 index 000000000000..9d6f2849ff77 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/ItemUnavailableException.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.exceptions; + +/** ItemUnavailableException is thrown when item is not available for shipping. */ +public class ItemUnavailableException extends Exception { + private static final long serialVersionUID = 575940L; +} diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java new file mode 100644 index 000000000000..1406b43de2b1 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.exceptions; + +/** + * PaymentDetailsErrorException is thrown when the details entered are incorrect or payment cannot + * be made with the details given. + */ +public class PaymentDetailsErrorException extends Exception { + private static final long serialVersionUID = 867203L; +} diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java new file mode 100644 index 000000000000..51036aaea3aa --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.exceptions; + +/** + * ShippingNotPossibleException is thrown when the address entered cannot be shipped to by service + * currently for some reason. + */ +public class ShippingNotPossibleException extends Exception { + private static final long serialVersionUID = 342055L; +} diff --git a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java new file mode 100644 index 000000000000..b6af7d7b52d2 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.messagingservice; + +import com.iluwatar.commander.Database; +import com.iluwatar.commander.messagingservice.MessagingService.MessageRequest; +import java.util.Hashtable; +import java.util.Map; + +/** The MessagingDatabase is where the MessageRequest is added. */ +public class MessagingDatabase extends Database { + private final Map data = new Hashtable<>(); + + @Override + public MessageRequest add(MessageRequest r) { + return data.put(r.reqId(), r); + } + + @Override + public MessageRequest get(String requestId) { + return data.get(requestId); + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java new file mode 100644 index 000000000000..44b58e5e07ba --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java @@ -0,0 +1,92 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.messagingservice; + +import com.iluwatar.commander.Service; +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import lombok.extern.slf4j.Slf4j; + +/** + * The MessagingService is used to send messages to user regarding their order and payment status. + * In case an error is encountered in payment and this service is found to be unavailable, the order + * is added to the {@link com.iluwatar.commander.employeehandle.EmployeeDatabase}. + */ +@Slf4j +public class MessagingService extends Service { + + enum MessageToSend { + PAYMENT_FAIL, + PAYMENT_TRYING, + PAYMENT_SUCCESSFUL + } + + record MessageRequest(String reqId, MessageToSend msg) {} + + public MessagingService(MessagingDatabase db, Exception... exc) { + super(db, exc); + } + + /** Public method which will receive request from {@link com.iluwatar.commander.Commander}. */ + public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { + var messageToSend = (int) parameters[0]; + var id = generateId(); + MessageToSend msg; + if (messageToSend == 0) { + msg = MessageToSend.PAYMENT_FAIL; + } else if (messageToSend == 1) { + msg = MessageToSend.PAYMENT_TRYING; + } else { // messageToSend == 2 + msg = MessageToSend.PAYMENT_SUCCESSFUL; + } + var req = new MessageRequest(id, msg); + return updateDb(req); + } + + protected String updateDb(Object... parameters) throws DatabaseUnavailableException { + var req = (MessageRequest) parameters[0]; + if (this.database.get(req.reqId) == null) { // idempotence, in case db fails here + database.add(req); // if successful: + LOGGER.info(sendMessage(req.msg)); + return req.reqId; + } + return null; + } + + String sendMessage(MessageToSend m) { + if (m.equals(MessageToSend.PAYMENT_SUCCESSFUL)) { + return "Msg: Your order has been placed and paid for successfully!" + + " Thank you for shopping with us!"; + } else if (m.equals(MessageToSend.PAYMENT_TRYING)) { + return "Msg: There was an error in your payment process," + + " we are working on it and will return back to you shortly." + + " Meanwhile, your order has been placed and will be shipped."; + } else { + return "Msg: There was an error in your payment process." + + " Your order is placed and has been converted to COD." + + " Please reach us on CUSTOMER-CARE-NUBER in case of any queries." + + " Thank you for shopping with us!"; + } + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java new file mode 100644 index 000000000000..354c1c958cae --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java @@ -0,0 +1,47 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.paymentservice; + +import com.iluwatar.commander.Database; +import com.iluwatar.commander.paymentservice.PaymentService.PaymentRequest; +import java.util.Hashtable; +import java.util.Map; + +/** PaymentDatabase is where the PaymentRequest is added, along with details. */ +public class PaymentDatabase extends Database { + + // 0-fail, 1-error, 2-success + private final Map data = new Hashtable<>(); + + @Override + public PaymentRequest add(PaymentRequest r) { + return data.put(r.transactionId, r); + } + + @Override + public PaymentRequest get(String requestId) { + return data.get(requestId); + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java new file mode 100644 index 000000000000..953c46165351 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java @@ -0,0 +1,65 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.paymentservice; + +import com.iluwatar.commander.Service; +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import lombok.RequiredArgsConstructor; + +/** + * The PaymentService class receives request from the {@link com.iluwatar.commander.Commander} and + * adds to the {@link PaymentDatabase}. + */ +public class PaymentService extends Service { + + @RequiredArgsConstructor + static class PaymentRequest { + final String transactionId; + final float payment; + boolean paid; + } + + public PaymentService(PaymentDatabase db, Exception... exc) { + super(db, exc); + } + + /** Public method which will receive request from {@link com.iluwatar.commander.Commander}. */ + public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { + // it could also be sending an userid, payment details here or something, not added here + var id = generateId(); + var req = new PaymentRequest(id, (float) parameters[0]); + return updateDb(req); + } + + protected String updateDb(Object... parameters) throws DatabaseUnavailableException { + var req = (PaymentRequest) parameters[0]; + if (database.get(req.transactionId) == null || !req.paid) { + database.add(req); + req.paid = true; + return req.transactionId; + } + return null; + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/queue/Queue.java b/commander/src/main/java/com/iluwatar/commander/queue/Queue.java new file mode 100644 index 000000000000..d66accb7dd85 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/queue/Queue.java @@ -0,0 +1,84 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.queue; + +import com.iluwatar.commander.exceptions.IsEmptyException; + +/** + * Queue data structure implementation. + * + * @param is the type of object the queue will hold. + */ +public class Queue { + + private Node front; + private Node rear; + private int size; + + static class Node { + V value; + Node next; + + Node(V obj, Node b) { + value = obj; + next = b; + } + } + + boolean isEmpty() { + return size == 0; + } + + void enqueue(T obj) { + if (front == null) { + front = new Node<>(obj, null); + rear = front; + } else { + var temp = new Node<>(obj, null); + rear.next = temp; + rear = temp; + } + size++; + } + + T dequeue() throws IsEmptyException { + if (isEmpty()) { + throw new IsEmptyException(); + } else { + var temp = front; + front = front.next; + size = size - 1; + return temp.value; + } + } + + T peek() throws IsEmptyException { + if (isEmpty()) { + throw new IsEmptyException(); + } else { + return front.value; + } + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java new file mode 100644 index 000000000000..41b54a276c5c --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java @@ -0,0 +1,74 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.queue; + +import com.iluwatar.commander.Database; +import com.iluwatar.commander.exceptions.IsEmptyException; +import java.util.ArrayList; +import java.util.List; + +/** QueueDatabase id where the instructions to be implemented are queued. */ +public class QueueDatabase extends Database { + + private final Queue data; + public List exceptionsList; + + public QueueDatabase(Exception... exc) { + this.data = new Queue<>(); + this.exceptionsList = new ArrayList<>(List.of(exc)); + } + + @Override + public QueueTask add(QueueTask t) { + data.enqueue(t); + return t; + // even if same thing queued twice, it is taken care of in other dbs + } + + /** + * peek method returns object at front without removing it from queue. + * + * @return object at front of queue + * @throws IsEmptyException if queue is empty + */ + public QueueTask peek() throws IsEmptyException { + return this.data.peek(); + } + + /** + * dequeue method removes the object at front and returns it. + * + * @return object at front of queue + * @throws IsEmptyException if queue is empty + */ + public QueueTask dequeue() throws IsEmptyException { + return this.data.dequeue(); + } + + @Override + public QueueTask get(String taskId) { + return null; + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java b/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java new file mode 100644 index 000000000000..aedf55a9e1a3 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java @@ -0,0 +1,73 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.queue; + +import com.iluwatar.commander.Order; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; + +/** QueueTask object is the object enqueued in queue. */ +@RequiredArgsConstructor +public class QueueTask { + + /** TaskType is the type of task to be done. */ + public enum TaskType { + MESSAGING, + PAYMENT, + EMPLOYEE_DB + } + + public final Order order; + public final TaskType taskType; + public final int messageType; // 0-fail, 1-error, 2-success + + /*we could have varargs Object instead to pass in any parameter instead of just message type + but keeping it simple here*/ + @Getter @Setter private long firstAttemptTime = -1L; // when first time attempt made to do task + + /** + * getType method. + * + * @return String representing type of task + */ + public String getType() { + if (!this.taskType.equals(TaskType.MESSAGING)) { + return this.taskType.toString(); + } else { + if (this.messageType == 0) { + return "Payment Failure Message"; + } else if (this.messageType == 1) { + return "Payment Error Message"; + } else { + return "Payment Success Message"; + } + } + } + + public boolean isFirstAttempt() { + return this.firstAttemptTime == -1L; + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java new file mode 100644 index 000000000000..3906834279b8 --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.shippingservice; + +import com.iluwatar.commander.Database; +import com.iluwatar.commander.shippingservice.ShippingService.ShippingRequest; +import java.util.Hashtable; +import java.util.Map; + +/** ShippingDatabase is where the ShippingRequest objects are added. */ +public class ShippingDatabase extends Database { + + private final Map data = new Hashtable<>(); + + @Override + public ShippingRequest add(ShippingRequest r) { + return data.put(r.transactionId, r); + } + + public ShippingRequest get(String trasnactionId) { + return data.get(trasnactionId); + } +} diff --git a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java new file mode 100644 index 000000000000..cc97159b763f --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java @@ -0,0 +1,65 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander.shippingservice; + +import com.iluwatar.commander.Service; +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import lombok.AllArgsConstructor; + +/** + * ShippingService class receives request from {@link com.iluwatar.commander.Commander} class and + * adds it to the {@link ShippingDatabase}. + */ +public class ShippingService extends Service { + + @AllArgsConstructor + static class ShippingRequest { + String transactionId; + String item; + String address; + } + + public ShippingService(ShippingDatabase db, Exception... exc) { + super(db, exc); + } + + /** Public method which will receive request from {@link com.iluwatar.commander.Commander}. */ + public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { + var id = generateId(); + var item = (String) parameters[0]; + var address = (String) parameters[1]; + var req = new ShippingRequest(id, item, address); + return updateDb(req); + } + + protected String updateDb(Object... parameters) throws DatabaseUnavailableException { + var req = (ShippingRequest) parameters[0]; + if (this.database.get(req.transactionId) == null) { + database.add(req); + return req.transactionId; + } + return null; + } +} diff --git a/commander/src/test/java/com/iluwatar/commander/CommanderTest.java b/commander/src/test/java/com/iluwatar/commander/CommanderTest.java new file mode 100644 index 000000000000..664268965bf7 --- /dev/null +++ b/commander/src/test/java/com/iluwatar/commander/CommanderTest.java @@ -0,0 +1,683 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +import com.iluwatar.commander.employeehandle.EmployeeDatabase; +import com.iluwatar.commander.employeehandle.EmployeeHandle; +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import com.iluwatar.commander.exceptions.ItemUnavailableException; +import com.iluwatar.commander.exceptions.PaymentDetailsErrorException; +import com.iluwatar.commander.exceptions.ShippingNotPossibleException; +import com.iluwatar.commander.messagingservice.MessagingDatabase; +import com.iluwatar.commander.messagingservice.MessagingService; +import com.iluwatar.commander.paymentservice.PaymentDatabase; +import com.iluwatar.commander.paymentservice.PaymentService; +import com.iluwatar.commander.queue.QueueDatabase; +import com.iluwatar.commander.shippingservice.ShippingDatabase; +import com.iluwatar.commander.shippingservice.ShippingService; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.platform.commons.util.StringUtils; + +class CommanderTest { + + private final RetryParams retryParams = new RetryParams(1, 1_000L); + + private final TimeLimits timeLimits = new TimeLimits(1L, 1000L, 6000L, 5000L, 2000L); + + private static final List exceptionList = new ArrayList<>(); + + private static final AppAllCases appAllCases = new AppAllCases(); + + static { + exceptionList.add(new DatabaseUnavailableException()); + exceptionList.add(new ShippingNotPossibleException()); + exceptionList.add(new ItemUnavailableException()); + exceptionList.add(new PaymentDetailsErrorException()); + exceptionList.add(new IllegalStateException()); + } + + private Commander buildCommanderObject() { + return buildCommanderObject(false); + } + + private Commander buildCommanderObject(boolean nonPaymentException) { + PaymentService paymentService = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + + ShippingService shippingService; + MessagingService messagingService; + if (nonPaymentException) { + shippingService = + new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException()); + messagingService = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + + } else { + shippingService = + new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException()); + messagingService = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + } + var employeeHandle = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectVanilla() { + PaymentService paymentService = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase()); + var employeeHandle = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectUnknownException() { + PaymentService paymentService = + new PaymentService(new PaymentDatabase(), new IllegalStateException()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase()); + var employeeHandle = new EmployeeHandle(new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase(new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectNoPaymentException1() { + PaymentService paymentService = new PaymentService(new PaymentDatabase()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase()); + var employeeHandle = new EmployeeHandle(new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase(new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectNoPaymentException2() { + PaymentService paymentService = new PaymentService(new PaymentDatabase()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = + new MessagingService(new MessagingDatabase(), new IllegalStateException()); + var employeeHandle = new EmployeeHandle(new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase(new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectNoPaymentException3() { + PaymentService paymentService = new PaymentService(new PaymentDatabase()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + var employeeHandle = new EmployeeHandle(new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase(new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectWithDB() { + return buildCommanderObjectWithoutDB(false, false, new IllegalStateException()); + } + + private Commander buildCommanderObjectWithDB( + boolean includeException, boolean includeDBException, Exception e) { + var l = includeDBException ? new DatabaseUnavailableException() : e; + PaymentService paymentService; + ShippingService shippingService; + MessagingService messagingService; + EmployeeHandle employeeHandle; + if (includeException) { + paymentService = new PaymentService(new PaymentDatabase(), l); + shippingService = new ShippingService(new ShippingDatabase(), l); + messagingService = new MessagingService(new MessagingDatabase(), l); + employeeHandle = new EmployeeHandle(new EmployeeDatabase(), l); + } else { + paymentService = new PaymentService(null); + shippingService = new ShippingService(null); + messagingService = new MessagingService(null); + employeeHandle = new EmployeeHandle(null); + } + + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + null, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectWithoutDB() { + return buildCommanderObjectWithoutDB(false, false, new IllegalStateException()); + } + + private Commander buildCommanderObjectWithoutDB( + boolean includeException, boolean includeDBException, Exception e) { + var l = includeDBException ? new DatabaseUnavailableException() : e; + PaymentService paymentService; + ShippingService shippingService; + MessagingService messagingService; + EmployeeHandle employeeHandle; + if (includeException) { + paymentService = new PaymentService(null, l); + shippingService = new ShippingService(null, l); + messagingService = new MessagingService(null, l); + employeeHandle = new EmployeeHandle(null, l); + } else { + paymentService = new PaymentService(null); + shippingService = new ShippingService(null); + messagingService = new MessagingService(null); + employeeHandle = new EmployeeHandle(null); + } + + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + null, + retryParams, + timeLimits); + } + + @Test + void testPlaceOrderVanilla() { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectVanilla(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrder() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObject(true); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrder2() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObject(false); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoException1() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException1(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoException2() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException2(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoException3() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException3(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoException4() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException3(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + c.placeOrder(order); + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderUnknownException() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectUnknownException(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderShortDuration() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObject(true); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderShortDuration2() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObject(false); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoExceptionShortMsgDuration() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectNoPaymentException1(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoExceptionShortQueueDuration() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectUnknownException(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderWithDatabase() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectWithDB(); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderWithDatabaseAndExceptions() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + + for (Exception e : exceptionList) { + + Commander c = buildCommanderObjectWithDB(true, true, e); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithDB(true, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithDB(false, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithDB(false, true, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + } + + @Test + void testPlaceOrderWithoutDatabase() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectWithoutDB(); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderWithoutDatabaseAndExceptions() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + + for (Exception e : exceptionList) { + + Commander c = buildCommanderObjectWithoutDB(true, true, e); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithoutDB(true, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithoutDB(false, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithoutDB(false, true, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + } + + @Test + void testAllSuccessCases() throws Exception { + appAllCases.employeeDbSuccessCase(); + appAllCases.messagingSuccessCase(); + appAllCases.paymentSuccessCase(); + appAllCases.queueSuccessCase(); + appAllCases.shippingSuccessCase(); + } + + @Test + void testAllUnavailableCase() throws Exception { + appAllCases.employeeDatabaseUnavailableCase(); + appAllCases.messagingDatabaseUnavailableCasePaymentSuccess(); + appAllCases.messagingDatabaseUnavailableCasePaymentError(); + appAllCases.messagingDatabaseUnavailableCasePaymentFailure(); + appAllCases.paymentDatabaseUnavailableCase(); + appAllCases.queuePaymentTaskDatabaseUnavailableCase(); + appAllCases.queueMessageTaskDatabaseUnavailableCase(); + appAllCases.queueEmployeeDbTaskDatabaseUnavailableCase(); + appAllCases.itemUnavailableCase(); + appAllCases.shippingDatabaseUnavailableCase(); + } + + @Test + void testAllNotPossibleCase() throws Exception { + appAllCases.paymentNotPossibleCase(); + appAllCases.shippingItemNotPossibleCase(); + } +} diff --git a/commander/src/test/java/com/iluwatar/commander/RetryTest.java b/commander/src/test/java/com/iluwatar/commander/RetryTest.java new file mode 100644 index 000000000000..389a45c2a52f --- /dev/null +++ b/commander/src/test/java/com/iluwatar/commander/RetryTest.java @@ -0,0 +1,86 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.commander; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import com.iluwatar.commander.exceptions.ItemUnavailableException; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class RetryTest { + + private static final Logger LOG = LoggerFactory.getLogger(RetryTest.class); + + @Test + void performTest() { + Retry.Operation op = + (l) -> { + if (!l.isEmpty()) { + throw l.remove(0); + } + }; + Retry.HandleErrorIssue handleError = (o, e) -> {}; + var r1 = + new Retry<>( + op, + handleError, + 3, + 30000, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + var r2 = + new Retry<>( + op, + handleError, + 3, + 30000, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + var user = new User("Jim", "ABCD"); + var order = new Order(user, "book", 10f); + var arr1 = + new ArrayList<>( + List.of(new ItemUnavailableException(), new DatabaseUnavailableException())); + try { + r1.perform(arr1, order); + } catch (Exception e1) { + LOG.error("An exception occurred", e1); + } + var arr2 = + new ArrayList<>( + List.of(new DatabaseUnavailableException(), new ItemUnavailableException())); + try { + r2.perform(arr2, order); + } catch (Exception e1) { + LOG.error("An exception occurred", e1); + } + // r1 stops at ItemUnavailableException, r2 retries because it encounters + // DatabaseUnavailableException + assertTrue(arr1.size() == 1 && arr2.isEmpty()); + } +} diff --git a/component/README.md b/component/README.md new file mode 100644 index 000000000000..6ab6284e280e --- /dev/null +++ b/component/README.md @@ -0,0 +1,165 @@ +--- +title: "Component Pattern in Java: Simplifying Complex Systems with Reusable Components" +shortTitle: Component +description: "Learn about the Component Design Pattern in Java, including ECS architecture, modularity, and decoupling. Explore examples, class diagrams, and real-world applications in game development for flexible and maintainable code." +categories: Structural +language: en +tag: + - Game programming + - Decoupling + - Modularity +--- + +## Also known as + +* Entity-Component-System (ECS) +* Component-Entity-System (CES) +* Component-Based Architecture (CBA) + +## Intent of Component Design Pattern + +The Component design pattern organizes code into reusable, interchangeable components, promoting flexibility, modularity, and ease of maintenance. This pattern is especially useful in game development, enabling entities to be configured with diverse behaviors dynamically. + +## Detailed Explanation of Component Pattern with Real-World Examples + +Real-world example + +> Consider a video game with a graphics component and a sound component. Including both in a single Java class can create maintenance challenges due to lengthy code and potential conflicts from different teams working on the same class. The Component design pattern resolves this by creating individual component classes for graphics and sound, allowing flexible and independent development. This modular approach enhances maintainability and scalability. + +In plain words + +> The component design pattern provides a single attribute to be accessible by numerous objects without requiring the existence of a relationship between the objects themselves. + +Architecture diagram + +![Component architecture diagram](./etc/component-architecture-diagram.png) + +## Programmatic Example of Component Pattern in Java + +The `App` class creates a demonstration of the use of the component pattern by creating two different objects which inherit a small collection of individual components that are modifiable. + +```java +public final class App { + + public static void main(String[] args) { + final var player = GameObject.createPlayer(); + final var npc = GameObject.createNpc(); + + LOGGER.info("Player Update:"); + player.update(KeyEvent.KEY_LOCATION_LEFT); + LOGGER.info("NPC Update:"); + npc.demoUpdate(); + } +} +``` + +Much of the program exists within the `GameObject` class, within this class, the player and NPC object create methods are set up. Additionally, this class also consists of the method calls used to update/alter information of the object's components. + +```java +public class GameObject { + private final InputComponent inputComponent; + private final PhysicComponent physicComponent; + private final GraphicComponent graphicComponent; + + public String name; + public int velocity = 0; + public int coordinate = 0; + + public static GameObject createPlayer() { + return new GameObject(new PlayerInputComponent(), + new ObjectPhysicComponent(), + new ObjectGraphicComponent(), + "player"); + } + + public static GameObject createNpc() { + return new GameObject( + new DemoInputComponent(), + new ObjectPhysicComponent(), + new ObjectGraphicComponent(), + "npc"); + } + + public void demoUpdate() { + inputComponent.update(this); + physicComponent.update(this); + graphicComponent.update(this); + } + + public void update(int e) { + inputComponent.update(this, e); + physicComponent.update(this); + graphicComponent.update(this); + } + + public void updateVelocity(int acceleration) { + this.velocity += acceleration; + } + + public void updateCoordinate() { + this.coordinate += this.velocity; + } +} +``` + +Upon opening the component package, the collection of components are revealed. These components provide the interface for objects to inherit these domains. The `PlayerInputComponent` class shown below updates the object's velocity characteristic based on user's key event input. + +```java +public class PlayerInputComponent implements InputComponent { + private static final int walkAcceleration = 1; + + @Override + public void update(GameObject gameObject, int e) { + switch (e) { + case KeyEvent.KEY_LOCATION_LEFT -> { + gameObject.updateVelocity(-WALK_ACCELERATION); + LOGGER.info(gameObject.getName() + " has moved left."); + } + case KeyEvent.KEY_LOCATION_RIGHT -> { + gameObject.updateVelocity(WALK_ACCELERATION); + LOGGER.info(gameObject.getName() + " has moved right."); + } + default -> { + LOGGER.info(gameObject.getName() + "'s velocity is unchanged due to the invalid input"); + gameObject.updateVelocity(0); + } // incorrect input + } + } +} +``` + +## When to Use the Component Pattern in Java + +* Used in game development and simulations where game entities (e.g., characters, items) can have a dynamic set of abilities or states. +* Suitable for systems requiring high modularity and systems where entities might need to change behavior at runtime without inheritance hierarchies. + +## Real-World Applications of Component Pattern in Java + +The Component pattern is ideal for game development and simulations where entities like characters and items have dynamic abilities or states. It suits systems requiring high modularity and scenarios where entities need to change behavior at runtime without relying on inheritance hierarchies, enhancing flexibility and maintainability. + +## Benefits and Trade-offs of Component Pattern + +Benefits: + +* Flexibility and Reusability: Components can be reused across different entities, making it easier to add new features or modify existing ones. +* Decoupling: Reduces dependencies between game entity states and behaviors, facilitating easier changes and maintenance. +* Dynamic Composition: Entities can alter their behavior at runtime by adding or removing components, providing significant flexibility in game design. + +Trade-offs: + +* Complexity: Can introduce additional complexity in system architecture, particularly in managing dependencies and communications between components. +* Performance Considerations: Depending on implementation, may incur a performance overhead due to indirection and dynamic behavior, especially critical in high-performance game loops. + +## Related Java Design Patterns + +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar concept of adding responsibilities dynamically, but without the focus on game entities. +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used in conjunction with the Component pattern to share component instances among many entities to save memory. +* [Observer](https://java-design-patterns.com/patterns/observer/): Often used in Component systems to communicate state changes between components. + +## References and Credits + +* [Game Programming Patterns](https://amzn.to/4cDRWhV) +* [Procedural Content Generation for Unity Game Development](https://amzn.to/3vBKCTp) +* [Unity in Action: Multiplatform Game Development in C#](https://amzn.to/3THO6vw) +* [Component (Game Programming Patterns)](https://gameprogrammingpatterns.com/component.html) +* [Component pattern - game programming series (Tutemic)](https://www.youtube.com/watch?v=n92GBp2WMkg&ab_channel=Tutemic) diff --git a/component/etc/component-architecture-diagram.png b/component/etc/component-architecture-diagram.png new file mode 100644 index 000000000000..8256d5719c18 Binary files /dev/null and b/component/etc/component-architecture-diagram.png differ diff --git a/component/etc/component.uml.png b/component/etc/component.uml.png new file mode 100644 index 000000000000..44b789453202 Binary files /dev/null and b/component/etc/component.uml.png differ diff --git a/component/etc/component.uml.puml b/component/etc/component.uml.puml new file mode 100644 index 000000000000..1c386fa30f75 --- /dev/null +++ b/component/etc/component.uml.puml @@ -0,0 +1,77 @@ +@startuml +class App +class GameObject + +interface GraphicComponent +interface InputComponent +interface PhysicComponent + +class ObjectGraphicComponent +class DemoInputComponent +class PlayerInputComponent +class ObjectPhysicComponent + +GraphicComponent <|.. ObjectGraphicComponent +InputComponent <|.. DemoInputComponent +InputComponent <|.. PlayerInputComponent +PhysicComponent <|.. ObjectPhysicComponent + +GameObject *-- ObjectGraphicComponent +GameObject *.. DemoInputComponent +GameObject *.. PlayerInputComponent +GameObject *-- ObjectPhysicComponent +class App { ++main(String[] args) +} + +class GameObject{ + - inputComponent; + - physicComponent; + - graphicComponent; + - name; + - velocity + - coordinate + + +GameObject() + +createPlayer() + +createNpc() + +demoUpdate() + +update(e:int) + +getName() + +getVelocity() + +setVelocity(acceleration:int) + +getCoordinate() + +setCoordinate() +} + +interface GraphicComponent{ + +update() +} + +interface InputComponent{ + +update() +} + +interface PhysicComponent{ + +update() +} + +class ObjectGraphicComponent{ + +update(gameObject:GameObject) +} + +class DemoInputComponent{ + -walkAcceleration + +update(gameObject:GameObject,e:int) +} + +class PlayerInputComponent{ + -walkAcceleration + +update(gameObject:GameObject,e:int) +} + +class ObjectPhysicComponent{ + +update(gameObject:GameObject) +} + +@enduml \ No newline at end of file diff --git a/component/etc/component.urm.puml b/component/etc/component.urm.puml new file mode 100644 index 000000000000..612eff22af0a --- /dev/null +++ b/component/etc/component.urm.puml @@ -0,0 +1,74 @@ +@startuml +package com.iluwatar.component.component.physiccomponent { + class ObjectPhysicComponent { + - LOGGER : Logger {static} + + ObjectPhysicComponent() + + update(gameObject : GameObject) + } + interface PhysicComponent { + + update(GameObject) {abstract} + } +} +package com.iluwatar.component.component.inputcomponent { + class DemoInputComponent { + - LOGGER : Logger {static} + - WALK_ACCELERATION : int {static} + + DemoInputComponent() + + update(gameObject : GameObject, e : int) + } + interface InputComponent { + + update(GameObject, int) {abstract} + } + class PlayerInputComponent { + - LOGGER : Logger {static} + - WALK_ACCELERATION : int {static} + + PlayerInputComponent() + + update(gameObject : GameObject, e : int) + } +} +package com.iluwatar.component.component.graphiccomponent { + interface GraphicComponent { + + update(GameObject) {abstract} + } + class ObjectGraphicComponent { + - LOGGER : Logger {static} + + ObjectGraphicComponent() + + update(gameObject : GameObject) + } +} +package com.iluwatar.component { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class GameObject { + - coordinate : int + - graphicComponent : GraphicComponent + - inputComponent : InputComponent + - name : String + - physicComponent : PhysicComponent + - velocity : int + + GameObject(inputComponent : InputComponent, physicComponent : PhysicComponent, graphicComponent : GraphicComponent, name : String) + + createNpc() : GameObject {static} + + createPlayer() : GameObject {static} + + demoUpdate() + + getCoordinate() : int + + getGraphicComponent() : GraphicComponent + + getInputComponent() : InputComponent + + getName() : String + + getPhysicComponent() : PhysicComponent + + getVelocity() : int + + update(e : int) + + updateCoordinate() + + updateVelocity(acceleration : int) + } +} +GameObject --> "-inputComponent" InputComponent +GameObject --> "-graphicComponent" GraphicComponent +GameObject --> "-physicComponent" PhysicComponent +ObjectGraphicComponent ..|> GraphicComponent +DemoInputComponent ..|> InputComponent +PlayerInputComponent ..|> InputComponent +ObjectPhysicComponent ..|> PhysicComponent +@enduml \ No newline at end of file diff --git a/component/pom.xml b/component/pom.xml new file mode 100644 index 000000000000..e666e283489b --- /dev/null +++ b/component/pom.xml @@ -0,0 +1,73 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + + component + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.component.App + + + + + + + + + \ No newline at end of file diff --git a/component/src/main/java/com/iluwatar/component/App.java b/component/src/main/java/com/iluwatar/component/App.java new file mode 100644 index 000000000000..9401483e92e2 --- /dev/null +++ b/component/src/main/java/com/iluwatar/component/App.java @@ -0,0 +1,60 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component; + +import java.awt.event.KeyEvent; +import lombok.extern.slf4j.Slf4j; + +/** + * The component design pattern is a common game design structure. This pattern is often used to + * reduce duplication of code as well as to improve maintainability. In this implementation, + * component design pattern has been used to provide two game objects with varying component + * interfaces (features). As opposed to copying and pasting same code for the two game objects, the + * component interfaces allow game objects to inherit these components from the component classes. + * + *

    The implementation has decoupled graphic, physics and input components from the player and NPC + * objects. As a result, it avoids the creation of monolithic java classes. + * + *

    The below example in this App class demonstrates the use of the component interfaces for + * separate objects (player & NPC) and updating of these components as per the implementations in + * GameObject class and the component classes. + */ +@Slf4j +public final class App { + /** + * Program entry point. + * + * @param args args command line args. + */ + public static void main(String[] args) { + final var player = GameObject.createPlayer(); + final var npc = GameObject.createNpc(); + + LOGGER.info("Player Update:"); + player.update(KeyEvent.KEY_LOCATION_LEFT); + LOGGER.info("NPC Update:"); + npc.demoUpdate(); + } +} diff --git a/component/src/main/java/com/iluwatar/component/GameObject.java b/component/src/main/java/com/iluwatar/component/GameObject.java new file mode 100644 index 000000000000..87c35b24e8c4 --- /dev/null +++ b/component/src/main/java/com/iluwatar/component/GameObject.java @@ -0,0 +1,111 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component; + +import com.iluwatar.component.component.graphiccomponent.GraphicComponent; +import com.iluwatar.component.component.graphiccomponent.ObjectGraphicComponent; +import com.iluwatar.component.component.inputcomponent.DemoInputComponent; +import com.iluwatar.component.component.inputcomponent.InputComponent; +import com.iluwatar.component.component.inputcomponent.PlayerInputComponent; +import com.iluwatar.component.component.physiccomponent.ObjectPhysicComponent; +import com.iluwatar.component.component.physiccomponent.PhysicComponent; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +/** + * The GameObject class has three component class instances that allow the creation of different + * game objects based on the game design requirements. + */ +@Getter +@RequiredArgsConstructor +public class GameObject { + private final InputComponent inputComponent; + private final PhysicComponent physicComponent; + private final GraphicComponent graphicComponent; + + private final String name; + private int velocity = 0; + private int coordinate = 0; + + /** + * Creates a player game object. + * + * @return player object + */ + public static GameObject createPlayer() { + return new GameObject( + new PlayerInputComponent(), + new ObjectPhysicComponent(), + new ObjectGraphicComponent(), + "player"); + } + + /** + * Creates a NPC game object. + * + * @return npc object + */ + public static GameObject createNpc() { + return new GameObject( + new DemoInputComponent(), new ObjectPhysicComponent(), new ObjectGraphicComponent(), "npc"); + } + + /** + * Updates the three components of the NPC object used in the demo in App.java note that this is + * simply a duplicate of update() without the key event for demonstration purposes. + * + *

    This method is usually used in games if the player becomes inactive. + */ + public void demoUpdate() { + inputComponent.update(this, 0); + physicComponent.update(this); + graphicComponent.update(this); + } + + /** + * Updates the three components for objects based on key events. + * + * @param e key event from the player. + */ + public void update(int e) { + inputComponent.update(this, e); + physicComponent.update(this); + graphicComponent.update(this); + } + + /** + * Update the velocity based on the acceleration of the GameObject. + * + * @param acceleration the acceleration of the GameObject + */ + public void updateVelocity(int acceleration) { + this.velocity += acceleration; + } + + /** Set the c based on the current velocity. */ + public void updateCoordinate() { + this.coordinate += this.velocity; + } +} diff --git a/component/src/main/java/com/iluwatar/component/component/graphiccomponent/GraphicComponent.java b/component/src/main/java/com/iluwatar/component/component/graphiccomponent/GraphicComponent.java new file mode 100644 index 000000000000..600ee8e5275d --- /dev/null +++ b/component/src/main/java/com/iluwatar/component/component/graphiccomponent/GraphicComponent.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component.component.graphiccomponent; + +import com.iluwatar.component.GameObject; + +/** Generic GraphicComponent interface. */ +public interface GraphicComponent { + void update(GameObject gameObject); +} diff --git a/component/src/main/java/com/iluwatar/component/component/graphiccomponent/ObjectGraphicComponent.java b/component/src/main/java/com/iluwatar/component/component/graphiccomponent/ObjectGraphicComponent.java new file mode 100644 index 000000000000..7f595763f10c --- /dev/null +++ b/component/src/main/java/com/iluwatar/component/component/graphiccomponent/ObjectGraphicComponent.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component.component.graphiccomponent; + +import com.iluwatar.component.GameObject; +import lombok.extern.slf4j.Slf4j; + +/** ObjectGraphicComponent class mimics the graphic component of the Game Object. */ +@Slf4j +public class ObjectGraphicComponent implements GraphicComponent { + + /** + * The method updates the graphics based on the velocity of gameObject. + * + * @param gameObject the gameObject instance + */ + @Override + public void update(GameObject gameObject) { + LOGGER.info(gameObject.getName() + "'s current velocity: " + gameObject.getVelocity()); + } +} diff --git a/component/src/main/java/com/iluwatar/component/component/inputcomponent/DemoInputComponent.java b/component/src/main/java/com/iluwatar/component/component/inputcomponent/DemoInputComponent.java new file mode 100644 index 000000000000..b7ff51c3f2e7 --- /dev/null +++ b/component/src/main/java/com/iluwatar/component/component/inputcomponent/DemoInputComponent.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component.component.inputcomponent; + +import com.iluwatar.component.GameObject; +import lombok.extern.slf4j.Slf4j; + +/** + * Take this component class to control player or the NPC for demo mode. and implemented the + * InputComponent interface. + * + *

    Essentially, the demo mode is utilised during a game if the user become inactive. Please see: + * http://gameprogrammingpatterns.com/component.html + */ +@Slf4j +public class DemoInputComponent implements InputComponent { + private static final int WALK_ACCELERATION = 2; + + /** + * Redundant method in the demo mode. + * + * @param gameObject the gameObject instance + * @param e key event instance + */ + @Override + public void update(GameObject gameObject, int e) { + gameObject.updateVelocity(WALK_ACCELERATION); + LOGGER.info(gameObject.getName() + " has moved right."); + } +} diff --git a/component/src/main/java/com/iluwatar/component/component/inputcomponent/InputComponent.java b/component/src/main/java/com/iluwatar/component/component/inputcomponent/InputComponent.java new file mode 100644 index 000000000000..65bab37fc59d --- /dev/null +++ b/component/src/main/java/com/iluwatar/component/component/inputcomponent/InputComponent.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component.component.inputcomponent; + +import com.iluwatar.component.GameObject; + +/** Generic InputComponent interface. */ +public interface InputComponent { + void update(GameObject gameObject, int e); +} diff --git a/component/src/main/java/com/iluwatar/component/component/inputcomponent/PlayerInputComponent.java b/component/src/main/java/com/iluwatar/component/component/inputcomponent/PlayerInputComponent.java new file mode 100644 index 000000000000..d38682de49f9 --- /dev/null +++ b/component/src/main/java/com/iluwatar/component/component/inputcomponent/PlayerInputComponent.java @@ -0,0 +1,62 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component.component.inputcomponent; + +import com.iluwatar.component.GameObject; +import java.awt.event.KeyEvent; +import lombok.extern.slf4j.Slf4j; + +/** + * PlayerInputComponent is used to handle user key event inputs, and thus it implements the + * InputComponent interface. + */ +@Slf4j +public class PlayerInputComponent implements InputComponent { + private static final int WALK_ACCELERATION = 1; + + /** + * The update method to change the velocity based on the input key event. + * + * @param gameObject the gameObject instance + * @param e key event instance + */ + @Override + public void update(GameObject gameObject, int e) { + switch (e) { + case KeyEvent.KEY_LOCATION_LEFT -> { + gameObject.updateVelocity(-WALK_ACCELERATION); + LOGGER.info(gameObject.getName() + " has moved left."); + } + case KeyEvent.KEY_LOCATION_RIGHT -> { + gameObject.updateVelocity(WALK_ACCELERATION); + LOGGER.info(gameObject.getName() + " has moved right."); + } + default -> { + LOGGER.info(gameObject.getName() + "'s velocity is unchanged due to the invalid input"); + gameObject.updateVelocity(0); + } // incorrect input + } + } +} diff --git a/component/src/main/java/com/iluwatar/component/component/physiccomponent/ObjectPhysicComponent.java b/component/src/main/java/com/iluwatar/component/component/physiccomponent/ObjectPhysicComponent.java new file mode 100644 index 000000000000..a7c189efc463 --- /dev/null +++ b/component/src/main/java/com/iluwatar/component/component/physiccomponent/ObjectPhysicComponent.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component.component.physiccomponent; + +import com.iluwatar.component.GameObject; +import lombok.extern.slf4j.Slf4j; + +/** Take this component class to update the x coordinate for the Game Object instance. */ +@Slf4j +public class ObjectPhysicComponent implements PhysicComponent { + + /** + * The method update the horizontal (X-axis) coordinate based on the velocity of gameObject. + * + * @param gameObject the gameObject instance + */ + @Override + public void update(GameObject gameObject) { + gameObject.updateCoordinate(); + LOGGER.info(gameObject.getName() + "'s coordinate has been changed."); + } +} diff --git a/component/src/main/java/com/iluwatar/component/component/physiccomponent/PhysicComponent.java b/component/src/main/java/com/iluwatar/component/component/physiccomponent/PhysicComponent.java new file mode 100644 index 000000000000..67c33026024d --- /dev/null +++ b/component/src/main/java/com/iluwatar/component/component/physiccomponent/PhysicComponent.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component.component.physiccomponent; + +import com.iluwatar.component.GameObject; + +/** Generic PhysicComponent interface. */ +public interface PhysicComponent { + void update(GameObject gameObject); +} diff --git a/component/src/test/java/com/iluwatar/component/AppTest.java b/component/src/test/java/com/iluwatar/component/AppTest.java new file mode 100644 index 000000000000..7de0745e7685 --- /dev/null +++ b/component/src/test/java/com/iluwatar/component/AppTest.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** + * Tests App class : src/main/java/com/iluwatar/component/App.java General execution test of the + * application. + */ +class AppTest { + + @Test + void shouldExecuteComponentWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/component/src/test/java/com/iluwatar/component/GameObjectTest.java b/component/src/test/java/com/iluwatar/component/GameObjectTest.java new file mode 100644 index 000000000000..09b3b3995268 --- /dev/null +++ b/component/src/test/java/com/iluwatar/component/GameObjectTest.java @@ -0,0 +1,87 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.component; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.awt.event.KeyEvent; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Tests GameObject class. src/main/java/com/iluwatar/component/GameObject.java */ +@Slf4j +class GameObjectTest { + GameObject playerTest; + GameObject npcTest; + + @BeforeEach + public void initEach() { + // creates player & npc objects for testing + // note that velocity and coordinates are initialised to 0 in GameObject.java + playerTest = GameObject.createPlayer(); + npcTest = GameObject.createNpc(); + } + + /** Tests the create methods - createPlayer() and createNPC(). */ + @Test + void objectTest() { + LOGGER.info("objectTest:"); + assertEquals("player", playerTest.getName()); + assertEquals("npc", npcTest.getName()); + } + + /** Tests the input component with varying key event inputs. Targets the player game object. */ + @Test + void eventInputTest() { + LOGGER.info("eventInputTest:"); + playerTest.update(KeyEvent.KEY_LOCATION_LEFT); + assertEquals(-1, playerTest.getVelocity()); + assertEquals(-1, playerTest.getCoordinate()); + + playerTest.update(KeyEvent.KEY_LOCATION_RIGHT); + playerTest.update(KeyEvent.KEY_LOCATION_RIGHT); + assertEquals(1, playerTest.getVelocity()); + assertEquals(0, playerTest.getCoordinate()); + + LOGGER.info(Integer.toString(playerTest.getCoordinate())); + LOGGER.info(Integer.toString(playerTest.getVelocity())); + + GameObject p2 = GameObject.createPlayer(); + p2.update(KeyEvent.KEY_LOCATION_LEFT); + // in the case of an unknown, object stats are set to default + p2.update(KeyEvent.KEY_LOCATION_UNKNOWN); + assertEquals(-1, p2.getVelocity()); + } + + /** Tests the demo component interface. */ + @Test + void npcDemoTest() { + LOGGER.info("npcDemoTest:"); + npcTest.demoUpdate(); + assertEquals(2, npcTest.getVelocity()); + assertEquals(2, npcTest.getCoordinate()); + } +} diff --git a/composite-entity/README.md b/composite-entity/README.md new file mode 100644 index 000000000000..5946663a85ae --- /dev/null +++ b/composite-entity/README.md @@ -0,0 +1,170 @@ +--- +title: "Composite Entity Pattern in Java: Streamlining Persistent Object Management" +shortTitle: Composite Entity +description: "Learn about the Composite Entity design pattern in Java, a structural pattern used to manage interrelated persistent objects as a single entity. Ideal for enterprise applications and EJB, this pattern simplifies complex data structures and client interactions." +category: Structural +language: en +tag: + - Client-server + - Data access + - Decoupling + - Enterprise patterns + - Object composition + - Persistence + - Resource management +--- + +## Also known as + +* Coarse-Grained Entity + +## Intent of Composite Entity Design Pattern + +The Composite Entity design pattern in Java is aimed at managing a set of interrelated persistent objects as if they were a single entity. It is commonly used in enterprise applications, particularly within the context of Enterprise JavaBeans (EJB) and similar enterprise frameworks, to represent graph-based data structures within business models. This pattern enables clients to treat these complex structures as a single unit, simplifying operations and interactions. + +## Detailed Explanation of Composite Entity Pattern with Real-World Examples + +Real-world example + +> Consider a university registration system where a "Student" entity is a composite entity. Each "Student" object includes several dependent objects: personal details, course enrollments, grades, and payment information. Instead of managing each of these aspects separately, the Composite Entity design pattern allows the university system to treat the "Student" as a single entity. This simplifies operations such as enrolling a student in a new course, updating grades, and processing payments, since all related actions can be managed through the composite "Student" object. + +In plain words + +> The Composite Entity pattern in Java allows a set of related persistent objects to be represented and managed by a unified object, simplifying enterprise application design. + +Wikipedia says + +> Composite entity is a Java EE Software design pattern and it is used to model, represent, and manage a set of interrelated persistent objects rather than representing them as individual fine-grained entity beans, and also a composite entity bean represents a graph of objects. + +Flowchart + +![Composite Entity flowchart](./etc/composite-entity-flowchart.png) + +## Programmatic Example of Composite Entity in Java + +For a console, there may be many interfaces that need to be managed and controlled. Using the composite entity pattern, dependent objects such as messages and signals can be combined and controlled using a single object. + +We need a generic solution for the problem. To achieve this, let's introduce a generic Composite Entity Pattern. + +```java +public abstract class DependentObject { + + T data; + + public void setData(T message) { + this.data = message; + } + + public T getData() { + return data; + } +} + +public abstract class CoarseGrainedObject { + + DependentObject[] dependentObjects; + + public void setData(T... data) { + IntStream.range(0, data.length).forEach(i -> dependentObjects[i].setData(data[i])); + } + + public T[] getData() { + return (T[]) Arrays.stream(dependentObjects).map(DependentObject::getData).toArray(); + } +} + +``` + +The specialized composite entity `console` inherit from this base class as follows. + +```java +public class MessageDependentObject extends DependentObject { + +} + +public class SignalDependentObject extends DependentObject { + +} + +public class ConsoleCoarseGrainedObject extends CoarseGrainedObject { + + @Override + public String[] getData() { + super.getData(); + return new String[] { + dependentObjects[0].getData(), dependentObjects[1].getData() + }; + } + + public void init() { + dependentObjects = new DependentObject[] { + new MessageDependentObject(), new SignalDependentObject()}; + } +} + +public class CompositeEntity { + + private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); + + public void setData(String message, String signal) { + console.setData(message, signal); + } + + public String[] getData() { + return console.getData(); + } +} +``` + +Now managing the assignment of message and signal objects with the composite entity `console`. + +```java +public App(String message, String signal) { + var console = new CompositeEntity(); + console.init(); + console.setData(message, signal); + Arrays.stream(console.getData()).forEach(LOGGER::info); + console.setData("Danger", "Red Light"); + Arrays.stream(console.getData()).forEach(LOGGER::info); +} +``` + +## When to Use the Composite Entity Pattern in Java + +* Useful in Java enterprise applications where business objects are complex and involve various interdependent persistent objects. +* Ideal for scenarios where clients need to work with a unified interface to a set of objects rather than individual entities. +* Applicable in systems that require a simplified view of a complex data model for external clients or services. + + +## Real-World Applications of Composite Entity Pattern in Java + +* Enterprise applications with complex business models, particularly those using EJB or similar enterprise frameworks. +* Systems requiring abstraction over complex database schemas to simplify client interactions. +* Applications that need to enforce consistency or transactions across multiple persistent objects in a business entity. + +## Benefits and Trade-offs of Composite Entity Pattern + +Benefits: + +* Simplifies client interactions with complex entity models by providing a unified interface. +* Enhances reusability and maintainability of the business layer by decoupling client code from the complex internals of business entities. +* Facilitates easier transaction management and consistency enforcement across a set of related persistent objects. + +Trade-offs: + +* May introduce a level of indirection that could impact performance. +* Can lead to overly coarse-grained interfaces that might not be as flexible for all client needs. +* Requires careful design to avoid bloated composite entities that are difficult to manage. + +## Related Java Design Patterns + +* [Decorator](https://java-design-patterns.com/patterns/decorator/): For dynamically adding behavior to individual objects within the composite entity without affecting the structure. +* [Facade](https://java-design-patterns.com/patterns/facade/): Provides a simplified interface to a complex subsystem, similar to how a composite entity simplifies access to a set of objects. +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Useful for managing shared objects within a composite entity to reduce memory footprint. + +## References and Credits + +* [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) +* [Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML](https://amzn.to/49mslqS) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3xjKdpe) +* [Composite Entity Pattern (Wikipedia)](https://en.wikipedia.org/wiki/Composite_entity_pattern) diff --git a/composite-entity/etc/composite-entity-flowchart.png b/composite-entity/etc/composite-entity-flowchart.png new file mode 100644 index 000000000000..2954db2db2fe Binary files /dev/null and b/composite-entity/etc/composite-entity-flowchart.png differ diff --git a/composite-entity/etc/composite-entity.urm.puml b/composite-entity/etc/composite-entity.urm.puml new file mode 100644 index 000000000000..5ac4b9e655d8 --- /dev/null +++ b/composite-entity/etc/composite-entity.urm.puml @@ -0,0 +1,45 @@ +@startuml +package com.iluwatar.compositeentity { + class App { + + App(message: String, signal: String) + + main(args : String[]) {static} + } + class CompositeEntity{ + - console : ConsoleCoarseGrainedObject + + CompositeEntity() + + setData(message: String, signal: String) + + getData() + + init() + } + abstract CoarseGrainedObject{ + - dependentObjects : DependentObject[] + + CoarseGrainedObject() + + setData(data: T[]) + + getData() + } + abstract DependentObject{ + - data : T + + DependentObject() + + setData(data: T) + + getData() + } + class ConsoleCoarseGrainedObject{ + + ConsoleCoarseGrainedObject() + + getData() + + init() + } + class MessageDependentObject{ + + MessageDependentObject() + } + class SignalDependentObject{ + + SignalDependentObject() + } + + MessageDependentObject --|> DependentObject + SignalDependentObject --|> DependentObject + ConsoleCoarseGrainedObject --|> CoarseGrainedObject + CompositeEntity -right-> ConsoleCoarseGrainedObject + CoarseGrainedObject "1" o--> "0.." DependentObject + App .right.> CompositeEntity +} +@enduml diff --git a/composite-entity/etc/composite_entity.urm.png b/composite-entity/etc/composite_entity.urm.png new file mode 100644 index 000000000000..d6c29a718837 Binary files /dev/null and b/composite-entity/etc/composite_entity.urm.png differ diff --git a/composite-entity/pom.xml b/composite-entity/pom.xml new file mode 100644 index 000000000000..5d11234c3a0a --- /dev/null +++ b/composite-entity/pom.xml @@ -0,0 +1,70 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + composite-entity + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.composite-entity.com.iluwatar.compositeentity.App + + + + + + + + + diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/App.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/App.java new file mode 100644 index 000000000000..c3ae1181a800 --- /dev/null +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/App.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeentity; + +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; + +/** + * Composite entity is a Java EE Software design pattern and it is used to model, represent, and + * manage a set of interrelated persistent objects rather than representing them as individual + * fine-grained entity beans, and also a composite entity bean represents a graph of objects. + */ +@Slf4j +public class App { + + /** An instance that a console manages two related objects. */ + public App(String message, String signal) { + var console = new CompositeEntity(); + console.init(); + console.setData(message, signal); + Arrays.stream(console.getData()).forEach(LOGGER::info); + console.setData("Danger", "Red Light"); + Arrays.stream(console.getData()).forEach(LOGGER::info); + } + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + + new App("No Danger", "Green Light"); + } +} diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/CoarseGrainedObject.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/CoarseGrainedObject.java new file mode 100644 index 000000000000..fa195c2cd9fd --- /dev/null +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/CoarseGrainedObject.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeentity; + +import java.util.Arrays; +import java.util.stream.IntStream; + +/** + * A coarse-grained object is an object with its own life cycle manages its own relationships to + * other objects. It can be an object contained in the composite entity, or, composite entity itself + * can be the coarse-grained object which holds dependent objects. + */ +public abstract class CoarseGrainedObject { + + DependentObject[] dependentObjects; + + public void setData(T... data) { + IntStream.range(0, data.length).forEach(i -> dependentObjects[i].setData(data[i])); + } + + public T[] getData() { + return (T[]) Arrays.stream(dependentObjects).map(DependentObject::getData).toArray(); + } +} diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/CompositeEntity.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/CompositeEntity.java new file mode 100644 index 000000000000..0c4a05155ca8 --- /dev/null +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/CompositeEntity.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeentity; + +/** + * Composite entity is the coarse-grained entity bean which may be the coarse-grained object, or may + * contain a reference to the coarse-grained object. + */ +public class CompositeEntity { + + private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); + + public void setData(String message, String signal) { + console.setData(message, signal); + } + + public String[] getData() { + return console.getData(); + } + + public void init() { + console.init(); + } +} diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/ConsoleCoarseGrainedObject.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/ConsoleCoarseGrainedObject.java new file mode 100644 index 000000000000..422fdc541079 --- /dev/null +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/ConsoleCoarseGrainedObject.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeentity; + +/** A specific CoarseGrainedObject to implement a console. */ +public class ConsoleCoarseGrainedObject extends CoarseGrainedObject { + + @Override + public String[] getData() { + return new String[] {dependentObjects[0].getData(), dependentObjects[1].getData()}; + } + + public void init() { + dependentObjects = + new DependentObject[] {new MessageDependentObject(), new SignalDependentObject()}; + } +} diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/DependentObject.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/DependentObject.java new file mode 100644 index 000000000000..90f2024bc127 --- /dev/null +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/DependentObject.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeentity; + +import lombok.Getter; +import lombok.Setter; + +/** + * It is an object, which can contain other dependent objects (there may be a tree of objects within + * the composite entity), that depends on the coarse-grained object and has its life cycle managed + * by the coarse-grained object. + */ +@Setter +@Getter +public abstract class DependentObject { + + T data; +} diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/MessageDependentObject.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/MessageDependentObject.java new file mode 100644 index 000000000000..199e5ee1d859 --- /dev/null +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/MessageDependentObject.java @@ -0,0 +1,28 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeentity; + +/** The first DependentObject to show message. */ +public class MessageDependentObject extends DependentObject {} diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/SignalDependentObject.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/SignalDependentObject.java new file mode 100644 index 000000000000..cc3847c2905d --- /dev/null +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/SignalDependentObject.java @@ -0,0 +1,28 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeentity; + +/** The second DependentObject to show message. */ +public class SignalDependentObject extends DependentObject {} diff --git a/composite-entity/src/test/java/com/iluwatar/compositeentity/AppTest.java b/composite-entity/src/test/java/com/iluwatar/compositeentity/AppTest.java new file mode 100644 index 000000000000..4010c2912dae --- /dev/null +++ b/composite-entity/src/test/java/com/iluwatar/compositeentity/AppTest.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeentity; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** com.iluwatar.compositeentity.App running test */ +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/composite-entity/src/test/java/com/iluwatar/compositeentity/PersistenceTest.java b/composite-entity/src/test/java/com/iluwatar/compositeentity/PersistenceTest.java new file mode 100644 index 000000000000..08e7899b4a58 --- /dev/null +++ b/composite-entity/src/test/java/com/iluwatar/compositeentity/PersistenceTest.java @@ -0,0 +1,56 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeentity; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class PersistenceTest { + + static final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); + + @Test + void dependentObjectChangedForPersistenceTest() { + MessageDependentObject dependentObject = new MessageDependentObject(); + console.init(); + console.dependentObjects[0] = dependentObject; + String message = "Danger"; + assertNull(console.dependentObjects[0].getData()); + dependentObject.setData(message); + assertEquals(message, console.dependentObjects[0].getData()); + } + + @Test + void coarseGrainedObjectChangedForPersistenceTest() { + MessageDependentObject dependentObject = new MessageDependentObject(); + console.init(); + console.dependentObjects[0] = dependentObject; + String message = "Danger"; + assertNull(console.dependentObjects[0].getData()); + console.setData(message); + assertEquals(message, dependentObject.getData()); + } +} diff --git a/composite-view/README.md b/composite-view/README.md new file mode 100644 index 000000000000..a670f00ffdb6 --- /dev/null +++ b/composite-view/README.md @@ -0,0 +1,350 @@ +--- +title: "Composite View Pattern in Java: Enhancing UI Consistency Across Applications" +shortTitle: Composite View +description: "Learn about the Composite View design pattern in Java, which helps in managing complex hierarchical views. This guide includes examples, applications, and benefits of using the Composite View pattern." +category: Structural +language: en +tag: + - Abstraction + - Enterprise patterns + - Object composition + - Presentation +--- + +## Intent of Composite View Design Pattern + +The primary goal of the Composite View design pattern is to compose objects into tree structures to represent part-whole hierarchies. This allows clients to treat individual objects and compositions of objects uniformly, simplifying the management of complex hierarchical views. + +## Detailed Explanation of Composite View Pattern with Real-World Examples + +Real-world example + +> A real-world example of the Composite View design pattern is the layout of a dashboard in a web application. Consider a financial dashboard that displays various widgets such as stock charts, recent transactions, account balances, and news feeds. Each of these widgets is a separate view component that can be independently updated and managed. By using the Composite View pattern, these individual widgets are composed into a single unified dashboard view. This approach allows for easy reorganization of the dashboard, the addition of new widgets without disrupting existing ones, and consistent management of the overall layout. This hierarchical composition of views mirrors how different sections of the dashboard are treated both as individual entities and as part of a larger whole. + +In plain words + +> Composite View Pattern is having a main view being composed of smaller subviews. The layout of this composite view is based on a template. A View-manager then decides which subviews to include in this template. + +Wikipedia says + +> Composite views that are composed of multiple atomic subviews. Each component of the template may be included dynamically into the whole and the layout of the page may be managed independently of the content. This solution provides for the creation of a composite view based on the inclusion and substitution of modular dynamic and static template fragments. It promotes the reuse of atomic portions of the view by encouraging modular design. + +Flowchart + +![Composite View flowchart](./etc/composite-view-flowchart.png) + +## Programmatic Example of Composite View Pattern in Java + +A news site wants to display the current date and news to different users based on that user's preferences. The news site will substitute in different news feed components depending on the user's interest, defaulting to local news. + +Since this is a web development pattern, a server is required to demonstrate it. This example uses Tomcat 10.0.13 to run the servlet, and this programmatic example will only work with Tomcat 10+. + +Firstly, there is `AppServlet` which is an `HttpServlet` that runs on Tomcat 10+. + +```java +public class AppServlet extends HttpServlet { + private String msgPartOne = "

    This Server Doesn't Support"; + private String msgPartTwo = "Requests

    \n" + + "

    Use a GET request with boolean values for the following parameters

    \n" + + "

    'name'

    \n

    'bus'

    \n

    'sports'

    \n

    'sci'

    \n

    'world'

    "; + + private String destination = "newsDisplay.jsp"; + + public AppServlet() { + + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination); + ClientPropertiesBean reqParams = new ClientPropertiesBean(req); + req.setAttribute("properties", reqParams); + requestDispatcher.forward(req, resp); + } + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Post " + msgPartTwo); + + } + + @Override + public void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Delete " + msgPartTwo); + + } + + @Override + public void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Put " + msgPartTwo); + + } +} + +``` + +This servlet is not part of the pattern, and simply forwards GET requests to the correct JSP. PUT, POST, and DELETE requests are not supported and will simply show an error message. + +The view management in this example is done via a javabean class: `ClientPropertiesBean`, which stores user preferences. + +```java +public class ClientPropertiesBean implements Serializable { + + private static final String WORLD_PARAM = "world"; + private static final String SCIENCE_PARAM = "sci"; + private static final String SPORTS_PARAM = "sport"; + private static final String BUSINESS_PARAM = "bus"; + private static final String NAME_PARAM = "name"; + + private static final String DEFAULT_NAME = "DEFAULT_NAME"; + private boolean worldNewsInterest; + private boolean sportsInterest; + private boolean businessInterest; + private boolean scienceNewsInterest; + private String name; + + public ClientPropertiesBean() { + worldNewsInterest = true; + sportsInterest = true; + businessInterest = true; + scienceNewsInterest = true; + name = DEFAULT_NAME; + + } + + public ClientPropertiesBean(HttpServletRequest req) { + worldNewsInterest = Boolean.parseBoolean(req.getParameter(WORLD_PARAM)); + sportsInterest = Boolean.parseBoolean(req.getParameter(SPORTS_PARAM)); + businessInterest = Boolean.parseBoolean(req.getParameter(BUSINESS_PARAM)); + scienceNewsInterest = Boolean.parseBoolean(req.getParameter(SCIENCE_PARAM)); + String tempName = req.getParameter(NAME_PARAM); + if (tempName == null || tempName == "") { + tempName = DEFAULT_NAME; + } + name = tempName; + } + // getters and setters generated by Lombok +} +``` + +This javabean has a default constructor, and another that takes an `HttpServletRequest`. + +This second constructor takes the request object, parses out the request parameters which contain the user preferences for different types of news. + +The template for the news page is in `newsDisplay.jsp` + +```html + + + + + + +<%ClientPropertiesBean propertiesBean = (ClientPropertiesBean) request.getAttribute("properties");%> +

    Welcome <%= propertiesBean.getName()%>

    + + + + + + <% if(propertiesBean.isWorldNewsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isBusinessInterest()) { %> + + <% } else { %> + + <% } %> + + <% if(propertiesBean.isSportsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isScienceNewsInterest()) { %> + + <% } else { %> + + <% } %> + + +
    <%@include file="worldNews.jsp"%><%@include file="localNews.jsp"%>
    <%@include file="businessNews.jsp"%><%@include file="localNews.jsp"%><%@include file="sportsNews.jsp"%><%@include file="localNews.jsp"%>
    <%@include file="scienceNews.jsp"%><%@include file="localNews.jsp"%>
    + + +``` + +This JSP page is the template. It declares a table with three rows, with one component in the first row, two components in the second row, and one component in the third row. + +The scriplets in the file are part of the view management strategy that include different atomic subviews based on the user preferences in the Javabean. + +Here are two examples of the mock atomic subviews used in the composite: `businessNews.jsp` + +```html + + + + + + +

    + Generic Business News +

    + + + + + + + + + +
    Stock prices up across the worldNew tech companies to invest in
    Industry leaders unveil new projectPrice fluctuations and what they mean
    + + +``` + +`localNews.jsp` + +```html + + + +
    +

    + Generic Local News +

    +
      +
    • + Mayoral elections coming up in 2 weeks +
    • +
    • + New parking meter rates downtown coming tomorrow +
    • +
    • + Park renovations to finish by the next year +
    • +
    • + Annual marathon sign ups available online +
    • +
    +
    + + +``` + +The different subviews such as `worldNews.jsp`, `businessNews.jsp`, etc. are included conditionally based on the request parameters. + +**How To Use** + +To try this example, make sure you have Tomcat 10+ installed. Set up your IDE to build a WAR file from the module and deploy that file to the server + +IntelliJ: + +Under `Run` and `edit configurations` Make sure Tomcat server is one of the run configurations. Go to the deployment tab, and make sure there is one artifact being built called `composite-view:war exploded`. If not present, add one. + +Ensure that the artifact is being built from the content of the `web` directory and the compilation results of the module. Point the output of the artifact to a convenient place. Run the configuration and view the landing page, follow instructions on that page to continue. + +## When to Use the Composite View Pattern in Java + +Use the Composite View design pattern when: + +* You want to represent part-whole hierarchies of objects. +* You expect that the composite structures might include any new components in the future. +* You want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly. + +## Composite View Pattern Java Tutorials + +* [Composite View Design Pattern – Core J2EE Patterns (Dinesh on Java)](https://www.dineshonjava.com/composite-view-design-pattern/) + +## Real-World Applications of Composite View Pattern in Java + +* Graphical User Interfaces (GUIs) where widgets can contain other widgets (e.g., a window containing panels, buttons, and text fields). +* Document structures, such as the representation of tables containing rows, which in turn contain cells, all of which can be treated as elements in a unified hierarchy. + +## Benefits and Trade-offs of Composite View Pattern + +Benefits: + +* High flexibility in adding new components: Since composites and leaf nodes are treated uniformly, it's easier to add new kinds of components. +* Simplified client code: Clients can treat composite structures and individual elements uniformly, reducing the complexity in client code. + +Trade-offs: + +* Overgeneralization: Designing the system might become more complex if you make everything composite, especially if your application doesn't require it. +* Difficulty in constraint enforcement: It can be harder to restrict the components of a composite to only certain types. + +## Related Java Design Patterns + +* [Composite](https://java-design-patterns.com/patterns/composite/): General structural pattern that is the foundation for Composite View, used for treating individual objects and compositions uniformly. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Enhances the behavior of individual views without modifying the underlying view. +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used to manage memory consumption of large numbers of similar view objects. +* View Helper: Separates the view logic from business logic, aiding in the clean organization and management of view components. + +## References and Credits + +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3xfntGJ) +* [Patterns of Enterprise Application Architecture](https://amzn.to/49jpQG3) +* [Core J2EE Patterns - Composite View (Oracle)](https://www.oracle.com/java/technologies/composite-view.html) diff --git a/composite-view/etc/composite-view-flowchart.png b/composite-view/etc/composite-view-flowchart.png new file mode 100644 index 000000000000..bee1d8d9b006 Binary files /dev/null and b/composite-view/etc/composite-view-flowchart.png differ diff --git a/composite-view/etc/composite-view.urm.puml b/composite-view/etc/composite-view.urm.puml new file mode 100644 index 000000000000..e92b13ea5961 --- /dev/null +++ b/composite-view/etc/composite-view.urm.puml @@ -0,0 +1,29 @@ +@startuml +package com.iluwatar.compositeview { + class ClientPropertiesBean { + - BUSINESS_PARAM : String {static} + - DEFAULT_NAME : String {static} + - NAME_PARAM : String {static} + - SCIENCE_PARAM : String {static} + - SPORTS_PARAM : String {static} + - WORLD_PARAM : String {static} + - businessInterest : boolean + - name : String + - scienceNewsInterest : boolean + - sportsInterest : boolean + - worldNewsInterest : boolean + + ClientPropertiesBean() + + ClientPropertiesBean(req : HttpServletRequest) + + getName() : String + + isBusinessInterest() : boolean + + isScienceNewsInterest() : boolean + + isSportsInterest() : boolean + + isWorldNewsInterest() : boolean + + setBusinessInterest(businessInterest : boolean) + + setName(name : String) + + setScienceNewsInterest(scienceNewsInterest : boolean) + + setSportsInterest(sportsInterest : boolean) + + setWorldNewsInterest(worldNewsInterest : boolean) + } +} +@enduml \ No newline at end of file diff --git a/composite-view/etc/composite_view.png b/composite-view/etc/composite_view.png new file mode 100644 index 000000000000..66215d9416b8 Binary files /dev/null and b/composite-view/etc/composite_view.png differ diff --git a/composite-view/pom.xml b/composite-view/pom.xml new file mode 100644 index 000000000000..f8b38b5233f6 --- /dev/null +++ b/composite-view/pom.xml @@ -0,0 +1,84 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + composite-view + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + jakarta.servlet + jakarta.servlet-api + 6.1.0 + compile + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.compositeview.App + + + + + + + + + + \ No newline at end of file diff --git a/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java new file mode 100644 index 000000000000..3b803a6152f3 --- /dev/null +++ b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java @@ -0,0 +1,94 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeview; + +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.PrintWriter; +import lombok.NoArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** A servlet object that extends HttpServlet. Runs on Tomcat 10 and handles Http requests */ +@Slf4j +@NoArgsConstructor +public final class AppServlet extends HttpServlet { + private static final String CONTENT_TYPE = "text/html"; + private String msgPartOne = "

    This Server Doesn't Support"; + private String msgPartTwo = + """ + Requests

    +

    Use a GET request with boolean values for the following parameters

    +

    'name'

    +

    'bus'

    +

    'sports'

    +

    'sci'

    +

    'world'

    """; + + private String destination = "newsDisplay.jsp"; + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) { + try { + RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination); + ClientPropertiesBean reqParams = new ClientPropertiesBean(req); + req.setAttribute("properties", reqParams); + requestDispatcher.forward(req, resp); + } catch (Exception e) { + LOGGER.error("Exception occurred GET request processing ", e); + } + } + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) { + resp.setContentType(CONTENT_TYPE); + try (PrintWriter out = resp.getWriter()) { + out.println(msgPartOne + " Post " + msgPartTwo); + } catch (Exception e) { + LOGGER.error("Exception occurred POST request processing ", e); + } + } + + @Override + public void doDelete(HttpServletRequest req, HttpServletResponse resp) { + resp.setContentType(CONTENT_TYPE); + try (PrintWriter out = resp.getWriter()) { + out.println(msgPartOne + " Delete " + msgPartTwo); + } catch (Exception e) { + LOGGER.error("Exception occurred DELETE request processing ", e); + } + } + + @Override + public void doPut(HttpServletRequest req, HttpServletResponse resp) { + resp.setContentType(CONTENT_TYPE); + try (PrintWriter out = resp.getWriter()) { + out.println(msgPartOne + " Put " + msgPartTwo); + } catch (Exception e) { + LOGGER.error("Exception occurred PUT request processing ", e); + } + } +} diff --git a/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java b/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java new file mode 100644 index 000000000000..ecda0cb38e6e --- /dev/null +++ b/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeview; + +import jakarta.servlet.http.HttpServletRequest; +import java.io.Serializable; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * A Java beans class that parses a http request and stores parameters. Java beans used in JSP's to + * dynamically include elements in view. DEFAULT_NAME = a constant, default name to be used for the + * default constructor worldNewsInterest = whether current request has world news interest + * sportsInterest = whether current request has a sportsInterest businessInterest = whether current + * request has a businessInterest scienceNewsInterest = whether current request has a + * scienceNewsInterest + */ +@Getter +@Setter +@NoArgsConstructor +public class ClientPropertiesBean implements Serializable { + + private static final String WORLD_PARAM = "world"; + private static final String SCIENCE_PARAM = "sci"; + private static final String SPORTS_PARAM = "sport"; + private static final String BUSINESS_PARAM = "bus"; + private static final String NAME_PARAM = "name"; + + private static final String DEFAULT_NAME = "DEFAULT_NAME"; + private boolean worldNewsInterest = true; + private boolean sportsInterest = true; + private boolean businessInterest = true; + private boolean scienceNewsInterest = true; + private String name = DEFAULT_NAME; + + /** + * Constructor that parses an HttpServletRequest and stores all the request parameters. + * + * @param req the HttpServletRequest object that is passed in + */ + public ClientPropertiesBean(HttpServletRequest req) { + worldNewsInterest = Boolean.parseBoolean(req.getParameter(WORLD_PARAM)); + sportsInterest = Boolean.parseBoolean(req.getParameter(SPORTS_PARAM)); + businessInterest = Boolean.parseBoolean(req.getParameter(BUSINESS_PARAM)); + scienceNewsInterest = Boolean.parseBoolean(req.getParameter(SCIENCE_PARAM)); + String tempName = req.getParameter(NAME_PARAM); + if (tempName == null || tempName.equals("")) { + tempName = DEFAULT_NAME; + } + name = tempName; + } +} diff --git a/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java b/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java new file mode 100644 index 000000000000..8219a56e4f39 --- /dev/null +++ b/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java @@ -0,0 +1,116 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeview; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.PrintWriter; +import java.io.StringWriter; +import org.junit.jupiter.api.Test; + +class AppServletTest { + + private final String msgPartOne = "

    This Server Doesn't Support"; + private final String msgPartTwo = + """ + Requests

    +

    Use a GET request with boolean values for the following parameters

    +

    'name'

    +

    'bus'

    +

    'sports'

    +

    'sci'

    +

    'world'

    """; + private final String destination = "newsDisplay.jsp"; + + @Test + void testDoGet() throws Exception { + HttpServletRequest mockReq = mock(HttpServletRequest.class); + HttpServletResponse mockResp = mock(HttpServletResponse.class); + RequestDispatcher mockDispatcher = mock(RequestDispatcher.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + + when(mockResp.getWriter()).thenReturn(printWriter); + when(mockReq.getRequestDispatcher(destination)).thenReturn(mockDispatcher); + + AppServlet curServlet = new AppServlet(); + curServlet.doGet(mockReq, mockResp); + + verify(mockReq, times(1)).getRequestDispatcher(destination); + verify(mockDispatcher).forward(mockReq, mockResp); + } + + @Test + void testDoPost() throws Exception { + HttpServletRequest mockReq = mock(HttpServletRequest.class); + HttpServletResponse mockResp = mock(HttpServletResponse.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + + when(mockResp.getWriter()).thenReturn(printWriter); + + AppServlet curServlet = new AppServlet(); + curServlet.doPost(mockReq, mockResp); + printWriter.flush(); + + assertTrue(stringWriter.toString().contains(msgPartOne + " Post " + msgPartTwo)); + } + + @Test + void testDoPut() throws Exception { + HttpServletRequest mockReq = mock(HttpServletRequest.class); + HttpServletResponse mockResp = mock(HttpServletResponse.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + + when(mockResp.getWriter()).thenReturn(printWriter); + + AppServlet curServlet = new AppServlet(); + curServlet.doPut(mockReq, mockResp); + printWriter.flush(); + + assertTrue(stringWriter.toString().contains(msgPartOne + " Put " + msgPartTwo)); + } + + @Test + void testDoDelete() throws Exception { + HttpServletRequest mockReq = mock(HttpServletRequest.class); + HttpServletResponse mockResp = mock(HttpServletResponse.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + + when(mockResp.getWriter()).thenReturn(printWriter); + + AppServlet curServlet = new AppServlet(); + curServlet.doDelete(mockReq, mockResp); + printWriter.flush(); + + assertTrue(stringWriter.toString().contains(msgPartOne + " Delete " + msgPartTwo)); + } +} diff --git a/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java b/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java new file mode 100644 index 000000000000..8e27a20e06f9 --- /dev/null +++ b/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java @@ -0,0 +1,101 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.compositeview; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.Test; + +class JavaBeansTest { + + @Test + void testDefaultConstructor() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertEquals("DEFAULT_NAME", newBean.getName()); + assertTrue(newBean.isBusinessInterest()); + assertTrue(newBean.isScienceNewsInterest()); + assertTrue(newBean.isSportsInterest()); + assertTrue(newBean.isWorldNewsInterest()); + } + + @Test + void testNameGetterSetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertEquals("DEFAULT_NAME", newBean.getName()); + + newBean.setName("TEST_NAME_ONE"); + assertEquals("TEST_NAME_ONE", newBean.getName()); + } + + @Test + void testBusinessSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isBusinessInterest()); + + newBean.setBusinessInterest(false); + assertFalse(newBean.isBusinessInterest()); + } + + @Test + void testScienceSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isScienceNewsInterest()); + + newBean.setScienceNewsInterest(false); + assertFalse(newBean.isScienceNewsInterest()); + } + + @Test + void testSportsSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isSportsInterest()); + + newBean.setSportsInterest(false); + assertFalse(newBean.isSportsInterest()); + } + + @Test + void testWorldSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isWorldNewsInterest()); + + newBean.setWorldNewsInterest(false); + assertFalse(newBean.isWorldNewsInterest()); + } + + @Test + void testRequestConstructor() { + HttpServletRequest mockReq = mock(HttpServletRequest.class); + ClientPropertiesBean newBean = new ClientPropertiesBean(mockReq); + + assertEquals("DEFAULT_NAME", newBean.getName()); + assertFalse(newBean.isWorldNewsInterest()); + assertFalse(newBean.isBusinessInterest()); + assertFalse(newBean.isScienceNewsInterest()); + assertFalse(newBean.isSportsInterest()); + } +} diff --git a/composite-view/web/WEB-INF/web.xml b/composite-view/web/WEB-INF/web.xml new file mode 100644 index 000000000000..01d4196204f4 --- /dev/null +++ b/composite-view/web/WEB-INF/web.xml @@ -0,0 +1,40 @@ + + + + + appServlet + com.iluwatar.compositeview.AppServlet + + + appServlet + /news + + \ No newline at end of file diff --git a/composite-view/web/businessNews.jsp b/composite-view/web/businessNews.jsp new file mode 100644 index 000000000000..c2e2543565e9 --- /dev/null +++ b/composite-view/web/businessNews.jsp @@ -0,0 +1,59 @@ +<%-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 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. + +--%> +<%-- + Created by IntelliJ IDEA. + User: Kevin + Date: 11/29/2021 + Time: 2:51 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + +

    + Generic Business News +

    + + + + + + + + + +
    Stock prices up across the worldNew tech companies to invest in
    Industry leaders unveil new projectPrice fluctuations and what they mean
    + + diff --git a/composite-view/web/header.jsp b/composite-view/web/header.jsp new file mode 100644 index 000000000000..3327c7bca654 --- /dev/null +++ b/composite-view/web/header.jsp @@ -0,0 +1,68 @@ +<%-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 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. + +--%> +<%-- + Created by IntelliJ IDEA. + User: Kevin + Date: 11/29/2021 + Time: 1:28 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ page import="java.util.Date"%> + + + + + + + + <% String todayDateStr = (new Date().toString()); %> +

    Today's Personalized Frontpage

    +

    <%= todayDateStr %>

    + + diff --git a/composite-view/web/index.jsp b/composite-view/web/index.jsp new file mode 100644 index 000000000000..47a8d774caad --- /dev/null +++ b/composite-view/web/index.jsp @@ -0,0 +1,78 @@ +<%-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 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. + +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Composite Patterns Mock News Site + + + +

    Welcome To The Composite Patterns Mock News Site

    +
    +

    Send a GET request to the "/news" path to see the composite view with mock news

    +

    Use the following parameters:

    +

    name: string - Your name to be dynamically displayed

    +

    bus: boolean - Set to true to see mock business news

    +

    world: boolean - Set to true to see mock world news

    +

    sci: boolean - Set to true to see mock science news

    +

    sport: boolean - Set to true to see mock sports news

    +

    Example Request:

    +

    /news?name=John&bus=true&world=false&sci=true&sport=false

    +

    If the request fails, ensure you have the correct parameters and try again.

    +
    + + diff --git a/composite-view/web/localNews.jsp b/composite-view/web/localNews.jsp new file mode 100644 index 000000000000..e596151e923f --- /dev/null +++ b/composite-view/web/localNews.jsp @@ -0,0 +1,50 @@ +<%-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 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. + +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + +
    +

    + Generic Local News +

    +
      +
    • + Mayoral elections coming up in 2 weeks +
    • +
    • + New parking meter rates downtown coming tomorrow +
    • +
    • + Park renovations to finish by the next year +
    • +
    • + Annual marathon sign ups available online +
    • +
    +
    + + diff --git a/composite-view/web/newsDisplay.jsp b/composite-view/web/newsDisplay.jsp new file mode 100644 index 000000000000..7503b2a46014 --- /dev/null +++ b/composite-view/web/newsDisplay.jsp @@ -0,0 +1,83 @@ +<%-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 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. + +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ page import="com.iluwatar.compositeview.ClientPropertiesBean"%> + + + + + + <%ClientPropertiesBean propertiesBean = (ClientPropertiesBean) request.getAttribute("properties");%> +

    Welcome <%= propertiesBean.getName()%>

    + + + + + + <% if(propertiesBean.isWorldNewsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isBusinessInterest()) { %> + + <% } else { %> + + <% } %> + + <% if(propertiesBean.isSportsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isScienceNewsInterest()) { %> + + <% } else { %> + + <% } %> + + +
    <%@include file="worldNews.jsp"%><%@include file="localNews.jsp"%>
    <%@include file="businessNews.jsp"%><%@include file="localNews.jsp"%><%@include file="sportsNews.jsp"%><%@include file="localNews.jsp"%>
    <%@include file="scienceNews.jsp"%><%@include file="localNews.jsp"%>
    + + diff --git a/composite-view/web/scienceNews.jsp b/composite-view/web/scienceNews.jsp new file mode 100644 index 000000000000..643fe94ea84b --- /dev/null +++ b/composite-view/web/scienceNews.jsp @@ -0,0 +1,60 @@ +<%-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 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. + +--%> +<%-- + Created by IntelliJ IDEA. + User: Kevin + Date: 11/29/2021 + Time: 4:18 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + +
    +

    + Generic Science News +

    +
      +
    • + New model of gravity proposed for dark matter +
    • +
    • + Genetic modifying technique proved on bacteria +
    • +
    • + Neurology study maps brain with new precision +
    • +
    • + Survey of rainforest discovers 15 new species +
    • +
    • + New signalling pathway for immune system discovered +
    • +
    +
    + + diff --git a/composite-view/web/sportsNews.jsp b/composite-view/web/sportsNews.jsp new file mode 100644 index 000000000000..4647cc826c7f --- /dev/null +++ b/composite-view/web/sportsNews.jsp @@ -0,0 +1,58 @@ +<%-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 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. + +--%> +<%-- + Created by IntelliJ IDEA. + User: Kevin + Date: 11/29/2021 + Time: 3:53 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + +

    + Generic Sports News +

    +
    + International football match delayed due to weather, will be held next week +
    +
    + New rising stars in winter sports, ten new athletes that will shake up the scene +
    +
    + Biggest upset in basketball history, upstart team sweeps competition +
    + + diff --git a/composite-view/web/worldNews.jsp b/composite-view/web/worldNews.jsp new file mode 100644 index 000000000000..9057faa9ea0c --- /dev/null +++ b/composite-view/web/worldNews.jsp @@ -0,0 +1,60 @@ +<%-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 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. + +--%> +<%-- + Created by IntelliJ IDEA. + User: Kevin + Date: 11/29/2021 + Time: 2:51 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + +

    + Generic World News +

    + + + + + + + + + + +
    New trade talks happening at UN on Thursday
    European Union to announce new resolution next week
    UN delivers report on world economic status
    + + diff --git a/composite/README.md b/composite/README.md index 05ee70cbb9b9..91f5e3230ff6 100644 --- a/composite/README.md +++ b/composite/README.md @@ -1,145 +1,222 @@ --- -layout: pattern -title: Composite -folder: composite -permalink: /patterns/composite/ -categories: Structural -tags: - - Java - - Gang Of Four - - Difficulty-Intermediate +title: "Composite Pattern in Java: Building Flexible Tree Structures" +shortTitle: Composite +description: "Explore the Composite Design Pattern in Java. Learn how to compose objects into tree structures to represent part-whole hierarchies, making it easier to treat individual objects and compositions uniformly. Ideal for graphical user interfaces, file systems, and organizational structures." +category: Structural +language: en +tag: + - Decoupling + - Gang of Four + - Object composition + - Recursion --- -## Intent -Compose objects into tree structures to represent part-whole -hierarchies. Composite lets clients treat individual objects and compositions -of objects uniformly. +## Also known as -## Explanation +* Object Tree +* Composite Structure -Real world example +## Intent of Composite Design Pattern -> 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 +Compose objects into tree structures to represent part-whole hierarchies. The Composite Design Pattern lets clients treat individual objects and compositions of objects uniformly. + +## Detailed Explanation of Composite Pattern with Real-World Examples + +Real-world example + +> In a real-world example, consider a company with a complex organizational structure. The company consists of various departments, each of which can contain sub-departments, and ultimately individual employees. The Composite Design Pattern can be used to represent this structure. Each department and employee are treated as a node in a tree structure, where departments can contain other departments or employees, but employees are leaf nodes with no children. This allows the company to perform operations uniformly, such as calculating total salaries or printing the organizational chart, by treating individual employees and entire departments in the same way. In plain words -> Composite pattern lets clients treat the individual objects in a uniform manner. +> The Composite Design Pattern lets clients uniformly treat individual objects and compositions of objects. 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** +Flowchart + +![Composite flowchart](./etc/composite-flowchart.png) -Taking our sentence example from above. Here we have the base class and different printable types +## Programmatic Example of Composite Pattern in Java + +Every sentence is composed of words which are in turn composed of characters. Each of these objects are 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. + +Here we have the base class `LetterComposite` and the different printable types `Letter`, `Word` and `Sentence`. ```java 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(); + + private final 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(); + children.forEach(LetterComposite::print); + printThisAfter(); } - printThisAfter(); - } } public class Letter extends LetterComposite { - private char c; - public Letter(char c) { - this.c = c; - } - @Override - protected void printThisBefore() { - System.out.print(c); - } + + private final char character; + + public Letter(char c) { + this.character = c; + } + + @Override + protected void printThisBefore() { + System.out.print(character); + } } public class Word extends LetterComposite { - public Word(List letters) { - for (Letter l : letters) { - this.add(l); + + public Word(List letters) { + letters.forEach(this::add); + } + + public Word(char... letters) { + for (char letter : letters) { + this.add(new Letter(letter)); + } + } + + @Override + protected void printThisBefore() { + System.out.print(" "); } - } - @Override - protected void printThisBefore() { - System.out.print(" "); - } } public class Sentence extends LetterComposite { - public Sentence(List words) { - for (Word w : words) { - this.add(w); + + public Sentence(List words) { + words.forEach(this::add); + } + + @Override + protected void printThisAfter() { + System.out.print("."); } - } - @Override - protected void printThisAfter() { - System.out.print("."); - } } ``` -Then we have a messenger to carry messages +Then we have a messenger to carry messages: ```java 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); - } + + LetterComposite messageFromOrcs() { + + var words = List.of( + new Word('W', 'h', 'e', 'r', 'e'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'h', 'i', 'p'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'a', 'y') + ); + + return new Sentence(words); + + } + + LetterComposite messageFromElves() { + + var words = List.of( + new Word('M', 'u', 'c', 'h'), + new Word('w', 'i', 'n', 'd'), + new Word('p', 'o', 'u', 'r', 's'), + new Word('f', 'r', 'o', 'm'), + new Word('y', 'o', 'u', 'r'), + new Word('m', 'o', 'u', 't', 'h') + ); + + return new Sentence(words); + + } + } ``` -And then it can be used as +And then it can be used as: ```java -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. + public static void main(String[] args) { + + var messenger = new Messenger(); + + LOGGER.info("Message from the orcs: "); + messenger.messageFromOrcs().print(); + + LOGGER.info("Message from the elves: "); + messenger.messageFromElves().print(); +} ``` -## Applicability +The console output: + +``` +20:43:54.801 [main] INFO com.iluwatar.composite.App -- Message from the orcs: + Where there is a whip there is a way. +20:43:54.803 [main] INFO com.iluwatar.composite.App -- Message from the elves: + Much wind pours from your mouth. +``` + +## When to Use the Composite Pattern in Java + Use the Composite pattern when -* you want to represent part-whole hierarchies of objects -* you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly +* You want to represent part-whole hierarchies of objects. +* You want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly. -## Real world examples +## Real-World Applications of Composite Pattern in Java +* Graphical user interfaces where components can contain other components (e.g., panels containing buttons, labels, other panels). +* File system representations where directories can contain files and other directories. +* Organizational structures where a department can contain sub-departments and employees. * [java.awt.Container](http://docs.oracle.com/javase/8/docs/api/java/awt/Container.html) and [java.awt.Component](http://docs.oracle.com/javase/8/docs/api/java/awt/Component.html) * [Apache Wicket](https://github.com/apache/wicket) component tree, see [Component](https://github.com/apache/wicket/blob/91e154702ab1ff3481ef6cbb04c6044814b7e130/wicket-core/src/main/java/org/apache/wicket/Component.java) and [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java) -## Credits +## Benefits and Trade-offs of Composite Pattern + +Benefits: + +* Simplifies client code, as it can treat composite structures and individual objects uniformly. +* Makes it easier to add new kinds of components, as existing code doesn't need to be changed. + +Trade-offs: + +* Can make the design overly general. It might be difficult to restrict the components of a composite. +* Can make it harder to restrict the types of components in a composite. + +## Related Java Design Patterns + +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Composite can use Flyweight to share component instances among several composites. +* [Iterator](https://java-design-patterns.com/patterns/iterator/): Can be used to traverse Composite structures. +* [Visitor](https://java-design-patterns.com/patterns/visitor/): Can apply an operation over a Composite structure. + +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3xoLAmi) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3vBKXWb) diff --git a/composite/etc/composite-flowchart.png b/composite/etc/composite-flowchart.png new file mode 100644 index 000000000000..7938250ec332 Binary files /dev/null and b/composite/etc/composite-flowchart.png differ diff --git a/composite/etc/composite.urm.png b/composite/etc/composite.urm.png new file mode 100644 index 000000000000..93c160f6450a Binary files /dev/null and b/composite/etc/composite.urm.png differ diff --git a/composite/etc/composite.urm.puml b/composite/etc/composite.urm.puml new file mode 100644 index 000000000000..6ff774711bcd --- /dev/null +++ b/composite/etc/composite.urm.puml @@ -0,0 +1,41 @@ +@startuml +package com.iluwatar.composite { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Letter { + - character : char + + Letter(c : char) + # printThisBefore() + } + abstract class LetterComposite { + - children : List + + LetterComposite() + + add(letter : LetterComposite) + + count() : int + + print() + # printThisAfter() + # printThisBefore() + } + class Messenger { + + Messenger() + ~ messageFromElves() : LetterComposite + ~ messageFromOrcs() : LetterComposite + } + class Sentence { + + Sentence(words : List) + # printThisAfter() + } + class Word { + + Word(letters : List) + + Word(letters : char[]) + # printThisBefore() + } +} +LetterComposite --> "-children" LetterComposite +Letter --|> LetterComposite +Sentence --|> LetterComposite +Word --|> LetterComposite +@enduml \ No newline at end of file diff --git a/composite/pom.xml b/composite/pom.xml index 944aa1456e95..7beb910d901e 100644 --- a/composite/pom.xml +++ b/composite/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT composite - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.composite.App + + + + + + + + diff --git a/composite/src/main/java/com/iluwatar/composite/App.java b/composite/src/main/java/com/iluwatar/composite/App.java index 517920ac6906..366ceffa45e9 100644 --- a/composite/src/main/java/com/iluwatar/composite/App.java +++ b/composite/src/main/java/com/iluwatar/composite/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,8 +24,7 @@ */ package com.iluwatar.composite; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** * The Composite pattern is a partitioning design pattern. The Composite pattern describes that a @@ -31,29 +32,26 @@ * 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. - *

    - * In this example we have sentences composed of words composed of letters. All of the objects can - * be treated through the same interface ({@link LetterComposite}). - * + * + *

    In this example we have sentences composed of words composed of letters. All of the objects + * can be treated through the same interface ({@link LetterComposite}). */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - LOGGER.info("Message from the orcs: "); - LetterComposite orcMessage = new Messenger().messageFromOrcs(); - orcMessage.print(); + var messenger = new Messenger(); - LOGGER.info("\nMessage from the elves: "); + LOGGER.info("Message from the orcs: "); + messenger.messageFromOrcs().print(); - LetterComposite elfMessage = new Messenger().messageFromElves(); - elfMessage.print(); + LOGGER.info("Message from the elves: "); + messenger.messageFromElves().print(); } } diff --git a/composite/src/main/java/com/iluwatar/composite/Letter.java b/composite/src/main/java/com/iluwatar/composite/Letter.java index cd149122d80e..4adcba864643 100644 --- a/composite/src/main/java/com/iluwatar/composite/Letter.java +++ b/composite/src/main/java/com/iluwatar/composite/Letter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,16 @@ */ package com.iluwatar.composite; -/** - * - * Letter - * - */ -public class Letter extends LetterComposite { +import lombok.RequiredArgsConstructor; - private char c; +/** Letter. */ +@RequiredArgsConstructor +public class Letter extends LetterComposite { - public Letter(char c) { - this.c = c; - } + private final char character; @Override protected void printThisBefore() { - System.out.print(c); + System.out.print(character); } } diff --git a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java index f9ff68463628..a5b0d1cc3d55 100644 --- a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java +++ b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java @@ -1,59 +1,53 @@ -/** - * 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.composite; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * Composite interface. - * - */ -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() {} - - /** - * Print - */ - public void print() { - printThisBefore(); - for (LetterComposite letter : children) { - letter.print(); - } - printThisAfter(); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.composite; + +import java.util.ArrayList; +import java.util.List; + +/** Composite interface. */ +public abstract class LetterComposite { + + private final List children = new ArrayList<>(); + + public void add(LetterComposite letter) { + children.add(letter); + } + + public int count() { + return children.size(); + } + + protected void printThisBefore() {} + + protected void printThisAfter() {} + + /** Print. */ + public void print() { + printThisBefore(); + children.forEach(LetterComposite::print); + printThisAfter(); + } +} diff --git a/composite/src/main/java/com/iluwatar/composite/Messenger.java b/composite/src/main/java/com/iluwatar/composite/Messenger.java index 998d7e7d0bba..3af972bc6ca0 100644 --- a/composite/src/main/java/com/iluwatar/composite/Messenger.java +++ b/composite/src/main/java/com/iluwatar/composite/Messenger.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,58 +24,39 @@ */ package com.iluwatar.composite; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -/** - * - * Messenger - * - */ +/** Messenger. */ 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')))); + var words = + List.of( + new Word('W', 'h', 'e', 'r', 'e'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'h', 'i', 'p'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'a', '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')))); + var words = + List.of( + new Word('M', 'u', 'c', 'h'), + new Word('w', 'i', 'n', 'd'), + new Word('p', 'o', 'u', 'r', 's'), + new Word('f', 'r', 'o', 'm'), + new Word('y', 'o', 'u', 'r'), + new Word('m', 'o', 'u', 't', 'h')); return new Sentence(words); - } - } diff --git a/composite/src/main/java/com/iluwatar/composite/Sentence.java b/composite/src/main/java/com/iluwatar/composite/Sentence.java index ae844cf59327..448d2096cc5d 100644 --- a/composite/src/main/java/com/iluwatar/composite/Sentence.java +++ b/composite/src/main/java/com/iluwatar/composite/Sentence.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,24 +26,16 @@ import java.util.List; -/** - * - * Sentence - * - */ +/** Sentence. */ public class Sentence extends LetterComposite { - /** - * Constructor - */ + /** Constructor. */ public Sentence(List words) { - for (Word w : words) { - this.add(w); - } + words.forEach(this::add); } @Override protected void printThisAfter() { - System.out.print("."); + System.out.print(".\n"); } } diff --git a/composite/src/main/java/com/iluwatar/composite/Word.java b/composite/src/main/java/com/iluwatar/composite/Word.java index 51e21a2d4f47..5b0f82049d9c 100644 --- a/composite/src/main/java/com/iluwatar/composite/Word.java +++ b/composite/src/main/java/com/iluwatar/composite/Word.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,19 +26,22 @@ import java.util.List; -/** - * - * Word - * - */ +/** Word. */ public class Word extends LetterComposite { + /** Constructor. */ + public Word(List letters) { + letters.forEach(this::add); + } + /** - * Constructor + * Constructor. + * + * @param letters to include */ - public Word(List letters) { - for (Letter l : letters) { - this.add(l); + public Word(char... letters) { + for (char letter : letters) { + this.add(new Letter(letter)); } } diff --git a/composite/src/test/java/com/iluwatar/composite/AppTest.java b/composite/src/test/java/com/iluwatar/composite/AppTest.java index 76e0220c9206..b1c79d7357b1 100644 --- a/composite/src/test/java/com/iluwatar/composite/AppTest.java +++ b/composite/src/test/java/com/iluwatar/composite/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,20 @@ */ package com.iluwatar.composite; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. + */ @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + Assertions.assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/composite/src/test/java/com/iluwatar/composite/MessengerTest.java b/composite/src/test/java/com/iluwatar/composite/MessengerTest.java index 3911382be14a..b22b94cc6b89 100644 --- a/composite/src/test/java/com/iluwatar/composite/MessengerTest.java +++ b/composite/src/test/java/com/iluwatar/composite/MessengerTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,83 +24,62 @@ */ package com.iluwatar.composite; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +/** MessengerTest */ +class MessengerTest { -/** - * Date: 12/11/15 - 8:12 PM - * - * @author Jeroen Meulemeester - */ -public class MessengerTest { - - /** - * The buffer used to capture every write to {@link System#out} - */ + /** The buffer used to capture every write to {@link System#out} */ private ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream(); - /** - * Keep the original std-out so it can be restored after the test - */ + /** Keep the original std-out so it can be restored after the test */ private final PrintStream realStdOut = System.out; /** * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test */ @BeforeEach - public void setUp() { + void setUp() { this.stdOutBuffer = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOutBuffer)); } - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ + /** Removed the mocked std-out {@link PrintStream} again from the {@link System} class */ @AfterEach - public void tearDown() { + void tearDown() { System.setOut(realStdOut); } - /** - * Test the message from the orcs - */ + /** Test the message from the orcs */ @Test - public void testMessageFromOrcs() { - final Messenger messenger = new Messenger(); - testMessage( - messenger.messageFromOrcs(), - "Where there is a whip there is a way." - ); + void testMessageFromOrcs() { + final var messenger = new Messenger(); + testMessage(messenger.messageFromOrcs(), "Where there is a whip there is a way."); } - /** - * Test the message from the elves - */ + /** Test the message from the elves */ @Test - public void testMessageFromElves() { - final Messenger messenger = new Messenger(); - testMessage( - messenger.messageFromElves(), - "Much wind pours from your mouth." - ); + void testMessageFromElves() { + final var messenger = new Messenger(); + testMessage(messenger.messageFromElves(), "Much wind pours from your mouth."); } /** * Test if the given composed message matches the expected message * * @param composedMessage The composed message, received from the messenger - * @param message The expected message + * @param message The expected message */ private void testMessage(final LetterComposite composedMessage, final String message) { // Test is the composed message has the correct number of words - final String[] words = message.split(" "); + final var words = message.split(" "); assertNotNull(composedMessage); assertEquals(words.length, composedMessage.count()); @@ -108,5 +89,4 @@ private void testMessage(final LetterComposite composedMessage, final String mes // ... and verify if the message matches with the expected one assertEquals(message, new String(this.stdOutBuffer.toByteArray()).trim()); } - } diff --git a/context-object/README.md b/context-object/README.md new file mode 100644 index 000000000000..71e231681bcb --- /dev/null +++ b/context-object/README.md @@ -0,0 +1,201 @@ +--- +title: "Context Object Pattern in Java: Simplifying Access to Contextual Data" +shortTitle: Context Object +description: "Learn about the Context Object pattern in Java Design Patterns. Encapsulate state and behaviors relevant to users or requests to decouple application components from environmental complexities. Explore real-world examples, benefits, and implementation tips." +category: Behavioral +language: en +tags: + - Context + - Decoupling + - Encapsulation + - Session management +--- + +## Also known as + +* Context +* Context Encapsulation +* Context Holder +* Encapsulate Context + +## Intent of Context Object Design Pattern + +Encapsulate the context (state and behaviors) relevant to the user or the request being processed to decouple Java application components from the complexities of the environment. This design pattern helps in managing the application's context efficiently. + +## Detailed Explanation of Context Object Pattern with Real-World Examples + +Real-world example + +> Imagine a busy airport where multiple services need to access and share passenger information throughout their journey. Instead of each service requesting and passing passenger details separately, the airport uses a "Passenger Context Object." This context object holds all relevant passenger information, such as identity, flight details, and preferences. Various services like check-in, security, boarding, and customer service access this context object to get or update passenger data as needed. This approach ensures consistent and efficient information handling without tightly coupling the services, similar to how the Context Object design pattern works in software. + +In plain words + +> Create an object to store and manage context data, and pass this context object wherever needed in the Java application, ensuring decoupled and cleaner code. + +[Core J2EE Patterns](http://corej2eepatterns.com/ContextObject.htm) says + +> Use a Context Object to encapsulate state in a protocol-independent way to be shared throughout your application. + +Sequence diagram + +![Context Object sequence diagram](./etc/context-object-sequence-diagram.png) + +## Programmatic Example of Context Object in Java + +In a multi-layered Java application, different layers such as A, B, and C extract specific information from a shared context. Passing each piece of information individually is inefficient. The Context Object pattern efficiently stores and passes this information, improving the overall performance and maintainability of the Java application. + +Define the data that the `ServiceContext` object contains. + +```Java +@Getter +@Setter +public class ServiceContext { + + String accountService; + String sessionService; + String searchService; +} +``` + +Create interface `ServiceContextFactory` to be used in parts of the application for context objects to be created. + +```Java +public class ServiceContextFactory { + + public static ServiceContext createContext() { + return new ServiceContext(); + } +} +``` + +Instantiate the context object in the first layer. The adjoining layer calls the context in the current layer, which then further structures the object. + +```Java +@Getter +public class LayerA { + + private static ServiceContext context; + + public LayerA() { + context = ServiceContextFactory.createContext(); + } + + public void addAccountInfo(String accountService) { + context.setACCOUNT_SERVICE(accountService); + } +} +``` + +```Java +@Getter +public class LayerB { + + private static ServiceContext context; + + public LayerB(LayerA layerA) { + this.context = layerA.getContext(); + } + + public void addSessionInfo(String sessionService) { + context.setSESSION_SERVICE(sessionService); + } +} +``` + +```Java +@Getter +public class LayerC { + + public static ServiceContext context; + + public LayerC(LayerB layerB) { + this.context = layerB.getContext(); + } + + public void addSearchInfo(String searchService) { + context.setSEARCH_SERVICE(searchService); + } +} +``` + +Here is the context object and layers in action. + +```Java +@Slf4j +public class App { + + private static final String SERVICE = "SERVICE"; + + public static void main(String[] args) { + //Initiate first layer and add service information into context + var layerA = new LayerA(); + layerA.addAccountInfo(SERVICE); + + logContext(layerA.getContext()); + + //Initiate second layer and preserving information retrieved in first layer through passing context object + var layerB = new LayerB(layerA); + layerB.addSessionInfo(SERVICE); + + logContext(layerB.getContext()); + + //Initiate third layer and preserving information retrieved in first and second layer through passing context object + var layerC = new LayerC(layerB); + layerC.addSearchInfo(SERVICE); + + logContext(layerC.getContext()); + } + + private static void logContext(ServiceContext context) { + LOGGER.info("Context = {}", context); + } +} +``` + +Program output: + +``` +08:15:32.134 [main] INFO com.iluwatar.context.object.App -- Context = com.iluwatar.context.object.ServiceContext@5577140b +08:15:32.136 [main] INFO com.iluwatar.context.object.App -- Context = com.iluwatar.context.object.ServiceContext@5577140b +08:15:32.137 [main] INFO com.iluwatar.context.object.App -- Context = com.iluwatar.context.object.ServiceContext@5577140b +``` + +## When to Use the Context Object Pattern in Java + +* When there is a need to abstract and encapsulate context information in a Java application to avoid cluttering the business logic with environment-specific code. This is especially useful in web applications for encapsulating request-specific information and in distributed systems for managing user preferences and security credentials. +* In web applications, to encapsulate request-specific information and make it easily accessible throughout the application without passing it explicitly between functions or components. +* In distributed systems, to encapsulate contextual information about the task being performed, user preferences, or security credentials, facilitating their propagation across different components and services. + +## Real-World Applications of Context Object Pattern in Java + +* Web application frameworks often use the Context Object pattern to encapsulate HTTP request and response objects, session information, and other request-specific data. Enterprise Java applications leverage this pattern to manage and propagate transactional information, security credentials, and user-specific settings across different layers and services. +* Enterprise applications use Context Objects to manage and propagate transactional information, security credentials, and user-specific settings across different layers and services. +* [Spring: ApplicationContext](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html) +* [Oracle: SecurityContext](https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/SecurityContext.html) +* [Oracle: ServletContext](https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html) + +## Benefits and Trade-offs of Context Object Pattern + +Benefits: + +* Decoupling: Components and services are decoupled from the specificities of the execution environment, enhancing modularity and maintainability. +* Centralization: Contextual information is centralized in one place, making it easier to manage, access, and debug. +* Flexibility: The pattern allows for flexible and dynamic context management, which can adapt to changes in the environment or requirements. + +Trade-offs: + +* Overhead: Introducing a Context Object can add overhead in terms of performance, especially if not implemented efficiently. +* Complexity: If the Context Object is not well-designed, it can become a bloated and complex monolith, difficult to manage and understand. + +## Related Java Design Patterns + +* [Singleton](https://java-design-patterns.com/patterns/singleton/): The Context Object is often implemented as a Singleton to ensure a global point of access. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Context Objects can use Strategies to adapt their behavior based on the context they encapsulate. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to dynamically add responsibilities to the Context Object. + +## References and Credits + +* [Core J2EE Design Patterns](https://amzn.to/3IhcY9w) +* [Context Object (Core J2EE Patterns)](http://corej2eepatterns.com/ContextObject.htm) +* [The Encapsulate Context Pattern (Accu)](https://accu.org/journals/overload/12/63/kelly_246/) +* [Context Object - A Design Pattern for Efficient Information Sharing across Multiple System Layers (Arvid S. Krishna et al.)](https://www.dre.vanderbilt.edu/~schmidt/PDF/Context-Object-Pattern.pdf) diff --git a/context-object/etc/context-object-sequence-diagram.png b/context-object/etc/context-object-sequence-diagram.png new file mode 100644 index 000000000000..f8cc87ff38e2 Binary files /dev/null and b/context-object/etc/context-object-sequence-diagram.png differ diff --git a/context-object/etc/context-object.png b/context-object/etc/context-object.png new file mode 100644 index 000000000000..a1f670812f7b Binary files /dev/null and b/context-object/etc/context-object.png differ diff --git a/context-object/etc/context-object.urm.puml b/context-object/etc/context-object.urm.puml new file mode 100644 index 000000000000..fa5eb1ace480 --- /dev/null +++ b/context-object/etc/context-object.urm.puml @@ -0,0 +1,50 @@ +@startuml +package com.iluwatar.context.object { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class ServiceContext { + - ACCOUNT_SERVICE : String + - SESSION_SERVICE : String + - SEARCH_SERVICE : String + + ServiceContext() + + getACCOUNT_SERVICE() : String + + getSESSION_SERVICE() : String + + getSEARCH_SERVICE() : String + + setACCOUNT_SERVICE(service : String) + + setSESSION_SERVICE(service : String) + + setSEARCH_SERVICE(service : String) + } + class ServiceContextFactory { + + ServiceContextFactory() + + createContext() : ServiceContext + } + class LayerA { + - context : ServiceContext + + LayerA() + + getContext() : ServiceContext + + addAccountInfo() + } + class LayerB { + - context : ServiceContext + + LayerB(layerA : LayerA) + + getContext() : ServiceContext + + addAccountInfo() + } + class LayerC { + - context : ServiceContext + + LayerC(layerB : LayerB) + + getContext() : ServiceContext + + addAccountInfo() + } +} + +LayerC ..|> LayerB +ServiceContext --> LayerC +ServiceContext --> LayerB +ServiceContext --> LayerA +ServiceContextFactory ..|> "<>" ServiceContext +LayerB ..|> LayerA +@enduml \ No newline at end of file diff --git a/context-object/pom.xml b/context-object/pom.xml new file mode 100644 index 000000000000..82f8862b6905 --- /dev/null +++ b/context-object/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + context-object + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.compositeview.App + + + + + + + + + \ No newline at end of file diff --git a/context-object/src/main/java/com/iluwatar/context/object/App.java b/context-object/src/main/java/com/iluwatar/context/object/App.java new file mode 100644 index 000000000000..f0fc505c31e3 --- /dev/null +++ b/context-object/src/main/java/com/iluwatar/context/object/App.java @@ -0,0 +1,74 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.context.object; + +import lombok.extern.slf4j.Slf4j; + +/** + * In the context object pattern, information and data from underlying protocol-specific + * classes/systems is decoupled and stored into a protocol-independent object in an organised + * format. The pattern ensures the data contained within the context object can be shared and + * further structured between different layers of a software system. + * + *

    In this example we show how a context object {@link ServiceContext} can be initiated, edited + * and passed/retrieved in different layers of the program ({@link LayerA}, {@link LayerB}, {@link + * LayerC}) through use of static methods. + */ +@Slf4j +public class App { + + private static final String SERVICE = "SERVICE"; + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + // Initiate first layer and add service information into context + var layerA = new LayerA(); + layerA.addAccountInfo(SERVICE); + + logContext(layerA.getContext()); + + // Initiate second layer and preserving information retrieved in first layer through passing + // context object + var layerB = new LayerB(layerA); + layerB.addSessionInfo(SERVICE); + + logContext(layerB.getContext()); + + // Initiate third layer and preserving information retrieved in first and second layer through + // passing context object + var layerC = new LayerC(layerB); + layerC.addSearchInfo(SERVICE); + + logContext(layerC.getContext()); + } + + private static void logContext(ServiceContext context) { + LOGGER.info("Context = {}", context); + } +} diff --git a/context-object/src/main/java/com/iluwatar/context/object/LayerA.java b/context-object/src/main/java/com/iluwatar/context/object/LayerA.java new file mode 100644 index 000000000000..4d37f079052e --- /dev/null +++ b/context-object/src/main/java/com/iluwatar/context/object/LayerA.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.context.object; + +import lombok.Getter; + +/** Layer A in the context object pattern. */ +@Getter +public class LayerA { + + private ServiceContext context; + + public LayerA() { + context = ServiceContextFactory.createContext(); + } + + public void addAccountInfo(String accountService) { + context.setAccountService(accountService); + } +} diff --git a/context-object/src/main/java/com/iluwatar/context/object/LayerB.java b/context-object/src/main/java/com/iluwatar/context/object/LayerB.java new file mode 100644 index 000000000000..a67aba9bd5f7 --- /dev/null +++ b/context-object/src/main/java/com/iluwatar/context/object/LayerB.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.context.object; + +import lombok.Getter; + +/** Layer B in the context object pattern. */ +@Getter +public class LayerB { + + private ServiceContext context; + + public LayerB(LayerA layerA) { + this.context = layerA.getContext(); + } + + public void addSessionInfo(String sessionService) { + context.setSessionService(sessionService); + } +} diff --git a/context-object/src/main/java/com/iluwatar/context/object/LayerC.java b/context-object/src/main/java/com/iluwatar/context/object/LayerC.java new file mode 100644 index 000000000000..d33a62998030 --- /dev/null +++ b/context-object/src/main/java/com/iluwatar/context/object/LayerC.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.context.object; + +import lombok.Getter; + +/** Layer C in the context object pattern. */ +@Getter +public class LayerC { + + public ServiceContext context; + + public LayerC(LayerB layerB) { + this.context = layerB.getContext(); + } + + public void addSearchInfo(String searchService) { + context.setSearchService(searchService); + } +} diff --git a/context-object/src/main/java/com/iluwatar/context/object/ServiceContext.java b/context-object/src/main/java/com/iluwatar/context/object/ServiceContext.java new file mode 100644 index 000000000000..3de91a20e672 --- /dev/null +++ b/context-object/src/main/java/com/iluwatar/context/object/ServiceContext.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.context.object; + +import lombok.Getter; +import lombok.Setter; + +/** Where context objects are defined. */ +@Getter +@Setter +public class ServiceContext { + + String accountService; + String sessionService; + String searchService; +} diff --git a/context-object/src/main/java/com/iluwatar/context/object/ServiceContextFactory.java b/context-object/src/main/java/com/iluwatar/context/object/ServiceContextFactory.java new file mode 100644 index 000000000000..bee65e828914 --- /dev/null +++ b/context-object/src/main/java/com/iluwatar/context/object/ServiceContextFactory.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.context.object; + +/** An interface to create context objects passed through layers. */ +public class ServiceContextFactory { + + public static ServiceContext createContext() { + return new ServiceContext(); + } +} diff --git a/context-object/src/test/java/com/iluwatar/contect/object/AppTest.java b/context-object/src/test/java/com/iluwatar/contect/object/AppTest.java new file mode 100644 index 000000000000..2cb5e901a80e --- /dev/null +++ b/context-object/src/test/java/com/iluwatar/contect/object/AppTest.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.contect.object; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import com.iluwatar.context.object.App; +import org.junit.jupiter.api.Test; + +public class AppTest { + + /** Test example app runs without error. */ + @Test + void shouldExecuteWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/context-object/src/test/java/com/iluwatar/contect/object/ServiceContextTest.java b/context-object/src/test/java/com/iluwatar/contect/object/ServiceContextTest.java new file mode 100644 index 000000000000..fdfd56af7948 --- /dev/null +++ b/context-object/src/test/java/com/iluwatar/contect/object/ServiceContextTest.java @@ -0,0 +1,101 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.contect.object; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +import com.iluwatar.context.object.LayerA; +import com.iluwatar.context.object.LayerB; +import com.iluwatar.context.object.LayerC; +import com.iluwatar.context.object.ServiceContext; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** ServiceContextTest */ +public class ServiceContextTest { + + private static final String SERVICE = "SERVICE"; + + private LayerA layerA; + + @BeforeEach + void initiateLayerA() { + this.layerA = new LayerA(); + } + + @Test + void testSameContextPassedBetweenLayers() { + ServiceContext context1 = layerA.getContext(); + var layerB = new LayerB(layerA); + ServiceContext context2 = layerB.getContext(); + var layerC = new LayerC(layerB); + ServiceContext context3 = layerC.getContext(); + + assertSame(context1, context2); + assertSame(context2, context3); + assertSame(context3, context1); + } + + @Test + void testScopedDataPassedBetweenLayers() { + layerA.addAccountInfo(SERVICE); + var layerB = new LayerB(layerA); + var layerC = new LayerC(layerB); + layerC.addSearchInfo(SERVICE); + ServiceContext context = layerC.getContext(); + + assertEquals(SERVICE, context.getAccountService()); + assertNull(context.getSessionService()); + assertEquals(SERVICE, context.getSearchService()); + } + + @Test + void testLayerContexts() { + assertAll( + () -> assertNull(layerA.getContext().getAccountService()), + () -> assertNull(layerA.getContext().getSearchService()), + () -> assertNull(layerA.getContext().getSessionService())); + layerA.addAccountInfo(SERVICE); + assertAll( + () -> assertEquals(SERVICE, layerA.getContext().getAccountService()), + () -> assertNull(layerA.getContext().getSearchService()), + () -> assertNull(layerA.getContext().getSessionService())); + var layerB = new LayerB(layerA); + layerB.addSessionInfo(SERVICE); + assertAll( + () -> assertEquals(SERVICE, layerB.getContext().getAccountService()), + () -> assertEquals(SERVICE, layerB.getContext().getSessionService()), + () -> assertNull(layerB.getContext().getSearchService())); + var layerC = new LayerC(layerB); + layerC.addSearchInfo(SERVICE); + assertAll( + () -> assertEquals(SERVICE, layerC.getContext().getAccountService()), + () -> assertEquals(SERVICE, layerC.getContext().getSearchService()), + () -> assertEquals(SERVICE, layerC.getContext().getSessionService())); + } +} diff --git a/converter/README.md b/converter/README.md index 79b539422892..7fbb1fe9e559 100644 --- a/converter/README.md +++ b/converter/README.md @@ -1,29 +1,174 @@ --- -layout: pattern -title: Converter -folder: converter -permalink: /patterns/converter/ -categories: Business Tier -tags: - - Java - - Difficulty-Beginner +title: "Converter Pattern in Java: Streamlining Data Conversion Across Layers" +shortTitle: Converter +description: "Discover the benefits and implementation of the Converter Pattern in Java. Learn how to achieve seamless bidirectional conversion between different data formats, promoting clean code and flexibility in your applications." +category: Structural +language: en +tag: + - Compatibility + - Data transformation + - Decoupling + - Interface + - Object mapping + - Wrapping --- -## Intent -The purpose of the Converter Pattern is to provide a generic, common way of bidirectional -conversion between corresponding types, allowing a clean implementation in which the types do not -need to be aware of each other. Moreover, the Converter Pattern introduces bidirectional collection -mapping, reducing a boilerplate code to minimum. +## Also known as -![alt text](./etc/converter.png "Converter Pattern") +* Mapper +* Translator + +## Intent of Converter Design Pattern + +The purpose of the Converter Pattern is to provide a generic, systematic way of bidirectional conversion between corresponding data types. This allows for a clean, decoupled implementation where types are unaware of each other. Additionally, the Converter pattern supports bidirectional collection mapping, minimizing boilerplate code. + +## Detailed Explanation of Converter Pattern with Real-World Examples + +Real-world example + +> In a real-world scenario, consider a library system that interacts with a third-party book database. The library uses an internal book format, while the third-party database uses a different format. By employing the Converter Pattern, a converter class can transform the third-party book data into the library's format and vice versa. This ensures seamless integration without altering the internal structures of either system. + +In plain words + +> The Converter Pattern simplifies mapping instances of one class to instances of another class, ensuring consistent and clean data transformation. + +Sequence diagram + +![Converter sequence diagram](./etc/converter-sequence-diagram.png) + +## Programmatic Example of Converter Pattern in Java + +In applications, it's common for the database layer to have entities that need mapping to DTOs (Data Transfer Objects) for business logic. This mapping often involves many classes, necessitating a generic solution. + +We introduce a generic `Converter` class: + +```java +public class Converter { + + private final Function fromDto; + private final Function fromEntity; + + public Converter(final Function fromDto, final Function fromEntity) { + this.fromDto = fromDto; + this.fromEntity = fromEntity; + } + + public final U convertFromDto(final T dto) { + return fromDto.apply(dto); + } + + public final T convertFromEntity(final U entity) { + return fromEntity.apply(entity); + } + + public final List createFromDtos(final Collection dtos) { + return dtos.stream().map(this::convertFromDto).collect(Collectors.toList()); + } + + public final List createFromEntities(final Collection entities) { + return entities.stream().map(this::convertFromEntity).collect(Collectors.toList()); + } +} +``` + +Specialized converters inherit from this base class: + +```java +public class UserConverter extends Converter { + + public UserConverter() { + super(UserConverter::convertToEntity, UserConverter::convertToDto); + } + + private static UserDto convertToDto(User user) { + return new UserDto(user.firstName(), user.lastName(), user.active(), user.userId()); + } + + private static User convertToEntity(UserDto dto) { + return new User(dto.firstName(), dto.lastName(), dto.active(), dto.email()); + } +} +``` + +Mapping between `User` and `UserDto` becomes straightforward: + +```java + public static void main(String[] args) { + Converter userConverter = new UserConverter(); + + UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); + User user = userConverter.convertFromDto(dtoUser); + LOGGER.info("Entity converted from DTO: {}", user); + + var users = List.of( + new User("Camile", "Tough", false, "124sad"), + new User("Marti", "Luther", true, "42309fd"), + new User("Kate", "Smith", true, "if0243") + ); + LOGGER.info("Domain entities:"); + users.stream().map(User::toString).forEach(LOGGER::info); + + LOGGER.info("DTO entities converted from domain:"); + List dtoEntities = userConverter.createFromEntities(users); + dtoEntities.stream().map(UserDto::toString).forEach(LOGGER::info); +} +``` + +Program output: + +``` +08:28:27.019 [main] INFO com.iluwatar.converter.App -- Entity converted from DTO: User[firstName=John, lastName=Doe, active=true, userId=whatever[at]wherever.com] +08:28:27.035 [main] INFO com.iluwatar.converter.App -- Domain entities: +08:28:27.035 [main] INFO com.iluwatar.converter.App -- User[firstName=Camile, lastName=Tough, active=false, userId=124sad] +08:28:27.035 [main] INFO com.iluwatar.converter.App -- User[firstName=Marti, lastName=Luther, active=true, userId=42309fd] +08:28:27.035 [main] INFO com.iluwatar.converter.App -- User[firstName=Kate, lastName=Smith, active=true, userId=if0243] +08:28:27.036 [main] INFO com.iluwatar.converter.App -- DTO entities converted from domain: +08:28:27.037 [main] INFO com.iluwatar.converter.App -- UserDto[firstName=Camile, lastName=Tough, active=false, email=124sad] +08:28:27.037 [main] INFO com.iluwatar.converter.App -- UserDto[firstName=Marti, lastName=Luther, active=true, email=42309fd] +08:28:27.037 [main] INFO com.iluwatar.converter.App -- UserDto[firstName=Kate, lastName=Smith, active=true, email=if0243] +``` + +## When to Use the Converter Pattern in Java -## Applicability Use the Converter Pattern in the following situations: -* When you have types that logically correspond which other and you need to convert entities between them -* When you want to provide different ways of types conversions depending on a context -* Whenever you introduce a DTO (Data transfer object), you will probably need to convert it into the domain equivalence +* When there are types that logically correspond with each other, and there is a need to convert between them. +* In applications that interact with external systems or services that require data in a specific format. +* For legacy systems integration where data models differ significantly from newer systems. +* When aiming to encapsulate conversion logic to promote single responsibility and cleaner code. + +## Converter Pattern Java Tutorials + +* [Converter Pattern in Java 8 (Boldare)](http://www.xsolve.pl/blog/converter-pattern-in-java-8/) + +## Real-World Applications of Converter Pattern in Java + +* Data Transfer Objects (DTOs) conversions in multi-layered applications. +* Adapting third-party data structures or API responses to internal models. +* ORM (Object-Relational Mapping) frameworks for mapping between database records and domain objects. +* Microservices architecture for data exchange between different services. + +## Benefits and Trade-offs of Converter Pattern + +Benefits: + +* Separation of Concerns: Encapsulates conversion logic in a single component, keeping the rest of the application unaware of the conversion details. +* Reusability: Converter components can be reused across the application or even in different applications. +* Flexibility: Makes it easy to add new conversions without impacting existing code, adhering to the [Open/Closed Principle](https://java-design-patterns.com/principles/#open-closed-principle). +* Interoperability: Facilitates communication between different systems or application layers by translating data formats. + +Trade-offs: + +* Overhead: Introducing converters can add complexity and potential performance overhead, especially in systems with numerous data formats. +* Duplication: There's a risk of duplicating model definitions if not carefully managed, leading to increased maintenance. + +## Related Java Design Patterns + +* [Adapter](https://java-design-patterns.com/patterns/adapter/): Similar in intent to adapting interfaces, but Converter focuses on data models. +* [Facade](https://java-design-patterns.com/patterns/facade/): Provides a simplified interface to a complex system, which might involve data conversion. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Converters can use different strategies for conversion, especially when multiple formats are involved. -## Credits +## References and Credits -* [Converter](http://www.xsolve.pl/blog/converter-pattern-in-java-8/) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/converter/etc/converter-sequence-diagram.png b/converter/etc/converter-sequence-diagram.png new file mode 100644 index 000000000000..65192915c2af Binary files /dev/null and b/converter/etc/converter-sequence-diagram.png differ diff --git a/converter/etc/Converter.png b/converter/etc/converter.png similarity index 100% rename from converter/etc/Converter.png rename to converter/etc/converter.png diff --git a/converter/etc/converter.urm.puml b/converter/etc/converter.urm.puml new file mode 100644 index 000000000000..275af84e6bc8 --- /dev/null +++ b/converter/etc/converter.urm.puml @@ -0,0 +1,50 @@ +@startuml +package com.iluwatar.converter { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Converter { + - fromDto : Function + - fromEntity : Function + + Converter(fromDto : Function, fromEntity : Function) + + convertFromDto(dto : T) : U + + convertFromEntity(entity : U) : T + + createFromDtos(dtos : Collection) : List + + createFromEntities(entities : Collection) : List + } + class User { + - firstName : String + - isActive : boolean + - lastName : String + - userId : String + + User(firstName : String, lastName : String, isActive : boolean, userId : String) + + equals(o : Object) : boolean + + getFirstName() : String + + getLastName() : String + + getUserId() : String + + hashCode() : int + + isActive() : boolean + + toString() : String + } + class UserConverter { + + UserConverter() + } + class UserDto { + - email : String + - firstName : String + - isActive : boolean + - lastName : String + + UserDto(firstName : String, lastName : String, isActive : boolean, email : String) + + equals(o : Object) : boolean + + getEmail() : String + + getFirstName() : String + + getLastName() : String + + hashCode() : int + + isActive() : boolean + + toString() : String + } +} +UserConverter --|> Converter +@enduml \ No newline at end of file diff --git a/converter/pom.xml b/converter/pom.xml index f696048f53c8..525237ed17f5 100644 --- a/converter/pom.xml +++ b/converter/pom.xml @@ -1,8 +1,10 @@ - - - java-design-patterns - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - com.google.guava - guava - - - converter - - + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + converter + 4.0.0 + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.converter.App + + + + + + + + diff --git a/converter/src/main/java/com/iluwatar/converter/App.java b/converter/src/main/java/com/iluwatar/converter/App.java index 6e436706d94f..100913501018 100644 --- a/converter/src/main/java/com/iluwatar/converter/App.java +++ b/converter/src/main/java/com/iluwatar/converter/App.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,11 +24,8 @@ */ package com.iluwatar.converter; - -import com.google.common.collect.Lists; - -import java.util.ArrayList; import java.util.List; +import lombok.extern.slf4j.Slf4j; /** * The Converter pattern is a behavioral design pattern which allows a common way of bidirectional @@ -34,9 +33,11 @@ * isomorphic types). Moreover, the pattern introduces a common way of converting a collection of * objects between types. */ +@Slf4j public class App { + /** - * Program entry point + * Program entry point. * * @param args command line args */ @@ -45,16 +46,18 @@ public static void main(String[] args) { UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); User user = userConverter.convertFromDto(dtoUser); - System.out.println("Entity converted from DTO:" + user); + LOGGER.info("Entity converted from DTO: {}", user); - ArrayList users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"), - new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); - System.out.println("Domain entities:"); - users.forEach(System.out::println); + var users = + List.of( + new User("Camile", "Tough", false, "124sad"), + new User("Marti", "Luther", true, "42309fd"), + new User("Kate", "Smith", true, "if0243")); + LOGGER.info("Domain entities:"); + users.stream().map(User::toString).forEach(LOGGER::info); - System.out.println("DTO entities converted from domain:"); + LOGGER.info("DTO entities converted from domain:"); List dtoEntities = userConverter.createFromEntities(users); - dtoEntities.forEach(System.out::println); - + dtoEntities.stream().map(UserDto::toString).forEach(LOGGER::info); } } diff --git a/converter/src/main/java/com/iluwatar/converter/Converter.java b/converter/src/main/java/com/iluwatar/converter/Converter.java index 4a2bb7381ede..374b2ce5da7e 100644 --- a/converter/src/main/java/com/iluwatar/converter/Converter.java +++ b/converter/src/main/java/com/iluwatar/converter/Converter.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,67 +22,68 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.converter; import java.util.Collection; import java.util.List; import java.util.function.Function; -import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; /** * Generic converter, thanks to Java8 features not only provides a way of generic bidirectional - * conversion between coresponding types, but also a common way of converting a collection of objects - * of the same type, reducing boilerplate code to the absolute minimum. + * conversion between corresponding types, but also a common way of converting a collection of + * objects of the same type, reducing boilerplate code to the absolute minimum. + * * @param DTO representation's type * @param Domain representation's type */ +@RequiredArgsConstructor public class Converter { private final Function fromDto; private final Function fromEntity; /** - * @param fromDto Function that converts given dto entity into the domain entity. - * @param fromEntity Function that converts given domain entity into the dto entity. - */ - public Converter(final Function fromDto, final Function fromEntity) { - this.fromDto = fromDto; - this.fromEntity = fromEntity; - } - - /** + * Converts DTO to Entity. + * * @param dto DTO entity - * @return The domain representation - the result of the converting function application on dto entity. + * @return The domain representation - the result of the converting function application on dto + * entity. */ public final U convertFromDto(final T dto) { return fromDto.apply(dto); } /** + * Converts Entity to DTO. + * * @param entity domain entity - * @return The DTO representation - the result of the converting function application on domain entity. + * @return The DTO representation - the result of the converting function application on domain + * entity. */ public final T convertFromEntity(final U entity) { return fromEntity.apply(entity); } /** + * Converts list of DTOs to list of Entities. + * * @param dtos collection of DTO entities - * @return List of domain representation of provided entities retrieved by - * mapping each of them with the conversion function + * @return List of domain representation of provided entities retrieved by mapping each of them + * with the conversion function */ public final List createFromDtos(final Collection dtos) { - return dtos.stream().map(this::convertFromDto).collect(Collectors.toList()); + return dtos.stream().map(this::convertFromDto).toList(); } /** + * Converts list of Entities to list of DTOs. + * * @param entities collection of domain entities - * @return List of domain representation of provided entities retrieved by - * mapping each of them with the conversion function + * @return List of domain representation of provided entities retrieved by mapping each of them + * with the conversion function */ public final List createFromEntities(final Collection entities) { - return entities.stream().map(this::convertFromEntity).collect(Collectors.toList()); + return entities.stream().map(this::convertFromEntity).toList(); } - } diff --git a/converter/src/main/java/com/iluwatar/converter/User.java b/converter/src/main/java/com/iluwatar/converter/User.java index 62903a9313cd..9f68047f1dcc 100644 --- a/converter/src/main/java/com/iluwatar/converter/User.java +++ b/converter/src/main/java/com/iluwatar/converter/User.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,67 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.converter; -import java.util.Objects; - -/** - * User class - */ -public class User { - private String firstName; - private String lastName; - private boolean isActive; - private String userId; - - /** - * @param firstName user's first name - * @param lastName user's last name - * @param isActive flag indicating whether the user is active - * @param userId user's identificator - */ - public User(String firstName, String lastName, boolean isActive, String userId) { - this.firstName = firstName; - this.lastName = lastName; - this.isActive = isActive; - this.userId = userId; - } - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - - public boolean isActive() { - return isActive; - } - - public String getUserId() { - return userId; - } - - @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - User user = (User) o; - return isActive == user.isActive && Objects.equals(firstName, user.firstName) && Objects - .equals(lastName, user.lastName) && Objects.equals(userId, user.userId); - } - - @Override public int hashCode() { - return Objects.hash(firstName, lastName, isActive, userId); - } - - @Override public String toString() { - return "User{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' - + ", isActive=" + isActive + ", userId='" + userId + '\'' + '}'; - } -} +/** User record. */ +public record User(String firstName, String lastName, boolean active, String userId) {} diff --git a/converter/src/main/java/com/iluwatar/converter/UserConverter.java b/converter/src/main/java/com/iluwatar/converter/UserConverter.java index 9ef1d03c24de..f7dbd3138047 100644 --- a/converter/src/main/java/com/iluwatar/converter/UserConverter.java +++ b/converter/src/main/java/com/iluwatar/converter/UserConverter.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,21 +22,20 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.converter; -/** - * Example implementation of the simple User converter. - */ +/** Example implementation of the simple User converter. */ public class UserConverter extends Converter { - /** - * Constructor. - */ public UserConverter() { - super(userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), - userDto.getEmail()), - user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), - user.getUserId())); + super(UserConverter::convertToEntity, UserConverter::convertToDto); + } + + private static UserDto convertToDto(User user) { + return new UserDto(user.firstName(), user.lastName(), user.active(), user.userId()); + } + + private static User convertToEntity(UserDto dto) { + return new User(dto.firstName(), dto.lastName(), dto.active(), dto.email()); } } diff --git a/converter/src/main/java/com/iluwatar/converter/UserDto.java b/converter/src/main/java/com/iluwatar/converter/UserDto.java index 8eacc0b3be96..dc1d861dd971 100644 --- a/converter/src/main/java/com/iluwatar/converter/UserDto.java +++ b/converter/src/main/java/com/iluwatar/converter/UserDto.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,69 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.converter; - -import java.util.Objects; - -/** - * User DTO class - */ -public class UserDto { - - private String firstName; - private String lastName; - private boolean isActive; - private String email; - - /** - * @param firstName user's first name - * @param lastName user's last name - * @param isActive flag indicating whether the user is active - * @param email user's email address - */ - public UserDto(String firstName, String lastName, boolean isActive, String email) { - this.firstName = firstName; - this.lastName = lastName; - this.isActive = isActive; - this.email = email; - } - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - - public boolean isActive() { - return isActive; - } - - public String getEmail() { - return email; - } - - @Override public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - UserDto userDto = (UserDto) o; - return isActive == userDto.isActive && Objects.equals(firstName, userDto.firstName) && Objects - .equals(lastName, userDto.lastName) && Objects.equals(email, userDto.email); - } - - @Override public int hashCode() { - return Objects.hash(firstName, lastName, isActive, email); - } - - @Override public String toString() { - return "UserDto{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' - + ", isActive=" + isActive + ", email='" + email + '\'' + '}'; - } -} +/** UserDto record. */ +public record UserDto(String firstName, String lastName, boolean active, String email) {} diff --git a/converter/src/test/java/com/iluwatar/converter/AppTest.java b/converter/src/test/java/com/iluwatar/converter/AppTest.java index 1617beeb40ea..366adef7b8a7 100644 --- a/converter/src/test/java/com/iluwatar/converter/AppTest.java +++ b/converter/src/test/java/com/iluwatar/converter/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,20 @@ */ package com.iluwatar.converter; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * App running test - */ -public class AppTest { +/** App running test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ @Test - public void testMain() { - String[] args = {}; - App.main(args); - } + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } } diff --git a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java index f5c41256d8b3..da14e3e5a67c 100644 --- a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java +++ b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,67 +24,72 @@ */ package com.iluwatar.converter; -import com.google.common.collect.Lists; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.ArrayList; import java.util.List; import java.util.Random; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; +/** Tests for {@link Converter} */ +class ConverterTest { -/** - * Tests for {@link Converter} - */ -public class ConverterTest { + private final UserConverter userConverter = new UserConverter(); - private UserConverter userConverter = new UserConverter(); - - /** - * Tests whether a converter created of opposite functions holds equality as a bijection. - */ + /** Tests whether a converter created of opposite functions holds equality as a bijection. */ @Test - public void testConversionsStartingFromDomain() { - User u1 = new User("Tom", "Hanks", true, "tom@hanks.com"); - User u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1)); + void testConversionsStartingFromDomain() { + var u1 = new User("Tom", "Hanks", true, "tom@hanks.com"); + var u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1)); assertEquals(u1, u2); } - /** - * Tests whether a converter created of opposite functions holds equality as a bijection. - */ + /** Tests whether a converter created of opposite functions holds equality as a bijection. */ @Test - public void testConversionsStartingFromDto() { - UserDto u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com"); - UserDto u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1)); + void testConversionsStartingFromDto() { + var u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com"); + var u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1)); assertEquals(u1, u2); } /** - * Tests the custom users converter. Thanks to Java8 lambdas, converter can be easily and - * cleanly instantiated allowing various different conversion strategies to be implemented. + * Tests the custom users converter. Thanks to Java8 lambdas, converter can be easily and cleanly + * instantiated allowing various different conversion strategies to be implemented. */ @Test - public void testCustomConverter() { - Converter converter = new Converter<>( - userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), - String.valueOf(new Random().nextInt())), - user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), - user.getFirstName().toLowerCase() + user.getLastName().toLowerCase() + "@whatever.com")); - User u1 = new User("John", "Doe", false, "12324"); - UserDto userDto = converter.convertFromEntity(u1); - assertEquals(userDto.getEmail(), "johndoe@whatever.com"); + void testCustomConverter() { + var converter = + new Converter( + userDto -> + new User( + userDto.firstName(), + userDto.lastName(), + userDto.active(), + String.valueOf(new Random().nextInt())), + user -> + new UserDto( + user.firstName(), + user.lastName(), + user.active(), + user.firstName().toLowerCase() + + user.lastName().toLowerCase() + + "@whatever.com")); + var u1 = new User("John", "Doe", false, "12324"); + var userDto = converter.convertFromEntity(u1); + assertEquals("johndoe@whatever.com", userDto.email()); } /** - * Test whether converting a collection of Users to DTO Users and then converting them back to domain - * users returns an equal collection. + * Test whether converting a collection of Users to DTO Users and then converting them back to + * domain users returns an equal collection. */ @Test - public void testCollectionConversion() { - ArrayList users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"), - new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); - List fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users)); - assertEquals(fromDtos, users); + void testCollectionConversion() { + var users = + List.of( + new User("Camile", "Tough", false, "124sad"), + new User("Marti", "Luther", true, "42309fd"), + new User("Kate", "Smith", true, "if0243")); + var fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users)); + assertEquals(users, fromDtos); } } diff --git a/cqrs/README.md b/cqrs/README.md deleted file mode 100644 index 111c1ccd45ec..000000000000 --- a/cqrs/README.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -layout: pattern -title: CQRS -folder: cqrs -permalink: /patterns/cqrs/ -categories: Architectural -tags: - - Java - - Difficulty-Intermediate ---- - -## Intent -CQRS Command Query Responsibility Segregation - Separate the query side from the command side. - -![alt text](./etc/cqrs.png "CQRS") - -## Applicability -Use the CQRS pattern when - -* you want to scale the queries and commands independently. -* you want to use different data models for queries and commands. Useful when dealing with complex domains. -* you want to use architectures like event sourcing or task based UI. - -## Credits - -* [Greg Young - CQRS, Task Based UIs, Event Sourcing agh!](http://codebetter.com/gregyoung/2010/02/16/cqrs-task-based-uis-event-sourcing-agh/) -* [Martin Fowler - CQRS](https://martinfowler.com/bliki/CQRS.html) -* [Oliver Wolf - CQRS for Great Good](https://www.youtube.com/watch?v=Ge53swja9Dw) diff --git a/cqrs/pom.xml b/cqrs/pom.xml deleted file mode 100644 index 7ed2e1208277..000000000000 --- a/cqrs/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - cqrs - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - com.h2database - h2 - - - org.hibernate - hibernate-core - - - diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java b/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java deleted file mode 100644 index a943a7f88891..000000000000 --- a/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java +++ /dev/null @@ -1,95 +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.cqrs.app; - -import java.math.BigInteger; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.iluwatar.cqrs.commandes.CommandServiceImpl; -import com.iluwatar.cqrs.commandes.ICommandService; -import com.iluwatar.cqrs.dto.Author; -import com.iluwatar.cqrs.dto.Book; -import com.iluwatar.cqrs.queries.IQueryService; -import com.iluwatar.cqrs.queries.QueryServiceImpl; -import com.iluwatar.cqrs.util.HibernateUtil; - -/** - * CQRS : Command Query Responsibility Segregation. A pattern used to separate query services from commands or writes - * services. The pattern is very simple but it has many consequences. For example, it can be used to tackle down a - * complex domain, or to use other architectures that were hard to implement with the classical way. - * - * This implementation is an example of managing books and authors in a library. The persistence of books and authors is - * done according to the CQRS architecture. A command side that deals with a data model to persist(insert,update,delete) - * objects to a database. And a query side that uses native queries to get data from the database and return objects as - * DTOs (Data transfer Objects). - * - */ -public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * Program entry point - * - * @param args - * command line args - */ - public static void main(String[] args) { - ICommandService commands = new CommandServiceImpl(); - - // Create Authors and Books using CommandService - commands.authorCreated("eEvans", "Eric Evans", "eEvans@email.com"); - commands.authorCreated("jBloch", "Joshua Bloch", "jBloch@email.com"); - commands.authorCreated("mFowler", "Martin Fowler", "mFowler@email.com"); - - commands.bookAddedToAuthor("Domain-Driven Design", 60.08, "eEvans"); - commands.bookAddedToAuthor("Effective Java", 40.54, "jBloch"); - commands.bookAddedToAuthor("Java Puzzlers", 39.99, "jBloch"); - commands.bookAddedToAuthor("Java Concurrency in Practice", 29.40, "jBloch"); - commands.bookAddedToAuthor("Patterns of Enterprise Application Architecture", 54.01, "mFowler"); - commands.bookAddedToAuthor("Domain Specific Languages", 48.89, "mFowler"); - commands.authorNameUpdated("eEvans", "Eric J. Evans"); - - IQueryService queries = new QueryServiceImpl(); - - // Query the database using QueryService - Author nullAuthor = queries.getAuthorByUsername("username"); - Author eEvans = queries.getAuthorByUsername("eEvans"); - BigInteger jBlochBooksCount = queries.getAuthorBooksCount("jBloch"); - BigInteger authorsCount = queries.getAuthorsCount(); - Book dddBook = queries.getBook("Domain-Driven Design"); - List jBlochBooks = queries.getAuthorBooks("jBloch"); - - LOGGER.info("Author username : {}", nullAuthor); - LOGGER.info("Author eEvans : {}", eEvans); - LOGGER.info("jBloch number of books : {}", jBlochBooksCount); - LOGGER.info("Number of authors : {}", authorsCount); - LOGGER.info("DDD book : {}", dddBook); - LOGGER.info("jBloch books : {}", jBlochBooks); - - HibernateUtil.getSessionFactory().close(); - } - -} diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java deleted file mode 100644 index a15f8a45716d..000000000000 --- a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java +++ /dev/null @@ -1,145 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.cqrs.commandes; - -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; - -import com.iluwatar.cqrs.domain.model.Author; -import com.iluwatar.cqrs.domain.model.Book; -import com.iluwatar.cqrs.util.HibernateUtil; - -/** - * This class is an implementation of {@link ICommandService} interface. It uses Hibernate as an api for persistence. - * - */ -public class CommandServiceImpl implements ICommandService { - - private SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); - - private Author getAuthorByUsername(String username) { - Author author = null; - try (Session session = sessionFactory.openSession()) { - Query query = session.createQuery("from Author where username=:username"); - query.setParameter("username", username); - author = (Author) query.uniqueResult(); - } - if (author == null) { - HibernateUtil.getSessionFactory().close(); - throw new NullPointerException("Author " + username + " doesn't exist!"); - } - return author; - } - - private Book getBookByTitle(String title) { - Book book = null; - try (Session session = sessionFactory.openSession()) { - Query query = session.createQuery("from Book where title=:title"); - query.setParameter("title", title); - book = (Book) query.uniqueResult(); - } - if (book == null) { - HibernateUtil.getSessionFactory().close(); - throw new NullPointerException("Book " + title + " doesn't exist!"); - } - return book; - } - - @Override - public void authorCreated(String username, String name, String email) { - Author author = new Author(username, name, email); - try (Session session = sessionFactory.openSession()) { - session.beginTransaction(); - session.save(author); - session.getTransaction().commit(); - } - } - - @Override - public void bookAddedToAuthor(String title, double price, String username) { - Author author = getAuthorByUsername(username); - Book book = new Book(title, price, author); - try (Session session = sessionFactory.openSession()) { - session.beginTransaction(); - session.save(book); - session.getTransaction().commit(); - } - } - - @Override - public void authorNameUpdated(String username, String name) { - Author author = getAuthorByUsername(username); - author.setName(name); - try (Session session = sessionFactory.openSession()) { - session.beginTransaction(); - session.update(author); - session.getTransaction().commit(); - } - } - - @Override - public void authorUsernameUpdated(String oldUsername, String newUsername) { - Author author = getAuthorByUsername(oldUsername); - author.setUsername(newUsername); - try (Session session = sessionFactory.openSession()) { - session.beginTransaction(); - session.update(author); - session.getTransaction().commit(); - } - } - - @Override - public void authorEmailUpdated(String username, String email) { - Author author = getAuthorByUsername(username); - author.setEmail(email); - try (Session session = sessionFactory.openSession()) { - session.beginTransaction(); - session.update(author); - session.getTransaction().commit(); - } - } - - @Override - public void bookTitleUpdated(String oldTitle, String newTitle) { - Book book = getBookByTitle(oldTitle); - book.setTitle(newTitle); - try (Session session = sessionFactory.openSession()) { - session.beginTransaction(); - session.update(book); - session.getTransaction().commit(); - } - } - - @Override - public void bookPriceUpdated(String title, double price) { - Book book = getBookByTitle(title); - book.setPrice(price); - try (Session session = sessionFactory.openSession()) { - session.beginTransaction(); - session.update(book); - session.getTransaction().commit(); - } - } - -} diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java deleted file mode 100644 index 1da3f6c42392..000000000000 --- a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.cqrs.commandes; - -/** - * This interface represents the commands of the CQRS pattern - * - */ -public interface ICommandService { - - void authorCreated(String username, String name, String email); - - void bookAddedToAuthor(String title, double price, String username); - - void authorNameUpdated(String username, String name); - - void authorUsernameUpdated(String oldUsername, String newUsername); - - void authorEmailUpdated(String username, String email); - - void bookTitleUpdated(String oldTitle, String newTitle); - - void bookPriceUpdated(String title, double price); - -} diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java deleted file mode 100644 index 9825de9f7b25..000000000000 --- a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.cqrs.domain.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -/** - * This is an Author entity. It is used by Hibernate for persistence. - * - */ -@Entity -public class Author { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - private String username; - private String name; - private String email; - - /** - * - * @param username - * username of the author - * @param name - * name of the author - * @param email - * email of the author - */ - public Author(String username, String name, String email) { - this.username = username; - this.name = name; - this.email = email; - } - - protected Author() { - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - @Override - public String toString() { - return "Author [name=" + name + ", email=" + email + "]"; - } - -} diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java b/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java deleted file mode 100644 index 8a11fcdd4166..000000000000 --- a/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.cqrs.domain.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -/** - * This is a Book entity. It is used by Hibernate for persistence. Many books can be written by one {@link Author} - * - */ -@Entity -public class Book { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - private String title; - private double price; - @ManyToOne - private Author author; - - /** - * - * @param title - * title of the book - * @param price - * price of the book - * @param author - * author of the book - */ - public Book(String title, double price, Author author) { - this.title = title; - this.price = price; - this.author = author; - } - - protected Book() { - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public double getPrice() { - return price; - } - - public void setPrice(double price) { - this.price = price; - } - - public Author getAuthor() { - return author; - } - - public void setAuthor(Author author) { - this.author = author; - } - - @Override - public String toString() { - return "Book [title=" + title + ", price=" + price + ", author=" + author + "]"; - } - -} diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java deleted file mode 100644 index c5473354dd59..000000000000 --- a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.cqrs.dto; - -import java.util.Objects; - -/** - * - * This is a DTO (Data Transfer Object) author, contains only useful information to be returned - * - */ -public class Author { - - private String name; - private String email; - private String username; - - /** - * - * @param name - * name of the author - * @param email - * email of the author - * @param username - * username of the author - */ - public Author(String name, String email, String username) { - this.name = name; - this.email = email; - this.username = username; - } - - public Author() { - } - - public String getName() { - return name; - } - - public String getEmail() { - return email; - } - - public String getUsername() { - return username; - } - - @Override - public String toString() { - return "AuthorDTO [name=" + name + ", email=" + email + ", username=" + username + "]"; - } - - @Override - public int hashCode() { - return Objects.hash(username, name, email); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof Author)) { - return false; - } - Author other = (Author) obj; - return username.equals(other.getUsername()) && email.equals(other.getEmail()) && name.equals(other.getName()); - - } - -} diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java b/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java deleted file mode 100644 index f121a2ca7c2c..000000000000 --- a/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.cqrs.dto; - -import java.util.Objects; - -/** - * - * This is a DTO (Data Transfer Object) book, contains only useful information to be returned - * - */ -public class Book { - - private String title; - private double price; - - /** - * - * @param title - * title of the book - * @param price - * price of the book - */ - public Book(String title, double price) { - this.title = title; - this.price = price; - } - - public Book() { - } - - public String getTitle() { - return title; - } - - public double getPrice() { - return price; - } - - @Override - public String toString() { - return "BookDTO [title=" + title + ", price=" + price + "]"; - } - - @Override - public int hashCode() { - return Objects.hash(title, price); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof Book)) { - return false; - } - Book book = (Book) obj; - return title.equals(book.getTitle()) && price == book.getPrice(); - } - -} diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java b/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java deleted file mode 100644 index 9c0252b0aeab..000000000000 --- a/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.cqrs.queries; - -import java.math.BigInteger; -import java.util.List; - -import com.iluwatar.cqrs.dto.Author; -import com.iluwatar.cqrs.dto.Book; - -/** - * - * This interface represents the query methods of the CQRS pattern - * - */ -public interface IQueryService { - - Author getAuthorByUsername(String username); - - Book getBook(String title); - - List getAuthorBooks(String username); - - BigInteger getAuthorBooksCount(String username); - - BigInteger getAuthorsCount(); - -} diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java b/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java deleted file mode 100644 index dc44d0f1b7c8..000000000000 --- a/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.cqrs.queries; - -import java.math.BigInteger; -import java.util.List; - -import org.hibernate.SQLQuery; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.transform.Transformers; - -import com.iluwatar.cqrs.dto.Author; -import com.iluwatar.cqrs.dto.Book; -import com.iluwatar.cqrs.util.HibernateUtil; - -/** - * This class is an implementation of {@link IQueryService}. It uses Hibernate native queries to return DTOs from the - * database. - * - */ -public class QueryServiceImpl implements IQueryService { - - private SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); - - @Override - public Author getAuthorByUsername(String username) { - Author authorDTo = null; - try (Session session = sessionFactory.openSession()) { - SQLQuery sqlQuery = session - .createSQLQuery("SELECT a.username as \"username\", a.name as \"name\", a.email as \"email\"" - + "FROM Author a where a.username=:username"); - sqlQuery.setParameter("username", username); - authorDTo = (Author) sqlQuery.setResultTransformer(Transformers.aliasToBean(Author.class)).uniqueResult(); - } - return authorDTo; - } - - @Override - public Book getBook(String title) { - Book bookDTo = null; - try (Session session = sessionFactory.openSession()) { - SQLQuery sqlQuery = session - .createSQLQuery("SELECT b.title as \"title\", b.price as \"price\"" + " FROM Book b where b.title=:title"); - sqlQuery.setParameter("title", title); - bookDTo = (Book) sqlQuery.setResultTransformer(Transformers.aliasToBean(Book.class)).uniqueResult(); - } - return bookDTo; - } - - @Override - public List getAuthorBooks(String username) { - List bookDTos = null; - try (Session session = sessionFactory.openSession()) { - SQLQuery sqlQuery = session.createSQLQuery("SELECT b.title as \"title\", b.price as \"price\"" - + " FROM Author a , Book b where b.author_id = a.id and a.username=:username"); - sqlQuery.setParameter("username", username); - bookDTos = sqlQuery.setResultTransformer(Transformers.aliasToBean(Book.class)).list(); - } - return bookDTos; - } - - @Override - public BigInteger getAuthorBooksCount(String username) { - BigInteger bookcount = null; - try (Session session = sessionFactory.openSession()) { - SQLQuery sqlQuery = session.createSQLQuery( - "SELECT count(b.title)" + " FROM Book b, Author a where b.author_id = a.id and a.username=:username"); - sqlQuery.setParameter("username", username); - bookcount = (BigInteger) sqlQuery.uniqueResult(); - } - return bookcount; - } - - @Override - public BigInteger getAuthorsCount() { - BigInteger authorcount = null; - try (Session session = sessionFactory.openSession()) { - SQLQuery sqlQuery = session.createSQLQuery("SELECT count(id) from Author"); - authorcount = (BigInteger) sqlQuery.uniqueResult(); - } - return authorcount; - } - -} diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java b/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java deleted file mode 100644 index a5b59e20dc27..000000000000 --- a/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.cqrs.util; - -import org.hibernate.SessionFactory; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class simply returns one instance of {@link SessionFactory} initialized when the application is started - * - */ -public class HibernateUtil { - - private static final SessionFactory SESSIONFACTORY = buildSessionFactory(); - private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); - - private static SessionFactory buildSessionFactory() { - - // configures settings from hibernate.cfg.xml - final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build(); - try { - return new MetadataSources(registry).buildMetadata().buildSessionFactory(); - } catch (Exception ex) { - StandardServiceRegistryBuilder.destroy(registry); - LOGGER.error("Initial SessionFactory creation failed." + ex); - throw new ExceptionInInitializerError(ex); - } - } - - public static SessionFactory getSessionFactory() { - return SESSIONFACTORY; - } - -} diff --git a/cqrs/src/main/resources/hibernate.cfg.xml b/cqrs/src/main/resources/hibernate.cfg.xml deleted file mode 100644 index 4ea1421667e1..000000000000 --- a/cqrs/src/main/resources/hibernate.cfg.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - org.hibernate.dialect.H2Dialect - org.h2.Driver - jdbc:h2:mem:test - sa - create - - - - \ No newline at end of file diff --git a/cqrs/src/main/resources/logback.xml b/cqrs/src/main/resources/logback.xml deleted file mode 100644 index e9694c41c398..000000000000 --- a/cqrs/src/main/resources/logback.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java b/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java deleted file mode 100644 index 536418cbe8e3..000000000000 --- a/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.cqrs; - -import java.math.BigInteger; -import java.util.List; - -import com.iluwatar.cqrs.commandes.CommandServiceImpl; -import com.iluwatar.cqrs.commandes.ICommandService; -import com.iluwatar.cqrs.dto.Author; -import com.iluwatar.cqrs.dto.Book; -import com.iluwatar.cqrs.queries.IQueryService; -import com.iluwatar.cqrs.queries.QueryServiceImpl; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Integration test of IQueryService and ICommandService with h2 data - * - */ -public class IntegrationTest { - - private static IQueryService queryService; - private static ICommandService commandService; - - @BeforeAll - public static void initializeAndPopulateDatabase() { - commandService = new CommandServiceImpl(); - queryService = new QueryServiceImpl(); - - // create first author1 - commandService.authorCreated("username1", "name1", "email1"); - - // create author1 and update all its data - commandService.authorCreated("username2", "name2", "email2"); - commandService.authorEmailUpdated("username2", "new_email2"); - commandService.authorNameUpdated("username2", "new_name2"); - commandService.authorUsernameUpdated("username2", "new_username2"); - - // add book1 to author1 - commandService.bookAddedToAuthor("title1", 10, "username1"); - - // add book2 to author1 and update all its data - commandService.bookAddedToAuthor("title2", 20, "username1"); - commandService.bookPriceUpdated("title2", 30); - commandService.bookTitleUpdated("title2", "new_title2"); - - } - - @Test - public void testGetAuthorByUsername() { - Author author = queryService.getAuthorByUsername("username1"); - assertEquals("username1", author.getUsername()); - assertEquals("name1", author.getName()); - assertEquals("email1", author.getEmail()); - } - - @Test - public void testGetUpdatedAuthorByUsername() { - Author author = queryService.getAuthorByUsername("new_username2"); - Author expectedAuthor = new Author("new_name2", "new_email2", "new_username2"); - assertEquals(expectedAuthor, author); - - } - - @Test - public void testGetBook() { - Book book = queryService.getBook("title1"); - assertEquals("title1", book.getTitle()); - assertEquals(10, book.getPrice(), 0.01); - } - - @Test - public void testGetAuthorBooks() { - List books = queryService.getAuthorBooks("username1"); - assertTrue(books.size() == 2); - assertTrue(books.contains(new Book("title1", 10))); - assertTrue(books.contains(new Book("new_title2", 30))); - } - - @Test - public void testGetAuthorBooksCount() { - BigInteger bookCount = queryService.getAuthorBooksCount("username1"); - assertEquals(new BigInteger("2"), bookCount); - } - - @Test - public void testGetAuthorsCount() { - BigInteger authorCount = queryService.getAuthorsCount(); - assertEquals(new BigInteger("2"), authorCount); - } - -} diff --git a/cqrs/src/test/resources/hibernate.cfg.xml b/cqrs/src/test/resources/hibernate.cfg.xml deleted file mode 100644 index 4ea1421667e1..000000000000 --- a/cqrs/src/test/resources/hibernate.cfg.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - org.hibernate.dialect.H2Dialect - org.h2.Driver - jdbc:h2:mem:test - sa - create - - - - \ No newline at end of file diff --git a/cqrs/src/test/resources/logback.xml b/cqrs/src/test/resources/logback.xml deleted file mode 100644 index e9694c41c398..000000000000 --- a/cqrs/src/test/resources/logback.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/curiously-recurring-template-pattern/README.md b/curiously-recurring-template-pattern/README.md new file mode 100644 index 000000000000..e44bd7d53097 --- /dev/null +++ b/curiously-recurring-template-pattern/README.md @@ -0,0 +1,162 @@ +--- +title: "Curiously Recurring Template Pattern in Java: Leveraging Polymorphism Uniquely" +shortTitle: Curiously Recurring Template Pattern (CRTP) +description: "Discover the Curiously Recurring Template Pattern (CRTP) in Java. Learn how to achieve static polymorphism for efficient method overriding and compile-time polymorphic behavior. Perfect for performance-critical applications." +language: en +category: Structural +tag: + - Code simplification + - Extensibility + - Generic + - Idiom + - Instantiation + - Polymorphism + - Recursion +--- + +## Also known as + +* CRTP +* Mixin Inheritance +* Recursive Type Bound +* Recursive Generic +* Static Polymorphism + +## Intent of Curiously Recurring Template Pattern + +The Curiously Recurring Template Pattern (CRTP) is a powerful design pattern in Java used to achieve static polymorphism. By having a class template derive from a template instantiation of its own class, CRTP enables method overriding and compile-time polymorphic behavior, enhancing efficiency and performance in your Java applications. + +## Detailed Explanation of Curiously Recurring Template Pattern with Real-World Examples + +Real-world example + +> Consider a scenario where a library system manages various types of media: books, DVDs, and magazines. Each media type has specific attributes and behaviors, but they all share common functionality like borrowing and returning. By applying the Curiously Recurring Template Pattern (CRTP) in Java, you can create a base template class `MediaItem` encompassing these common methods. Each specific media type (e.g., `Book`, `DVD`, `Magazine`) would inherit from `MediaItem` using itself as a template parameter. This approach allows each media type to customize shared functionality efficiently, avoiding the overhead of virtual methods. + +In plain words + +> The CRTP in Java ensures that certain methods within a type can accept arguments specific to its subtypes, enabling more efficient and type-safe polymorphic behavior at compile time. + +Wikipedia says + +> The curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X derives from a class template instantiation using X itself as a template argument. + +Flowchart + +![Curiously Recurring Template Pattern flowchart](./etc/crtp-flowchart.png) + +## Programmatic example of CRTP in Java + +For a mixed martial arts promotion that is planning an event, ensuring that the fights are organized between athletes of the same weight class is crucial. This prevents mismatches between fighters of significantly different sizes, such as a heavyweight facing off against a bantamweight. + +Let's define the generic interface `Fighter`. + +```java +public interface Fighter { + + void fight(T t); + +} +``` + +The `MMAFighter` class is used to instantiate fighters distinguished by their weight class. + +```java +@Slf4j +@Data +public class MmaFighter> implements Fighter { + + private final String name; + private final String surname; + private final String nickName; + private final String speciality; + + @Override + public void fight(T opponent) { + LOGGER.info("{} is going to fight against {}", this, opponent); + } +} +``` + +The followings are some subtypes of `MmaFighter`. + +```java +class MmaBantamweightFighter extends MmaFighter { + + public MmaBantamweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } +} + +public class MmaHeavyweightFighter extends MmaFighter { + + public MmaHeavyweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } +} +``` + +A fighter is allowed to fight an opponent of the same weight classes. If the opponent is of a different weight class, an error is raised. + +```java +public static void main(String[] args) { + + MmaBantamweightFighter fighter1 = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai"); + MmaBantamweightFighter fighter2 = new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo"); + fighter1.fight(fighter2); + + MmaHeavyweightFighter fighter3 = new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing"); + MmaHeavyweightFighter fighter4 = new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu"); + fighter3.fight(fighter4); +} +``` + +Program output: + +``` +08:42:34.048 [main] INFO crtp.MmaFighter -- MmaFighter(name=Joe, surname=Johnson, nickName=The Geek, speciality=Muay Thai) is going to fight against MmaFighter(name=Ed, surname=Edwards, nickName=The Problem Solver, speciality=Judo) +08:42:34.054 [main] INFO crtp.MmaFighter -- MmaFighter(name=Dave, surname=Davidson, nickName=The Bug Smasher, speciality=Kickboxing) is going to fight against MmaFighter(name=Jack, surname=Jackson, nickName=The Pragmatic, speciality=Brazilian Jiu-Jitsu) +``` + +## When to Use the Curiously Recurring Template Pattern in Java + +* When you need to extend the functionality of a class through inheritance but prefer compile-time polymorphism to runtime polymorphism for efficiency reasons. +* When you want to avoid the overhead of virtual functions but still achieve polymorphic behavior. +* In template metaprogramming to provide implementations of functions or policies that can be selected at compile time. +* You have type conflicts when chaining methods in an object hierarchy. +* You want to use a parameterized class method that can accept subclasses of the class as arguments, allowing it to be applied to objects that inherit from the class. +* You want certain methods to work only with instances of the same type, such as for achieving mutual comparability. + +## Curiously Recurring Template Pattern Java Tutorials + +* [Curiously Recurring Template Pattern in Java (The NuaH Blog)](https://nuah.livejournal.com/328187.html) + +## Real-World Applications of Curiously Recurring Template Pattern in Java + +* Implementing compile-time polymorphic interfaces in template libraries. +* Enhancing code reuse in libraries where performance is critical, like in mathematical computations, embedded systems, and real-time processing applications. +* Implementation of the `Cloneable` interface in various Java libraries. + +## Benefits and Trade-offs of Curiously Recurring Template Pattern + +Benefits: + +* Elimination of virtual function call overhead, enhancing performance. +* Safe reuse of the base class code without the risks associated with multiple inheritances. +* Greater flexibility and extensibility in compile-time polymorphism scenarios. + +Trade-offs: + +* Increased complexity in understanding and debugging due to the interplay of templates and inheritance. +* Can lead to code bloat because each instantiation of a template results in a new class. +* Less flexibility compared to runtime polymorphism as the behavior must be determined entirely at compile time. + +## Related Java Design Patterns + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Can be used in conjunction with CRTP to instantiate derived classes without knowing their specific types. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): CRTP can implement compile-time strategy selection. +* [Template Method](https://java-design-patterns.com/patterns/template-method/): Similar in structure but differs in that CRTP achieves behavior variation through compile-time polymorphism. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) diff --git a/curiously-recurring-template-pattern/etc/crtp-flowchart.png b/curiously-recurring-template-pattern/etc/crtp-flowchart.png new file mode 100644 index 000000000000..a205e1638ca0 Binary files /dev/null and b/curiously-recurring-template-pattern/etc/crtp-flowchart.png differ diff --git a/curiously-recurring-template-pattern/etc/curiously-recurring-template-pattern.urm.puml b/curiously-recurring-template-pattern/etc/curiously-recurring-template-pattern.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/curiously-recurring-template-pattern/etc/curiously-recurring-template-pattern.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/curiously-recurring-template-pattern/pom.xml b/curiously-recurring-template-pattern/pom.xml new file mode 100644 index 000000000000..ab7ed0b19a36 --- /dev/null +++ b/curiously-recurring-template-pattern/pom.xml @@ -0,0 +1,72 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + curiously-recurring-template-pattern + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.crtp.App + + + + + + + + + diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/App.java b/curiously-recurring-template-pattern/src/main/java/crtp/App.java new file mode 100644 index 000000000000..d592dd717f89 --- /dev/null +++ b/curiously-recurring-template-pattern/src/main/java/crtp/App.java @@ -0,0 +1,55 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 crtp; + +import lombok.extern.slf4j.Slf4j; + +/** + * Shows the {@link Fighter} fight method call on some implementations of {@link MmaFighter}. Note + * that fighters can only fight against opponents of their same weight class. + */ +@Slf4j +public class App { + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + + MmaBantamweightFighter fighter1 = + new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai"); + MmaBantamweightFighter fighter2 = + new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo"); + fighter1.fight(fighter2); + + MmaHeavyweightFighter fighter3 = + new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing"); + MmaHeavyweightFighter fighter4 = + new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu"); + fighter3.fight(fighter4); + } +} diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/Fighter.java b/curiously-recurring-template-pattern/src/main/java/crtp/Fighter.java new file mode 100644 index 000000000000..da149229c8ba --- /dev/null +++ b/curiously-recurring-template-pattern/src/main/java/crtp/Fighter.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 crtp; + +/** + * Fighter interface. + * + * @param The type of fighter. + */ +public interface Fighter { + + void fight(T t); +} diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/MmaBantamweightFighter.java b/curiously-recurring-template-pattern/src/main/java/crtp/MmaBantamweightFighter.java new file mode 100644 index 000000000000..08886a3b371c --- /dev/null +++ b/curiously-recurring-template-pattern/src/main/java/crtp/MmaBantamweightFighter.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 crtp; + +/** MmaBantamweightFighter class. */ +class MmaBantamweightFighter extends MmaFighter { + + public MmaBantamweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } +} diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/MmaFighter.java b/curiously-recurring-template-pattern/src/main/java/crtp/MmaFighter.java new file mode 100644 index 000000000000..a62ad2811b38 --- /dev/null +++ b/curiously-recurring-template-pattern/src/main/java/crtp/MmaFighter.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 crtp; + +import lombok.Data; +import lombok.extern.slf4j.Slf4j; + +/** + * MmaFighter class. + * + * @param MmaFighter derived class that uses itself as type parameter. + */ +@Slf4j +@Data +public class MmaFighter> implements Fighter { + + private final String name; + private final String surname; + private final String nickName; + private final String speciality; + + @Override + public void fight(T opponent) { + LOGGER.info("{} is going to fight against {}", this, opponent); + } +} diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/MmaHeavyweightFighter.java b/curiously-recurring-template-pattern/src/main/java/crtp/MmaHeavyweightFighter.java new file mode 100644 index 000000000000..1ed545ede7ec --- /dev/null +++ b/curiously-recurring-template-pattern/src/main/java/crtp/MmaHeavyweightFighter.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 crtp; + +/** MmaHeavyweightFighter. */ +public class MmaHeavyweightFighter extends MmaFighter { + + public MmaHeavyweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } +} diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/MmaLightweightFighter.java b/curiously-recurring-template-pattern/src/main/java/crtp/MmaLightweightFighter.java new file mode 100644 index 000000000000..433b1934fa15 --- /dev/null +++ b/curiously-recurring-template-pattern/src/main/java/crtp/MmaLightweightFighter.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 crtp; + +/** MmaLightweightFighter class. */ +class MmaLightweightFighter extends MmaFighter { + + public MmaLightweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } +} diff --git a/curiously-recurring-template-pattern/src/test/java/crtp/AppTest.java b/curiously-recurring-template-pattern/src/test/java/crtp/AppTest.java new file mode 100644 index 000000000000..fb19aa31a8d6 --- /dev/null +++ b/curiously-recurring-template-pattern/src/test/java/crtp/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 crtp; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application test */ +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/curiously-recurring-template-pattern/src/test/java/crtp/FightTest.java b/curiously-recurring-template-pattern/src/test/java/crtp/FightTest.java new file mode 100644 index 000000000000..a70edd0d674d --- /dev/null +++ b/curiously-recurring-template-pattern/src/test/java/crtp/FightTest.java @@ -0,0 +1,72 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 crtp; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; + +@Slf4j +public class FightTest { + + /** + * A fighter has signed a contract with a promotion, and he will face some other fighters. A list + * of opponents is ready but for some reason not all of them belong to the same weight class. + * Let's ensure that the fighter will only face opponents in the same weight class. + */ + @Test + void testFighterCanFightOnlyAgainstSameWeightOpponents() { + MmaBantamweightFighter fighter = + new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai"); + List> opponents = getOpponents(); + List> challenged = new ArrayList<>(); + + opponents.forEach( + challenger -> { + try { + ((MmaBantamweightFighter) challenger).fight(fighter); + challenged.add(challenger); + } catch (ClassCastException e) { + LOGGER.error(e.getMessage()); + } + }); + + assertFalse(challenged.isEmpty()); + assertTrue(challenged.stream().allMatch(c -> c instanceof MmaBantamweightFighter)); + } + + private static List> getOpponents() { + return List.of( + new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo"), + new MmaLightweightFighter("Evan", "Evans", "Clean Coder", "Sambo"), + new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing"), + new MmaBantamweightFighter("Ray", "Raymond", "Scrum Master", "Karate"), + new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu")); + } +} diff --git a/currying/README.md b/currying/README.md new file mode 100644 index 000000000000..b0e86856df03 --- /dev/null +++ b/currying/README.md @@ -0,0 +1,237 @@ +--- +title: "Currying Pattern in Java: Enhancing Function Flexibility and Reusability" +shortTitle: Currying +description: "Learn about currying in Java, a technique to simplify functions by breaking them into a sequence of single-argument functions. Discover its applications, benefits, and examples in this comprehensive guide." +category: Functional +language: en +tag: + - Code simplification + - Functional decomposition + - Generic + - Immutable +--- + +## Also known as + +* Partial Function Application + +## Intent of Currying Design Pattern + +Currying decomposes a function that takes multiple arguments into a sequence of functions that each take a single argument. This technique is integral in functional programming, enabling the creation of higher-order functions through partial application of its arguments. Using currying in Java can lead to more modular, reusable, and maintainable code. + +## Detailed Explanation of Currying Pattern with Real-World Examples + +Real-world example + +> Currying in programming can be compared to an assembly line in a factory. Imagine a car manufacturing process where each station on the assembly line performs a specific task, such as installing the engine, painting the car, and adding the wheels. Each station takes a partially completed car and performs a single operation before passing it to the next station. Similarly, in currying, a function that requires multiple arguments is broken down into a series of functions, each taking a single argument and returning another function until all arguments are provided. This step-by-step processing simplifies complex tasks by dividing them into manageable, sequential operations, which is especially useful in Java functional programming. + +In plain words + +> Decompose a function that take multiple arguments into multiple functions that take a single argument. + +Wikipedia says + +> In mathematics and computer science, currying is the technique of translating a function that takes multiple arguments into a sequence of families of functions, each taking a single argument. + +Sequence diagram + +![Currying sequence diagram](./etc/currying-sequence-diagram.png) + +## Programmatic example of Currying Pattern in Java + +Consider a librarian who wants to populate their library with books. The librarian wants functions which can create books corresponding to specific genres and authors. Currying makes this possible by writing a curried book builder function and utilising partial application. + +We have a `Book` class and `Genre` enum. + +```java +public class Book { + private final Genre genre; + private final String author; + private final String title; + private final LocalDate publicationDate; + + Book(Genre genre, String author, String title, LocalDate publicationDate) { + this.genre = genre; + this.author = author; + this.title = title; + this.publicationDate = publicationDate; + } +} +``` + +```java +public enum Genre { + FANTASY, + HORROR, + SCI_FI +} +``` + +We could easily create a `Book` object with the following method: + +```java +Book createBook(Genre genre, String author, String title, LocalDate publicationDate) { + return new Book(genre, author, title, publicationDate); +} +``` + +However, what if we only wanted to create books from the `FANTASY` genre? Passing the `FANTASY` parameter with each method call would be repetitive. Alternatively, we could define a new method specifically for creating `FANTASY` books, but it would be impractical to create a separate method for each genre. The solution is to use a curried function. + +```java +static Function>>> book_creator + = bookGenre + -> bookAuthor + -> bookTitle + -> bookPublicationDate + -> new Book(bookGenre, bookAuthor, bookTitle, bookPublicationDate); +``` + +Note that the order of the parameters is important. `genre` must come before `author`, `author` must come before `title` and so on. We must be considerate of this when writing curried functions to take full advantage of partial application. Using the above function, we can define a new function `fantasyBookFunc`, to generate `FANTASY` books as follows: + +```java +Function>> fantasyBookFunc = Book.book_creator.apply(Genre.FANTASY); +``` + +Unfortunately, the type signature of `BOOK_CREATOR` and `fantasyBookFunc` are difficult to read and understand. We can improve this by using the [builder pattern](https://java-design-patterns.com/patterns/builder/) and functional interfaces. + +```java +public static AddGenre builder() { + return genre + -> author + -> title + -> publicationDate + -> new Book(genre, author, title, publicationDate); +} + +public interface AddGenre { + Book.AddAuthor withGenre(Genre genre); +} + +public interface AddAuthor { + Book.AddTitle withAuthor(String author); +} + +public interface AddTitle { + Book.AddPublicationDate withTitle(String title); +} + +public interface AddPublicationDate { + Book withPublicationDate(LocalDate publicationDate); +} +``` + +The semantics of the `builder` function can easily be understood. The `builder` function returns a function `AddGenre`, which adds the genre to the book. Similarity, the `AddGenre` function returns another function `AddTitle`, which adds the title to the book and so on, until the `AddPublicationDate` function returns a `Book`. For example, we could create a `Book` as follows: + +```java +Book book = Book.builder().withGenre(Genre.FANTASY) + .withAuthor("Author") + .withTitle("Title") + .withPublicationDate(LocalDate.of(2000, 7, 2)); +``` + +The below example demonstrates how partial application can be used with the `builder` function to create specialised book builder functions. + +```java +public static void main(String[] args) { + LOGGER.info("Librarian begins their work."); + + // Defining genre book functions + Book.AddAuthor fantasyBookFunc = Book.builder().withGenre(Genre.FANTASY); + Book.AddAuthor horrorBookFunc = Book.builder().withGenre(Genre.HORROR); + Book.AddAuthor scifiBookFunc = Book.builder().withGenre(Genre.SCIFI); + + // Defining author book functions + Book.AddTitle kingFantasyBooksFunc = fantasyBookFunc.withAuthor("Stephen King"); + Book.AddTitle kingHorrorBooksFunc = horrorBookFunc.withAuthor("Stephen King"); + Book.AddTitle rowlingFantasyBooksFunc = fantasyBookFunc.withAuthor("J.K. Rowling"); + + // Creates books by Stephen King (horror and fantasy genres) + Book shining = kingHorrorBooksFunc.withTitle("The Shining") + .withPublicationDate(LocalDate.of(1977, 1, 28)); + Book darkTower = kingFantasyBooksFunc.withTitle("The Dark Tower: Gunslinger") + .withPublicationDate(LocalDate.of(1982, 6, 10)); + + // Creates fantasy books by J.K. Rowling + Book chamberOfSecrets = rowlingFantasyBooksFunc.withTitle("Harry Potter and the Chamber of Secrets") + .withPublicationDate(LocalDate.of(1998, 7, 2)); + + // Create sci-fi books + Book dune = scifiBookFunc.withAuthor("Frank Herbert") + .withTitle("Dune") + .withPublicationDate(LocalDate.of(1965, 8, 1)); + Book foundation = scifiBookFunc.withAuthor("Isaac Asimov") + .withTitle("Foundation") + .withPublicationDate(LocalDate.of(1942, 5, 1)); + + LOGGER.info("Stephen King Books:"); + LOGGER.info(shining.toString()); + LOGGER.info(darkTower.toString()); + + LOGGER.info("J.K. Rowling Books:"); + LOGGER.info(chamberOfSecrets.toString()); + + LOGGER.info("Sci-fi Books:"); + LOGGER.info(dune.toString()); + LOGGER.info(foundation.toString()); +} +``` + +Program output: + +``` +09:04:52.499 [main] INFO com.iluwatar.currying.App -- Librarian begins their work. +09:04:52.502 [main] INFO com.iluwatar.currying.App -- Stephen King Books: +09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=HORROR, author='Stephen King', title='The Shining', publicationDate=1977-01-28} +09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=FANTASY, author='Stephen King', title='The Dark Tower: Gunslinger', publicationDate=1982-06-10} +09:04:52.506 [main] INFO com.iluwatar.currying.App -- J.K. Rowling Books: +09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=FANTASY, author='J.K. Rowling', title='Harry Potter and the Chamber of Secrets', publicationDate=1998-07-02} +09:04:52.506 [main] INFO com.iluwatar.currying.App -- Sci-fi Books: +09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=SCIFI, author='Frank Herbert', title='Dune', publicationDate=1965-08-01} +09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=SCIFI, author='Isaac Asimov', title='Foundation', publicationDate=1942-05-01} +``` + +## When to Use the Currying Pattern in Java + +* When functions need to be called with some arguments preset in Java. +* In functional programming languages or paradigms to simplify functions that take multiple arguments. +* To improve code reusability and composability by breaking down functions into simpler, unary functions, enhancing the modularity of Java applications. + +## Currying Pattern Java Tutorials + +* [Currying in Java (Baeldung)](https://www.baeldung.com/java-currying) +* [What Is Currying in Programming (Towards Data Science)](https://towardsdatascience.com/what-is-currying-in-programming-56fd57103431#:~:text=Currying%20is%20helpful%20when%20you,concise%2C%20and%20more%20readable%20solution.) +* [Why the fudge should I use currying? (DailyJS)](https://medium.com/dailyjs/why-the-fudge-should-i-use-currying-84e4000c8743) + +## Real-World Applications of Currying Pattern in Java + +* Functional programming languages like Haskell, Scala, and JavaScript. +* Java programming, especially with lambda expressions and streams introduced in Java 8. +* Event handling in UIs where a function with specific parameters needs to be triggered upon an event. +* APIs that require configuration with multiple parameters. + +## Benefits and Trade-offs of Currying Pattern + +Benefits: + +* Increases function reusability by allowing the creation of specialized functions from more generic ones. +* Enhances code readability and maintainability by breaking complex functions into simpler, single-argument functions. +* Facilitates function composition, leading to more declarative and concise code. + +Trade-offs: + +* Can lead to performance overhead due to the creation of additional closures. +* May make debugging more challenging, as it introduces additional layers of function calls. +* Can be less intuitive for developers unfamiliar with functional programming concepts. +* As shown in the programmatic example above, curried functions with several parameters have a cumbersome type signature in Java. + +## Related Java Design Patterns + +* Function Composition: Currying is often used in conjunction with function composition to enable more readable and concise code. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): While not the same, currying shares the decorator pattern's concept of wrapping functionality. +* [Factory](https://java-design-patterns.com/patterns/factory/): Currying can be used to create factory functions that produce variations of a function with certain arguments preset. + +## References and Credits + +* [Functional Programming in Java: Harnessing the Power Of Java 8 Lambda Expressions](https://amzn.to/3TKeZPD) +* [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3J6vEaW) +* [Modern Java in Action: Lambdas, streams, functional and reactive programming](https://amzn.to/3J6vJLM) diff --git a/currying/etc/currying-sequence-diagram.png b/currying/etc/currying-sequence-diagram.png new file mode 100644 index 000000000000..7c3300263566 Binary files /dev/null and b/currying/etc/currying-sequence-diagram.png differ diff --git a/currying/etc/currying.urm.png b/currying/etc/currying.urm.png new file mode 100644 index 000000000000..c672bdde37cf Binary files /dev/null and b/currying/etc/currying.urm.png differ diff --git a/currying/etc/currying.urm.puml b/currying/etc/currying.urm.puml new file mode 100644 index 000000000000..9b336ff90828 --- /dev/null +++ b/currying/etc/currying.urm.puml @@ -0,0 +1,39 @@ +@startuml +package com.iluwatar.currying { + class App { + + App() + + main(args : String[]) {static} + } + class Book { + ~ BOOK_CREATOR : Function>>> {static} + - author : String + - genre : Genre + - publicationDate : LocalDate + - title : String + ~ Book(genre : Genre, author : String, title : String, publicationDate : LocalDate) + + builder() : AddGenre {static} + } + interface AddAuthor { + + withAuthor(String) : AddTitle {abstract} + } + interface AddGenre { + + withGenre(Genre) : AddAuthor {abstract} + } + interface AddPublicationDate { + + withPublicationDate(LocalDate) : Book {abstract} + } + interface AddTitle { + + withTitle(String) : AddPublicationDate {abstract} + } + enum Genre { + + FANTASY {static} + + HORROR {static} + + SCI_FI {static} + } +} +Book --> "-genre" Genre +AddPublicationDate ..+ Book +AddAuthor ..+ Book +AddTitle ..+ Book +AddGenre ..+ Book +@enduml \ No newline at end of file diff --git a/currying/pom.xml b/currying/pom.xml new file mode 100644 index 000000000000..5244aa2792d8 --- /dev/null +++ b/currying/pom.xml @@ -0,0 +1,74 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + currying + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.currying.App + + + + + + + + + \ No newline at end of file diff --git a/currying/src/main/java/com/iluwatar/currying/App.java b/currying/src/main/java/com/iluwatar/currying/App.java new file mode 100644 index 000000000000..d919887530a2 --- /dev/null +++ b/currying/src/main/java/com/iluwatar/currying/App.java @@ -0,0 +1,92 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.currying; + +import java.time.LocalDate; +import lombok.extern.slf4j.Slf4j; + +/** + * Currying decomposes a function with multiple arguments in multiple functions that take a single + * argument. A curried function which has only been passed some of its arguments is called a partial + * application. Partial application is useful since it can be used to create specialised functions + * in a concise way. + * + *

    In this example, a librarian uses a curried book builder function create books belonging to + * desired genres and written by specific authors. + */ +@Slf4j +public class App { + /** Main entry point of the program. */ + public static void main(String[] args) { + LOGGER.info("Librarian begins their work."); + + // Defining genre book functions + Book.AddAuthor fantasyBookFunc = Book.builder().withGenre(Genre.FANTASY); + Book.AddAuthor horrorBookFunc = Book.builder().withGenre(Genre.HORROR); + Book.AddAuthor scifiBookFunc = Book.builder().withGenre(Genre.SCIFI); + + // Defining author book functions + Book.AddTitle kingFantasyBooksFunc = fantasyBookFunc.withAuthor("Stephen King"); + Book.AddTitle kingHorrorBooksFunc = horrorBookFunc.withAuthor("Stephen King"); + Book.AddTitle rowlingFantasyBooksFunc = fantasyBookFunc.withAuthor("J.K. Rowling"); + + // Creates books by Stephen King (horror and fantasy genres) + Book shining = + kingHorrorBooksFunc.withTitle("The Shining").withPublicationDate(LocalDate.of(1977, 1, 28)); + Book darkTower = + kingFantasyBooksFunc + .withTitle("The Dark Tower: Gunslinger") + .withPublicationDate(LocalDate.of(1982, 6, 10)); + + // Creates fantasy books by J.K. Rowling + Book chamberOfSecrets = + rowlingFantasyBooksFunc + .withTitle("Harry Potter and the Chamber of Secrets") + .withPublicationDate(LocalDate.of(1998, 7, 2)); + + // Create sci-fi books + Book dune = + scifiBookFunc + .withAuthor("Frank Herbert") + .withTitle("Dune") + .withPublicationDate(LocalDate.of(1965, 8, 1)); + Book foundation = + scifiBookFunc + .withAuthor("Isaac Asimov") + .withTitle("Foundation") + .withPublicationDate(LocalDate.of(1942, 5, 1)); + + LOGGER.info("Stephen King Books:"); + LOGGER.info(shining.toString()); + LOGGER.info(darkTower.toString()); + + LOGGER.info("J.K. Rowling Books:"); + LOGGER.info(chamberOfSecrets.toString()); + + LOGGER.info("Sci-fi Books:"); + LOGGER.info(dune.toString()); + LOGGER.info(foundation.toString()); + } +} diff --git a/currying/src/main/java/com/iluwatar/currying/Book.java b/currying/src/main/java/com/iluwatar/currying/Book.java new file mode 100644 index 000000000000..7ec4ed8cb448 --- /dev/null +++ b/currying/src/main/java/com/iluwatar/currying/Book.java @@ -0,0 +1,113 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.currying; + +import java.time.LocalDate; +import java.util.Objects; +import java.util.function.Function; +import lombok.AllArgsConstructor; + +/** Book class. */ +@AllArgsConstructor +public class Book { + private final Genre genre; + private final String author; + private final String title; + private final LocalDate publicationDate; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Book book = (Book) o; + return Objects.equals(author, book.author) + && Objects.equals(genre, book.genre) + && Objects.equals(title, book.title) + && Objects.equals(publicationDate, book.publicationDate); + } + + @Override + public int hashCode() { + return Objects.hash(author, genre, title, publicationDate); + } + + @Override + public String toString() { + return "Book{" + + "genre=" + + genre + + ", author='" + + author + + '\'' + + ", title='" + + title + + '\'' + + ", publicationDate=" + + publicationDate + + '}'; + } + + /** Curried book builder/creator function. */ + static Function>>> + book_creator = + bookGenre -> + bookAuthor -> + bookTitle -> + bookPublicationDate -> + new Book(bookGenre, bookAuthor, bookTitle, bookPublicationDate); + + /** + * Implements the builder pattern using functional interfaces to create a more readable book + * creator function. This function is equivalent to the BOOK_CREATOR function. + */ + public static AddGenre builder() { + return genre -> + author -> title -> publicationDate -> new Book(genre, author, title, publicationDate); + } + + /** Functional interface which adds the genre to a book. */ + public interface AddGenre { + Book.AddAuthor withGenre(Genre genre); + } + + /** Functional interface which adds the author to a book. */ + public interface AddAuthor { + Book.AddTitle withAuthor(String author); + } + + /** Functional interface which adds the title to a book. */ + public interface AddTitle { + Book.AddPublicationDate withTitle(String title); + } + + /** Functional interface which adds the publication date to a book. */ + public interface AddPublicationDate { + Book withPublicationDate(LocalDate publicationDate); + } +} diff --git a/currying/src/main/java/com/iluwatar/currying/Genre.java b/currying/src/main/java/com/iluwatar/currying/Genre.java new file mode 100644 index 000000000000..ad41f4004190 --- /dev/null +++ b/currying/src/main/java/com/iluwatar/currying/Genre.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.currying; + +/** Enum representing different book genres. */ +public enum Genre { + FANTASY, + HORROR, + SCIFI +} diff --git a/currying/src/test/java/com/iluwatar/currying/AppTest.java b/currying/src/test/java/com/iluwatar/currying/AppTest.java new file mode 100644 index 000000000000..3074628f29e6 --- /dev/null +++ b/currying/src/test/java/com/iluwatar/currying/AppTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.currying; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +/** Tests that the App can be run without throwing any exceptions. */ +class AppTest { + @Test + void executesWithoutExceptions() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java b/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java new file mode 100644 index 000000000000..f22ff62850e5 --- /dev/null +++ b/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.currying; + +import static org.junit.jupiter.api.Assertions.*; + +import java.time.LocalDate; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** Unit tests for the Book class */ +class BookCurryingTest { + private static Book expectedBook; + + @BeforeAll + public static void initialiseBook() { + expectedBook = new Book(Genre.FANTASY, "Dave", "Into the Night", LocalDate.of(2002, 4, 7)); + } + + /** Tests that the expected book can be created via curried functions */ + @Test + void createsExpectedBook() { + Book builderCurriedBook = + Book.builder() + .withGenre(Genre.FANTASY) + .withAuthor("Dave") + .withTitle("Into the Night") + .withPublicationDate(LocalDate.of(2002, 4, 7)); + + Book funcCurriedBook = + Book.book_creator + .apply(Genre.FANTASY) + .apply("Dave") + .apply("Into the Night") + .apply(LocalDate.of(2002, 4, 7)); + + assertEquals(expectedBook, builderCurriedBook); + assertEquals(expectedBook, funcCurriedBook); + } + + /** Tests that an intermediate curried function can be used to create the expected book */ + @Test + void functionCreatesExpectedBook() { + Book.AddTitle daveFantasyBookFunc = Book.builder().withGenre(Genre.FANTASY).withAuthor("Dave"); + + Book curriedBook = + daveFantasyBookFunc + .withTitle("Into the Night") + .withPublicationDate(LocalDate.of(2002, 4, 7)); + + assertEquals(expectedBook, curriedBook); + } +} diff --git a/dao/README.md b/dao/README.md deleted file mode 100644 index 785a1c362a58..000000000000 --- a/dao/README.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -layout: pattern -title: Data Access Object -folder: dao -permalink: /patterns/dao/ -categories: Persistence Tier -tags: - - Java - - Difficulty-Beginner ---- - -## Intent -Object provides an abstract interface to some type of database or -other persistence mechanism. - -![alt text](./etc/dao.png "Data Access Object") - -## Applicability -Use the Data Access Object in any of the following situations - -* when you want to consolidate how the data layer is accessed -* when you want to avoid writing multiple data retrieval/persistence layers - -## Credits - -* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2) diff --git a/dao/pom.xml b/dao/pom.xml deleted file mode 100644 index 3700d76a7896..000000000000 --- a/dao/pom.xml +++ /dev/null @@ -1,106 +0,0 @@ - - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - dao - - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - log4j - log4j - - - com.h2database - h2 - - - org.mockito - mockito-core - - - - - - - - - - src/main/resources - - - src/main/resources - - log4j.xml - - .. - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.6 - - - log4j.xml - - - - true - - - - - - - - diff --git a/dao/src/main/java/com/iluwatar/dao/App.java b/dao/src/main/java/com/iluwatar/dao/App.java deleted file mode 100644 index d2fa945b617d..000000000000 --- a/dao/src/main/java/com/iluwatar/dao/App.java +++ /dev/null @@ -1,135 +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.dao; - -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Stream; - -import javax.sql.DataSource; - -import org.apache.log4j.Logger; -import org.h2.jdbcx.JdbcDataSource; - -/** - * Data Access Object (DAO) is an object that provides an abstract interface to some type of - * database or other persistence mechanism. By mapping application calls to the persistence layer, - * DAO provide some specific data operations without exposing details of the database. This - * isolation supports the Single responsibility principle. It separates what data accesses the - * application needs, in terms of domain-specific objects and data types (the public interface of - * the DAO), from how these needs can be satisfied with a specific DBMS. - * - *

    With the DAO pattern, we can use various method calls to retrieve/add/delete/update data - * without directly interacting with the data source. The below example demonstrates basic CRUD - * operations: select, add, update, and delete. - * - * - */ -public class App { - private static final String DB_URL = "jdbc:h2:~/dao"; - private static Logger log = Logger.getLogger(App.class); - - /** - * Program entry point. - * - * @param args command line args. - * @throws Exception if any error occurs. - */ - public static void main(final String[] args) throws Exception { - final CustomerDao inMemoryDao = new InMemoryCustomerDao(); - performOperationsUsing(inMemoryDao); - - final DataSource dataSource = createDataSource(); - createSchema(dataSource); - final CustomerDao dbDao = new DbCustomerDao(dataSource); - performOperationsUsing(dbDao); - deleteSchema(dataSource); - } - - private static void deleteSchema(DataSource dataSource) throws SQLException { - try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { - statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); - } - } - - private static void createSchema(DataSource dataSource) throws SQLException { - try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { - statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); - } - } - - private static DataSource createDataSource() { - JdbcDataSource dataSource = new JdbcDataSource(); - dataSource.setURL(DB_URL); - return dataSource; - } - - private static void performOperationsUsing(final CustomerDao customerDao) throws Exception { - addCustomers(customerDao); - log.info("customerDao.getAllCustomers(): "); - try (Stream customerStream = customerDao.getAll()) { - customerStream.forEach((customer) -> log.info(customer)); - } - log.info("customerDao.getCustomerById(2): " + customerDao.getById(2)); - final Customer customer = new Customer(4, "Dan", "Danson"); - customerDao.add(customer); - log.info("customerDao.getAllCustomers(): " + customerDao.getAll()); - customer.setFirstName("Daniel"); - customer.setLastName("Danielson"); - customerDao.update(customer); - log.info("customerDao.getAllCustomers(): "); - try (Stream customerStream = customerDao.getAll()) { - customerStream.forEach((cust) -> log.info(cust)); - } - customerDao.delete(customer); - log.info("customerDao.getAllCustomers(): " + customerDao.getAll()); - } - - private static void addCustomers(CustomerDao customerDao) throws Exception { - for (Customer customer : generateSampleCustomers()) { - customerDao.add(customer); - } - } - - /** - * Generate customers. - * - * @return list of customers. - */ - public static List generateSampleCustomers() { - final Customer customer1 = new Customer(1, "Adam", "Adamson"); - final Customer customer2 = new Customer(2, "Bob", "Bobson"); - final Customer customer3 = new Customer(3, "Carl", "Carlson"); - final List customers = new ArrayList<>(); - customers.add(customer1); - customers.add(customer2); - customers.add(customer3); - return customers; - } -} diff --git a/dao/src/main/java/com/iluwatar/dao/Customer.java b/dao/src/main/java/com/iluwatar/dao/Customer.java deleted file mode 100644 index a133bf2b0ded..000000000000 --- a/dao/src/main/java/com/iluwatar/dao/Customer.java +++ /dev/null @@ -1,93 +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.dao; - -/** - * A customer POJO that represents the data that will be read from the data source. - * - */ -public class Customer { - - private int id; - private String firstName; - private String lastName; - - /** - * Creates an instance of customer. - */ - public Customer(final int id, final String firstName, final String lastName) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(final String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(final String lastName) { - this.lastName = lastName; - } - - @Override - public String toString() { - return "Customer{" + "id=" + getId() + ", firstName='" + getFirstName() + '\'' + ", lastName='" - + getLastName() + '\'' + '}'; - } - - @Override - public boolean equals(final Object that) { - boolean isEqual = false; - if (this == that) { - isEqual = true; - } else if (that != null && getClass() == that.getClass()) { - final Customer customer = (Customer) that; - if (getId() == customer.getId()) { - isEqual = true; - } - } - return isEqual; - } - - @Override - public int hashCode() { - return getId(); - } -} diff --git a/dao/src/main/java/com/iluwatar/dao/CustomerDao.java b/dao/src/main/java/com/iluwatar/dao/CustomerDao.java deleted file mode 100644 index 6156bb8d7d95..000000000000 --- a/dao/src/main/java/com/iluwatar/dao/CustomerDao.java +++ /dev/null @@ -1,81 +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.dao; - -import java.util.Optional; -import java.util.stream.Stream; - -/** - * In an application the Data Access Object (DAO) is a part of Data access layer. It is an object - * that provides an interface to some type of persistence mechanism. By mapping application calls - * to the persistence layer, DAO provides some specific data operations without exposing details - * of the database. This isolation supports the Single responsibility principle. It separates what - * data accesses the application needs, in terms of domain-specific objects and data types - * (the public interface of the DAO), from how these needs can be satisfied with a specific DBMS, - * database schema, etc. - * - *

    Any change in the way data is stored and retrieved will not change the client code as the - * client will be using interface and need not worry about exact source. - * - * @see InMemoryCustomerDao - * @see DbCustomerDao - */ -public interface CustomerDao { - - /** - * @return all the customers as a stream. The stream may be lazily or eagerly evaluated based - * on the implementation. The stream must be closed after use. - * @throws Exception if any error occurs. - */ - Stream getAll() throws Exception; - - /** - * @param id unique identifier of the customer. - * @return an optional with customer if a customer with unique identifier id - * exists, empty optional otherwise. - * @throws Exception if any error occurs. - */ - Optional getById(int id) throws Exception; - - /** - * @param customer the customer to be added. - * @return true if customer is successfully added, false if customer already exists. - * @throws Exception if any error occurs. - */ - boolean add(Customer customer) throws Exception; - - /** - * @param customer the customer to be updated. - * @return true if customer exists and is successfully updated, false otherwise. - * @throws Exception if any error occurs. - */ - boolean update(Customer customer) throws Exception; - - /** - * @param customer the customer to be deleted. - * @return true if customer exists and is successfully deleted, false otherwise. - * @throws Exception if any error occurs. - */ - boolean delete(Customer customer) throws Exception; -} diff --git a/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java b/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java deleted file mode 100644 index fa2e411dab56..000000000000 --- a/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java +++ /dev/null @@ -1,196 +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.dao; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Optional; -import java.util.Spliterator; -import java.util.Spliterators; -import java.util.function.Consumer; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; - -import javax.sql.DataSource; - -import org.apache.log4j.Logger; - -/** - * An implementation of {@link CustomerDao} that persists customers in RDBMS. - * - */ -public class DbCustomerDao implements CustomerDao { - - private static final Logger LOGGER = Logger.getLogger(DbCustomerDao.class); - - private final DataSource dataSource; - - /** - * Creates an instance of {@link DbCustomerDao} which uses provided dataSource - * to store and retrieve customer information. - * - * @param dataSource a non-null dataSource. - */ - public DbCustomerDao(DataSource dataSource) { - this.dataSource = dataSource; - } - - /** - * @return a lazily populated stream of customers. Note the stream returned must be closed to - * free all the acquired resources. The stream keeps an open connection to the database till - * it is complete or is closed manually. - */ - @Override - public Stream getAll() throws Exception { - - Connection connection; - try { - connection = getConnection(); - PreparedStatement statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR - ResultSet resultSet = statement.executeQuery(); // NOSONAR - return StreamSupport.stream(new Spliterators.AbstractSpliterator(Long.MAX_VALUE, - Spliterator.ORDERED) { - - @Override - public boolean tryAdvance(Consumer action) { - try { - if (!resultSet.next()) { - return false; - } - action.accept(createCustomer(resultSet)); - return true; - } catch (SQLException e) { - throw new RuntimeException(e); // NOSONAR - } - } - }, false).onClose(() -> mutedClose(connection, statement, resultSet)); - } catch (SQLException e) { - throw new CustomException(e.getMessage(), e); - } - } - - private Connection getConnection() throws SQLException { - return dataSource.getConnection(); - } - - private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) { - try { - resultSet.close(); - statement.close(); - connection.close(); - } catch (SQLException e) { - LOGGER.info("Exception thrown " + e.getMessage()); - } - } - - private Customer createCustomer(ResultSet resultSet) throws SQLException { - return new Customer(resultSet.getInt("ID"), - resultSet.getString("FNAME"), - resultSet.getString("LNAME")); - } - - /** - * {@inheritDoc} - */ - @Override - public Optional getById(int id) throws Exception { - - ResultSet resultSet = null; - - try (Connection connection = getConnection(); - PreparedStatement statement = - connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) { - - statement.setInt(1, id); - resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(createCustomer(resultSet)); - } else { - return Optional.empty(); - } - } catch (SQLException ex) { - throw new CustomException(ex.getMessage(), ex); - } finally { - if (resultSet != null) { - resultSet.close(); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean add(Customer customer) throws Exception { - if (getById(customer.getId()).isPresent()) { - return false; - } - - try (Connection connection = getConnection(); - PreparedStatement statement = - connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) { - statement.setInt(1, customer.getId()); - statement.setString(2, customer.getFirstName()); - statement.setString(3, customer.getLastName()); - statement.execute(); - return true; - } catch (SQLException ex) { - throw new CustomException(ex.getMessage(), ex); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean update(Customer customer) throws Exception { - try (Connection connection = getConnection(); - PreparedStatement statement = - connection.prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) { - statement.setString(1, customer.getFirstName()); - statement.setString(2, customer.getLastName()); - statement.setInt(3, customer.getId()); - return statement.executeUpdate() > 0; - } catch (SQLException ex) { - throw new CustomException(ex.getMessage(), ex); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean delete(Customer customer) throws Exception { - try (Connection connection = getConnection(); - PreparedStatement statement = - connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) { - statement.setInt(1, customer.getId()); - return statement.executeUpdate() > 0; - } catch (SQLException ex) { - throw new CustomException(ex.getMessage(), ex); - } - } -} diff --git a/dao/src/main/resources/log4j.xml b/dao/src/main/resources/log4j.xml deleted file mode 100644 index 14f043ff7576..000000000000 --- a/dao/src/main/resources/log4j.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dao/src/test/java/com/iluwatar/dao/AppTest.java b/dao/src/test/java/com/iluwatar/dao/AppTest.java deleted file mode 100644 index 75ef59f18463..000000000000 --- a/dao/src/test/java/com/iluwatar/dao/AppTest.java +++ /dev/null @@ -1,37 +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.dao; - -import org.junit.jupiter.api.Test; - -/** - * Tests that DAO example runs without errors. - */ -public class AppTest { - @Test - public void test() throws Exception { - String[] args = {}; - App.main(args); - } -} diff --git a/dao/src/test/java/com/iluwatar/dao/CustomerTest.java b/dao/src/test/java/com/iluwatar/dao/CustomerTest.java deleted file mode 100644 index 1a55e3bebcd1..000000000000 --- a/dao/src/test/java/com/iluwatar/dao/CustomerTest.java +++ /dev/null @@ -1,100 +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.dao; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link Customer}. - */ -public class CustomerTest { - - private Customer customer; - private static final int ID = 1; - private static final String FIRSTNAME = "Winston"; - private static final String LASTNAME = "Churchill"; - - @BeforeEach - public void setUp() { - customer = new Customer(ID, FIRSTNAME, LASTNAME); - } - - @Test - public void getAndSetId() { - final int newId = 2; - customer.setId(newId); - assertEquals(newId, customer.getId()); - } - - @Test - public void getAndSetFirstname() { - final String newFirstname = "Bill"; - customer.setFirstName(newFirstname); - assertEquals(newFirstname, customer.getFirstName()); - } - - @Test - public void getAndSetLastname() { - final String newLastname = "Clinton"; - customer.setLastName(newLastname); - assertEquals(newLastname, customer.getLastName()); - } - - @Test - public void notEqualWithDifferentId() { - final int newId = 2; - final Customer otherCustomer = new Customer(newId, FIRSTNAME, LASTNAME); - assertNotEquals(customer, otherCustomer); - assertNotEquals(customer.hashCode(), otherCustomer.hashCode()); - } - - @Test - public void equalsWithSameObjectValues() { - final Customer otherCustomer = new Customer(ID, FIRSTNAME, LASTNAME); - assertEquals(customer, otherCustomer); - assertEquals(customer.hashCode(), otherCustomer.hashCode()); - } - - @Test - public void equalsWithSameObjects() { - assertEquals(customer, customer); - assertEquals(customer.hashCode(), customer.hashCode()); - } - - @Test - public void testToString() { - final StringBuffer buffer = new StringBuffer(); - buffer.append("Customer{id=") - .append("" + customer.getId()) - .append(", firstName='") - .append(customer.getFirstName()) - .append("\', lastName='") - .append(customer.getLastName() + "\'}"); - assertEquals(buffer.toString(), customer.toString()); - } -} diff --git a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java deleted file mode 100644 index 80920aa371d9..000000000000 --- a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java +++ /dev/null @@ -1,273 +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.dao; - -import org.h2.jdbcx.JdbcDataSource; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; - -/** - * Tests {@link DbCustomerDao}. - */ -public class DbCustomerDaoTest { - - private static final String DB_URL = "jdbc:h2:~/dao"; - private DbCustomerDao dao; - private Customer existingCustomer = new Customer(1, "Freddy", "Krueger"); - - /** - * Creates customers schema. - * @throws SQLException if there is any error while creating schema. - */ - @BeforeEach - public void createSchema() throws SQLException { - try (Connection connection = DriverManager.getConnection(DB_URL); - Statement statement = connection.createStatement()) { - statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); - } - } - - /** - * Represents the scenario where DB connectivity is present. - */ - @Nested - public class ConnectionSuccess { - - /** - * Setup for connection success scenario. - * @throws Exception if any error occurs. - */ - @BeforeEach - public void setUp() throws Exception { - JdbcDataSource dataSource = new JdbcDataSource(); - dataSource.setURL(DB_URL); - dao = new DbCustomerDao(dataSource); - boolean result = dao.add(existingCustomer); - assertTrue(result); - } - - /** - * Represents the scenario when DAO operations are being performed on a non existing customer. - */ - @Nested - public class NonExistingCustomer { - - @Test - public void addingShouldResultInSuccess() throws Exception { - try (Stream allCustomers = dao.getAll()) { - assumeTrue(allCustomers.count() == 1); - } - - final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); - boolean result = dao.add(nonExistingCustomer); - assertTrue(result); - - assertCustomerCountIs(2); - assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get()); - } - - @Test - public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { - final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); - boolean result = dao.delete(nonExistingCustomer); - - assertFalse(result); - assertCustomerCountIs(1); - } - - @Test - public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { - final int nonExistingId = getNonExistingCustomerId(); - final String newFirstname = "Douglas"; - final String newLastname = "MacArthur"; - final Customer customer = new Customer(nonExistingId, newFirstname, newLastname); - boolean result = dao.update(customer); - - assertFalse(result); - assertFalse(dao.getById(nonExistingId).isPresent()); - } - - @Test - public void retrieveShouldReturnNoCustomer() throws Exception { - assertFalse(dao.getById(getNonExistingCustomerId()).isPresent()); - } - } - - /** - * Represents a scenario where DAO operations are being performed on an already existing - * customer. - * - */ - @Nested - public class ExistingCustomer { - - @Test - public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { - Customer existingCustomer = new Customer(1, "Freddy", "Krueger"); - - boolean result = dao.add(existingCustomer); - - assertFalse(result); - assertCustomerCountIs(1); - assertEquals(existingCustomer, dao.getById(existingCustomer.getId()).get()); - } - - @Test - public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { - boolean result = dao.delete(existingCustomer); - - assertTrue(result); - assertCustomerCountIs(0); - assertFalse(dao.getById(existingCustomer.getId()).isPresent()); - } - - @Test - public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception { - final String newFirstname = "Bernard"; - final String newLastname = "Montgomery"; - final Customer customer = new Customer(existingCustomer.getId(), newFirstname, newLastname); - boolean result = dao.update(customer); - - assertTrue(result); - - final Customer cust = dao.getById(existingCustomer.getId()).get(); - assertEquals(newFirstname, cust.getFirstName()); - assertEquals(newLastname, cust.getLastName()); - } - } - } - - /** - * Represents a scenario where DB connectivity is not present due to network issue, or - * DB service unavailable. - * - */ - @Nested - public class ConnectivityIssue { - - private static final String EXCEPTION_CAUSE = "Connection not available"; - - /** - * setup a connection failure scenario. - * @throws SQLException if any error occurs. - */ - @BeforeEach - public void setUp() throws SQLException { - dao = new DbCustomerDao(mockedDatasource()); - } - - private DataSource mockedDatasource() throws SQLException { - DataSource mockedDataSource = mock(DataSource.class); - Connection mockedConnection = mock(Connection.class); - SQLException exception = new SQLException(EXCEPTION_CAUSE); - doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString()); - doReturn(mockedConnection).when(mockedDataSource).getConnection(); - return mockedDataSource; - } - - @Test - public void addingACustomerFailsWithExceptionAsFeedbackToClient() { - assertThrows(Exception.class, () -> { - dao.add(new Customer(2, "Bernard", "Montgomery")); - }); - } - - @Test - public void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() { - assertThrows(Exception.class, () -> { - dao.delete(existingCustomer); - }); - } - - @Test - public void updatingACustomerFailsWithFeedbackToTheClient() { - final String newFirstname = "Bernard"; - final String newLastname = "Montgomery"; - assertThrows(Exception.class, () -> { - dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname)); - }); - } - - @Test - public void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() { - assertThrows(Exception.class, () -> { - dao.getById(existingCustomer.getId()); - }); - } - - @Test - public void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() { - assertThrows(Exception.class, () -> { - dao.getAll(); - }); - } - - } - - /** - * Delete customer schema for fresh setup per test. - * @throws SQLException if any error occurs. - */ - @AfterEach - public void deleteSchema() throws SQLException { - try (Connection connection = DriverManager.getConnection(DB_URL); - Statement statement = connection.createStatement()) { - statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); - } - } - - private void assertCustomerCountIs(int count) throws Exception { - try (Stream allCustomers = dao.getAll()) { - assertTrue(allCustomers.count() == count); - } - } - - - /** - * An arbitrary number which does not correspond to an active Customer id. - * - * @return an int of a customer id which doesn't exist - */ - private int getNonExistingCustomerId() { - return 999; - } -} diff --git a/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java b/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java deleted file mode 100644 index 7cb14b0b1d9f..000000000000 --- a/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java +++ /dev/null @@ -1,162 +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.dao; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; - -import java.util.Optional; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * Tests {@link InMemoryCustomerDao}. - */ -public class InMemoryCustomerDaoTest { - - private InMemoryCustomerDao dao; - private static final Customer CUSTOMER = new Customer(1, "Freddy", "Krueger"); - - @BeforeEach - public void setUp() { - dao = new InMemoryCustomerDao(); - assertTrue(dao.add(CUSTOMER)); - } - - /** - * Represents the scenario when the DAO operations are being performed on a non existent - * customer. - */ - @Nested - public class NonExistingCustomer { - - @Test - public void addingShouldResultInSuccess() throws Exception { - try (Stream allCustomers = dao.getAll()) { - assumeTrue(allCustomers.count() == 1); - } - - final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); - boolean result = dao.add(nonExistingCustomer); - assertTrue(result); - - assertCustomerCountIs(2); - assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get()); - } - - @Test - public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { - final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); - boolean result = dao.delete(nonExistingCustomer); - - assertFalse(result); - assertCustomerCountIs(1); - } - - @Test - public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { - final int nonExistingId = getNonExistingCustomerId(); - final String newFirstname = "Douglas"; - final String newLastname = "MacArthur"; - final Customer customer = new Customer(nonExistingId, newFirstname, newLastname); - boolean result = dao.update(customer); - - assertFalse(result); - assertFalse(dao.getById(nonExistingId).isPresent()); - } - - @Test - public void retrieveShouldReturnNoCustomer() throws Exception { - assertFalse(dao.getById(getNonExistingCustomerId()).isPresent()); - } - } - - /** - * Represents the scenario when the DAO operations are being performed on an already existing - * customer. - */ - @Nested - public class ExistingCustomer { - - @Test - public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { - boolean result = dao.add(CUSTOMER); - - assertFalse(result); - assertCustomerCountIs(1); - assertEquals(CUSTOMER, dao.getById(CUSTOMER.getId()).get()); - } - - @Test - public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { - boolean result = dao.delete(CUSTOMER); - - assertTrue(result); - assertCustomerCountIs(0); - assertFalse(dao.getById(CUSTOMER.getId()).isPresent()); - } - - @Test - public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception { - final String newFirstname = "Bernard"; - final String newLastname = "Montgomery"; - final Customer customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname); - boolean result = dao.update(customer); - - assertTrue(result); - - final Customer cust = dao.getById(CUSTOMER.getId()).get(); - assertEquals(newFirstname, cust.getFirstName()); - assertEquals(newLastname, cust.getLastName()); - } - - @Test - public void retriveShouldReturnTheCustomer() { - Optional optionalCustomer = dao.getById(CUSTOMER.getId()); - - assertTrue(optionalCustomer.isPresent()); - assertEquals(CUSTOMER, optionalCustomer.get()); - } - } - - /** - * An arbitrary number which does not correspond to an active Customer id. - * - * @return an int of a customer id which doesn't exist - */ - private int getNonExistingCustomerId() { - return 999; - } - - private void assertCustomerCountIs(int count) throws Exception { - try (Stream allCustomers = dao.getAll()) { - assertTrue(allCustomers.count() == count); - } - } -} diff --git a/data-access-object/README.md b/data-access-object/README.md new file mode 100644 index 000000000000..7e84299e23e1 --- /dev/null +++ b/data-access-object/README.md @@ -0,0 +1,249 @@ +--- +title: "Data Access Object Pattern in Java: Streamlining Database Interaction" +shortTitle: Data Access Object (DAO) +description: "Explore the Java Data Access Object (DAO) pattern to effectively separate business logic from database operations. Learn implementation strategies, real-world examples, and best practices." +category: Structural +language: en +tag: + - Abstraction + - Data access + - Data processing + - Decoupling + - Layered architecture + - Persistence +--- + +## Also known as + +* Data Access Layer +* DAO + +## Intent of Data Access Object Design Pattern + +The Data Access Object (DAO) design pattern aims to separate the application's business logic from the persistence layer, typically a database or any other storage mechanism. By using DAOs, the application can access and manipulate data without being dependent on the specific database implementation details. + +## Detailed Explanation of Data Access Object Pattern with Real-World Examples + +Real-world example + +> Imagine a library system where the main application manages book loans, user accounts, and inventory. The Data Access Object (DAO) pattern in this context would be used to separate the database operations (such as fetching book details, updating user records, and checking inventory) from the business logic of managing loans and accounts. For instance, there would be a `BookDAO` class responsible for all database interactions related to books, such as retrieving a book by its ISBN or updating its availability status. This abstraction allows the library system's main application code to focus on business rules and workflows, while the `BookDAO` handles the complex SQL queries and data management. This separation makes the system easier to maintain and test, as changes to the data source or business logic can be managed independently. + +In plain words + +> DAO is an interface we provide over the base persistence mechanism. + +Wikipedia says + +> In computer software, a data access object (DAO) is a pattern that provides an abstract interface to some type of database or other persistence mechanism. + +Sequence diagram + +![Data Access Object sequence diagram](./etc/dao-sequence-diagram.png) + +## Programmatic Example of DAO Pattern in Java + +There's a set of customers that need to be persisted to database. Additionally, we need the whole set of CRUD (create/read/update/delete) operations, so we can operate on customers easily. + +Walking through our customers example, here's the basic `Customer` entity. + +```java +@Setter +@Getter +@ToString +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@AllArgsConstructor +public class Customer { + + @EqualsAndHashCode.Include + private int id; + private String firstName; + private String lastName; +} +``` + +Here's the `CustomerDao` interface and two different implementations for it. `InMemoryCustomerDao` keeps a simple map of customers in memory while `DBCustomerDao` is the real RDBMS implementation. + +```java +public interface CustomerDao { + + Stream getAll() throws Exception; + + Optional getById(int id) throws Exception; + + boolean add(Customer customer) throws Exception; + + boolean update(Customer customer) throws Exception; + + boolean delete(Customer customer) throws Exception; +} + +public class InMemoryCustomerDao implements CustomerDao { + + private final Map idToCustomer = new HashMap<>(); + + // implement the interface using the map +} + +@Slf4j +@RequiredArgsConstructor +public class DbCustomerDao implements CustomerDao { + + private final DataSource dataSource; + + // implement the interface using the data source +} +``` + +Finally, here's how we use our DAO to manage customers. + +```java + +@Slf4j +public class App { + private static final String DB_URL = "jdbc:h2:mem:dao;DB_CLOSE_DELAY=-1"; + private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): "; + + public static void main(final String[] args) throws Exception { + final var inMemoryDao = new InMemoryCustomerDao(); + performOperationsUsing(inMemoryDao); + + final var dataSource = createDataSource(); + createSchema(dataSource); + final var dbDao = new DbCustomerDao(dataSource); + performOperationsUsing(dbDao); + deleteSchema(dataSource); + } + + private static void deleteSchema(DataSource dataSource) throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); + } + } + + private static void createSchema(DataSource dataSource) throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); + } + } + + private static DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + return dataSource; + } + + private static void performOperationsUsing(final CustomerDao customerDao) throws Exception { + addCustomers(customerDao); + LOGGER.info(ALL_CUSTOMERS); + try (var customerStream = customerDao.getAll()) { + customerStream.forEach(customer -> LOGGER.info(customer.toString())); + } + LOGGER.info("customerDao.getCustomerById(2): " + customerDao.getById(2)); + final var customer = new Customer(4, "Dan", "Danson"); + customerDao.add(customer); + LOGGER.info(ALL_CUSTOMERS + customerDao.getAll()); + customer.setFirstName("Daniel"); + customer.setLastName("Danielson"); + customerDao.update(customer); + LOGGER.info(ALL_CUSTOMERS); + try (var customerStream = customerDao.getAll()) { + customerStream.forEach(cust -> LOGGER.info(cust.toString())); + } + customerDao.delete(customer); + LOGGER.info(ALL_CUSTOMERS + customerDao.getAll()); + } + + private static void addCustomers(CustomerDao customerDao) throws Exception { + for (var customer : generateSampleCustomers()) { + customerDao.add(customer); + } + } + + public static List generateSampleCustomers() { + final var customer1 = new Customer(1, "Adam", "Adamson"); + final var customer2 = new Customer(2, "Bob", "Bobson"); + final var customer3 = new Customer(3, "Carl", "Carlson"); + return List.of(customer1, customer2, customer3); + } +} +``` + +The program output: + +``` +10:02:09.788 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): +10:02:09.793 [main] INFO com.iluwatar.dao.App -- Customer(id=1, firstName=Adam, lastName=Adamson) +10:02:09.793 [main] INFO com.iluwatar.dao.App -- Customer(id=2, firstName=Bob, lastName=Bobson) +10:02:09.793 [main] INFO com.iluwatar.dao.App -- Customer(id=3, firstName=Carl, lastName=Carlson) +10:02:09.794 [main] INFO com.iluwatar.dao.App -- customerDao.getCustomerById(2): Optional[Customer(id=2, firstName=Bob, lastName=Bobson)] +10:02:09.794 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@4c3e4790 +10:02:09.794 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): +10:02:09.795 [main] INFO com.iluwatar.dao.App -- Customer(id=1, firstName=Adam, lastName=Adamson) +10:02:09.795 [main] INFO com.iluwatar.dao.App -- Customer(id=2, firstName=Bob, lastName=Bobson) +10:02:09.795 [main] INFO com.iluwatar.dao.App -- Customer(id=3, firstName=Carl, lastName=Carlson) +10:02:09.795 [main] INFO com.iluwatar.dao.App -- Customer(id=4, firstName=Daniel, lastName=Danielson) +10:02:09.795 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@5679c6c6 +10:02:09.894 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): +10:02:09.895 [main] INFO com.iluwatar.dao.App -- Customer(id=1, firstName=Adam, lastName=Adamson) +10:02:09.895 [main] INFO com.iluwatar.dao.App -- Customer(id=2, firstName=Bob, lastName=Bobson) +10:02:09.895 [main] INFO com.iluwatar.dao.App -- Customer(id=3, firstName=Carl, lastName=Carlson) +10:02:09.895 [main] INFO com.iluwatar.dao.App -- customerDao.getCustomerById(2): Optional[Customer(id=2, firstName=Bob, lastName=Bobson)] +10:02:09.896 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@23282c25 +10:02:09.897 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): +10:02:09.897 [main] INFO com.iluwatar.dao.App -- Customer(id=1, firstName=Adam, lastName=Adamson) +10:02:09.897 [main] INFO com.iluwatar.dao.App -- Customer(id=2, firstName=Bob, lastName=Bobson) +10:02:09.898 [main] INFO com.iluwatar.dao.App -- Customer(id=3, firstName=Carl, lastName=Carlson) +10:02:09.898 [main] INFO com.iluwatar.dao.App -- Customer(id=4, firstName=Daniel, lastName=Danielson) +10:02:09.898 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@f2f2cc1 +``` + +## When to Use the Data Access Object Pattern in Java + +Use the Data Access Object in any of the following situations: + +* There is a need to abstract and encapsulate all access to the data source. +* The application needs to support multiple types of databases or storage mechanisms without significant code changes. +* You want to keep the database access clean and simple, and separate from business logic. + +## Data Access Object Pattern Java Tutorials + +* [The DAO Pattern in Java(Baeldung)](https://www.baeldung.com/java-dao-pattern) +* [Data Access Object Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm) + +## Real-World Applications of DAO Pattern in Java + +* Enterprise applications that require database interaction. +* Applications requiring data access to be adaptable to multiple storage types (relational databases, XML files, flat files, etc.). +* Frameworks providing generic data access functionalities. + +## Benefits and Trade-offs of Data Access Object Pattern + +Benefits: + +* Decoupling: Separates the data access logic from the business logic, enhancing modularity and clarity. +* Reusability: DAOs can be reused across different parts of the application or even in different projects. +* Testability: Simplifies testing by allowing business logic to be tested separately from the data access logic. +* Flexibility: Makes it easier to switch underlying storage mechanisms with minimal impact on the application code. + +Trade-offs: + +* Layer Complexity: Introduces additional layers to the application, which can increase complexity and development time. +* Overhead: For simple applications, the DAO pattern might introduce more overhead than necessary. +* Learning Curve: Developers might need time to understand and implement the pattern effectively, especially in complex projects. + +## Related Java Design Patterns + +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Helps in abstracting the creation of DAOs, especially when supporting multiple databases or storage mechanisms. +* [Factory](https://java-design-patterns.com/patterns/factory/): Can be used to instantiate DAOs dynamically, providing flexibility in the choice of implementation. +* [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Often used in conjunction with the DAO pattern to define application's boundaries and its set of available operations. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Might be employed to change the data access strategy at runtime, depending on the context. + +## References and Credits + +* [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/49u3r91) +* [Expert One-on-One J2EE Design and Development](https://amzn.to/3vK3pfq) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3U5cxEI) +* [Professional Java Development with the Spring Framework](https://amzn.to/49tANF0) diff --git a/data-access-object/etc/dao-sequence-diagram.png b/data-access-object/etc/dao-sequence-diagram.png new file mode 100644 index 000000000000..74488bd78107 Binary files /dev/null and b/data-access-object/etc/dao-sequence-diagram.png differ diff --git a/dao/etc/dao.png b/data-access-object/etc/dao.png similarity index 100% rename from dao/etc/dao.png rename to data-access-object/etc/dao.png diff --git a/dao/etc/dao.ucls b/data-access-object/etc/dao.ucls similarity index 100% rename from dao/etc/dao.ucls rename to data-access-object/etc/dao.ucls diff --git a/data-access-object/etc/dao.urm.puml b/data-access-object/etc/dao.urm.puml new file mode 100644 index 000000000000..12dfd5e51215 --- /dev/null +++ b/data-access-object/etc/dao.urm.puml @@ -0,0 +1,68 @@ +@startuml +package com.iluwatar.dao { + class App { + - ALL_CUSTOMERS : String {static} + - DB_URL : String {static} + - log : Logger {static} + + App() + - addCustomers(customerDao : CustomerDao) {static} + - createDataSource() : DataSource {static} + - createSchema(dataSource : DataSource) {static} + - deleteSchema(dataSource : DataSource) {static} + + generateSampleCustomers() : List {static} + + main(args : String[]) {static} + - performOperationsUsing(customerDao : CustomerDao) {static} + } + class Customer { + - firstName : String + - id : int + - lastName : String + + Customer(id : int, firstName : String, lastName : String) + + equals(that : Object) : boolean + + getFirstName() : String + + getId() : int + + getLastName() : String + + hashCode() : int + + setFirstName(firstName : String) + + setId(id : int) + + setLastName(lastName : String) + + toString() : String + } + interface CustomerDao { + + add(Customer) : boolean {abstract} + + delete(Customer) : boolean {abstract} + + getAll() : Stream {abstract} + + getById(int) : Optional {abstract} + + update(Customer) : boolean {abstract} + } + class CustomerSchemaSql { + + CREATE_SCHEMA_SQL : String {static} + + DELETE_SCHEMA_SQL : String {static} + - CustomerSchemaSql() + } + class DbCustomerDao { + - LOGGER : Logger {static} + - dataSource : DataSource + + DbCustomerDao(dataSource : DataSource) + + add(customer : Customer) : boolean + - createCustomer(resultSet : ResultSet) : Customer + + delete(customer : Customer) : boolean + + getAll() : Stream + + getById(id : int) : Optional + - getConnection() : Connection + - mutedClose(connection : Connection, statement : PreparedStatement, resultSet : ResultSet) + + update(customer : Customer) : boolean + } + class InMemoryCustomerDao { + - idToCustomer : Map + + InMemoryCustomerDao() + + add(customer : Customer) : boolean + + delete(customer : Customer) : boolean + + getAll() : Stream + + getById(id : int) : Optional + + update(customer : Customer) : boolean + } +} +DbCustomerDao ..|> CustomerDao +InMemoryCustomerDao ..|> CustomerDao +@enduml \ No newline at end of file diff --git a/data-access-object/etc/data-access-object.urm.puml b/data-access-object/etc/data-access-object.urm.puml new file mode 100644 index 000000000000..5c6e5f703053 --- /dev/null +++ b/data-access-object/etc/data-access-object.urm.puml @@ -0,0 +1,69 @@ +@startuml +package com.iluwatar.dao { + class App { + - ALL_CUSTOMERS : String {static} + - DB_URL : String {static} + - LOGGER : Logger {static} + + App() + - addCustomers(customerDao : CustomerDao) {static} + - createDataSource() : DataSource {static} + - createSchema(dataSource : DataSource) {static} + - deleteSchema(dataSource : DataSource) {static} + + generateSampleCustomers() : List {static} + + main(args : String[]) {static} + - performOperationsUsing(customerDao : CustomerDao) {static} + } + class Customer { + - firstName : String + - id : int + - lastName : String + + Customer(id : int, firstName : String, lastName : String) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getFirstName() : String + + getId() : int + + getLastName() : String + + hashCode() : int + + setFirstName(firstName : String) + + setId(id : int) + + setLastName(lastName : String) + + toString() : String + } + interface CustomerDao { + + add(Customer) : boolean {abstract} + + delete(Customer) : boolean {abstract} + + getAll() : Stream {abstract} + + getById(int) : Optional {abstract} + + update(Customer) : boolean {abstract} + } + class CustomerSchemaSql { + + CREATE_SCHEMA_SQL : String {static} + + DELETE_SCHEMA_SQL : String {static} + - CustomerSchemaSql() + } + class DbCustomerDao { + - LOGGER : Logger {static} + - dataSource : DataSource + + DbCustomerDao(dataSource : DataSource) + + add(customer : Customer) : boolean + - createCustomer(resultSet : ResultSet) : Customer + + delete(customer : Customer) : boolean + + getAll() : Stream + + getById(id : int) : Optional + - getConnection() : Connection + - mutedClose(connection : Connection, statement : PreparedStatement, resultSet : ResultSet) + + update(customer : Customer) : boolean + } + class InMemoryCustomerDao { + - idToCustomer : Map + + InMemoryCustomerDao() + + add(customer : Customer) : boolean + + delete(customer : Customer) : boolean + + getAll() : Stream + + getById(id : int) : Optional + + update(customer : Customer) : boolean + } +} +DbCustomerDao ..|> CustomerDao +InMemoryCustomerDao ..|> CustomerDao +@enduml \ No newline at end of file diff --git a/data-access-object/pom.xml b/data-access-object/pom.xml new file mode 100644 index 000000000000..f96bf54cd818 --- /dev/null +++ b/data-access-object/pom.xml @@ -0,0 +1,79 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + data-access-object + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + com.h2database + h2 + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.dao.App + + + + + + + + + diff --git a/data-access-object/src/main/java/com/iluwatar/dao/App.java b/data-access-object/src/main/java/com/iluwatar/dao/App.java new file mode 100644 index 000000000000..106b7458c9cf --- /dev/null +++ b/data-access-object/src/main/java/com/iluwatar/dao/App.java @@ -0,0 +1,125 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dao; + +import java.sql.SQLException; +import java.util.List; +import javax.sql.DataSource; +import lombok.extern.slf4j.Slf4j; +import org.h2.jdbcx.JdbcDataSource; + +/** + * Data Access Object (DAO) is an object that provides an abstract interface to some type of + * database or other persistence mechanism. By mapping application calls to the persistence layer, + * DAO provide some specific data operations without exposing details of the database. This + * isolation supports the Single responsibility principle. It separates what data accesses the + * application needs, in terms of domain-specific objects and data types (the public interface of + * the DAO), from how these needs can be satisfied with a specific DBMS. + * + *

    With the DAO pattern, we can use various method calls to retrieve/add/delete/update data + * without directly interacting with the data source. The below example demonstrates basic CRUD + * operations: select, add, update, and delete. + */ +@Slf4j +public class App { + private static final String DB_URL = "jdbc:h2:mem:dao;DB_CLOSE_DELAY=-1"; + private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): "; + + /** + * Program entry point. + * + * @param args command line args. + * @throws Exception if any error occurs. + */ + public static void main(final String[] args) throws Exception { + final var inMemoryDao = new InMemoryCustomerDao(); + performOperationsUsing(inMemoryDao); + + final var dataSource = createDataSource(); + createSchema(dataSource); + final var dbDao = new DbCustomerDao(dataSource); + performOperationsUsing(dbDao); + deleteSchema(dataSource); + } + + private static void deleteSchema(DataSource dataSource) throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); + } + } + + private static void createSchema(DataSource dataSource) throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); + } + } + + private static DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + return dataSource; + } + + private static void performOperationsUsing(final CustomerDao customerDao) throws Exception { + addCustomers(customerDao); + LOGGER.info(ALL_CUSTOMERS); + try (var customerStream = customerDao.getAll()) { + customerStream.forEach(customer -> LOGGER.info(customer.toString())); + } + LOGGER.info("customerDao.getCustomerById(2): " + customerDao.getById(2)); + final var customer = new Customer(4, "Dan", "Danson"); + customerDao.add(customer); + LOGGER.info(ALL_CUSTOMERS + customerDao.getAll()); + customer.setFirstName("Daniel"); + customer.setLastName("Danielson"); + customerDao.update(customer); + LOGGER.info(ALL_CUSTOMERS); + try (var customerStream = customerDao.getAll()) { + customerStream.forEach(cust -> LOGGER.info(cust.toString())); + } + customerDao.delete(customer); + LOGGER.info(ALL_CUSTOMERS + customerDao.getAll()); + } + + private static void addCustomers(CustomerDao customerDao) throws Exception { + for (var customer : generateSampleCustomers()) { + customerDao.add(customer); + } + } + + /** + * Generate customers. + * + * @return list of customers. + */ + public static List generateSampleCustomers() { + final var customer1 = new Customer(1, "Adam", "Adamson"); + final var customer2 = new Customer(2, "Bob", "Bobson"); + final var customer3 = new Customer(3, "Carl", "Carlson"); + return List.of(customer1, customer2, customer3); + } +} diff --git a/dao/src/main/java/com/iluwatar/dao/CustomException.java b/data-access-object/src/main/java/com/iluwatar/dao/CustomException.java similarity index 81% rename from dao/src/main/java/com/iluwatar/dao/CustomException.java rename to data-access-object/src/main/java/com/iluwatar/dao/CustomException.java index fd291b605392..79470bd810ab 100644 --- a/dao/src/main/java/com/iluwatar/dao/CustomException.java +++ b/data-access-object/src/main/java/com/iluwatar/dao/CustomException.java @@ -1,43 +1,37 @@ -/** - * 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.dao; - -/** - * - * Custom exception - * - */ -public class CustomException extends Exception { - - private static final long serialVersionUID = 1L; - - public CustomException() {} - - public CustomException(String message) { - super(message); - } - - public CustomException(String message, Throwable cause) { - super(message, cause); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dao; + +import java.io.Serial; + +/** Custom exception. */ +public class CustomException extends Exception { + + @Serial private static final long serialVersionUID = 1L; + + public CustomException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/data-access-object/src/main/java/com/iluwatar/dao/Customer.java b/data-access-object/src/main/java/com/iluwatar/dao/Customer.java new file mode 100644 index 000000000000..17a15fc1b92f --- /dev/null +++ b/data-access-object/src/main/java/com/iluwatar/dao/Customer.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dao; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** A customer POJO that represents the data that will be read from the data source. */ +@Setter +@Getter +@ToString +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@AllArgsConstructor +public class Customer { + + @EqualsAndHashCode.Include private int id; + private String firstName; + private String lastName; +} diff --git a/data-access-object/src/main/java/com/iluwatar/dao/CustomerDao.java b/data-access-object/src/main/java/com/iluwatar/dao/CustomerDao.java new file mode 100644 index 000000000000..5bb9ca2af97b --- /dev/null +++ b/data-access-object/src/main/java/com/iluwatar/dao/CustomerDao.java @@ -0,0 +1,92 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dao; + +import java.util.Optional; +import java.util.stream.Stream; + +/** + * In an application the Data Access Object (DAO) is a part of Data access layer. It is an object + * that provides an interface to some type of persistence mechanism. By mapping application calls to + * the persistence layer, DAO provides some specific data operations without exposing details of the + * database. This isolation supports the Single responsibility principle. It separates what data + * accesses the application needs, in terms of domain-specific objects and data types (the public + * interface of the DAO), from how these needs can be satisfied with a specific DBMS, database + * schema, etc. + * + *

    Any change in the way data is stored and retrieved will not change the client code as the + * client will be using interface and need not worry about exact source. + * + * @see InMemoryCustomerDao + * @see DbCustomerDao + */ +public interface CustomerDao { + + /** + * Get all customers. + * + * @return all the customers as a stream. The stream may be lazily or eagerly evaluated based on + * the implementation. The stream must be closed after use. + * @throws Exception if any error occurs. + */ + Stream getAll() throws Exception; + + /** + * Get customer as Optional by id. + * + * @param id unique identifier of the customer. + * @return an optional with customer if a customer with unique identifier id exists, + * empty optional otherwise. + * @throws Exception if any error occurs. + */ + Optional getById(int id) throws Exception; + + /** + * Add a customer. + * + * @param customer the customer to be added. + * @return true if customer is successfully added, false if customer already exists. + * @throws Exception if any error occurs. + */ + boolean add(Customer customer) throws Exception; + + /** + * Update a customer. + * + * @param customer the customer to be updated. + * @return true if customer exists and is successfully updated, false otherwise. + * @throws Exception if any error occurs. + */ + boolean update(Customer customer) throws Exception; + + /** + * Delete a customer. + * + * @param customer the customer to be deleted. + * @return true if customer exists and is successfully deleted, false otherwise. + * @throws Exception if any error occurs. + */ + boolean delete(Customer customer) throws Exception; +} diff --git a/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java b/data-access-object/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java similarity index 77% rename from dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java rename to data-access-object/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java index cce967dc8939..aab41423a748 100644 --- a/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java +++ b/data-access-object/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,16 +24,13 @@ */ package com.iluwatar.dao; -/** - * Customer Schema SQL Class - */ +/** Customer Schema SQL Class. */ public final class CustomerSchemaSql { private CustomerSchemaSql() {} - public static final String CREATE_SCHEMA_SQL = "CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), " - + "LNAME VARCHAR(100))"; + public static final String CREATE_SCHEMA_SQL = + "CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), " + "LNAME VARCHAR(100))"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE CUSTOMERS"; - } diff --git a/data-access-object/src/main/java/com/iluwatar/dao/DbCustomerDao.java b/data-access-object/src/main/java/com/iluwatar/dao/DbCustomerDao.java new file mode 100644 index 000000000000..cb75b195ddc4 --- /dev/null +++ b/data-access-object/src/main/java/com/iluwatar/dao/DbCustomerDao.java @@ -0,0 +1,173 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dao; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Optional; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Consumer; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; +import javax.sql.DataSource; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** An implementation of {@link CustomerDao} that persists customers in RDBMS. */ +@Slf4j +@RequiredArgsConstructor +public class DbCustomerDao implements CustomerDao { + + private final DataSource dataSource; + + /** + * Get all customers as Java Stream. + * + * @return a lazily populated stream of customers. Note the stream returned must be closed to free + * all the acquired resources. The stream keeps an open connection to the database till it is + * complete or is closed manually. + */ + @Override + public Stream getAll() throws Exception { + try { + var connection = getConnection(); + var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR + var resultSet = statement.executeQuery(); // NOSONAR + return StreamSupport.stream( + new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { + + @Override + public boolean tryAdvance(Consumer action) { + try { + if (!resultSet.next()) { + return false; + } + action.accept(createCustomer(resultSet)); + return true; + } catch (SQLException e) { + throw new RuntimeException(e); // NOSONAR + } + } + }, + false) + .onClose(() -> mutedClose(connection, statement, resultSet)); + } catch (SQLException e) { + throw new CustomException(e.getMessage(), e); + } + } + + private Connection getConnection() throws SQLException { + return dataSource.getConnection(); + } + + private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) { + try { + resultSet.close(); + statement.close(); + connection.close(); + } catch (SQLException e) { + LOGGER.info("Exception thrown " + e.getMessage()); + } + } + + private Customer createCustomer(ResultSet resultSet) throws SQLException { + return new Customer( + resultSet.getInt("ID"), resultSet.getString("FNAME"), resultSet.getString("LNAME")); + } + + /** {@inheritDoc} */ + @Override + public Optional getById(int id) throws Exception { + + ResultSet resultSet = null; + + try (var connection = getConnection(); + var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) { + + statement.setInt(1, id); + resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(createCustomer(resultSet)); + } else { + return Optional.empty(); + } + } catch (SQLException ex) { + throw new CustomException(ex.getMessage(), ex); + } finally { + if (resultSet != null) { + resultSet.close(); + } + } + } + + /** {@inheritDoc} */ + @Override + public boolean add(Customer customer) throws Exception { + if (getById(customer.getId()).isPresent()) { + return false; + } + + try (var connection = getConnection(); + var statement = connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) { + statement.setInt(1, customer.getId()); + statement.setString(2, customer.getFirstName()); + statement.setString(3, customer.getLastName()); + statement.execute(); + return true; + } catch (SQLException ex) { + throw new CustomException(ex.getMessage(), ex); + } + } + + /** {@inheritDoc} */ + @Override + public boolean update(Customer customer) throws Exception { + try (var connection = getConnection(); + var statement = + connection.prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) { + statement.setString(1, customer.getFirstName()); + statement.setString(2, customer.getLastName()); + statement.setInt(3, customer.getId()); + return statement.executeUpdate() > 0; + } catch (SQLException ex) { + throw new CustomException(ex.getMessage(), ex); + } + } + + /** {@inheritDoc} */ + @Override + public boolean delete(Customer customer) throws Exception { + try (var connection = getConnection(); + var statement = connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) { + statement.setInt(1, customer.getId()); + return statement.executeUpdate() > 0; + } catch (SQLException ex) { + throw new CustomException(ex.getMessage(), ex); + } + } +} diff --git a/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java b/data-access-object/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java similarity index 83% rename from dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java rename to data-access-object/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java index 947da23ca4a0..b5b7eb0c4ff7 100644 --- a/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java +++ b/data-access-object/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,7 +22,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.dao; import java.util.HashMap; @@ -29,18 +30,15 @@ import java.util.stream.Stream; /** - * An in memory implementation of {@link CustomerDao}, which stores the customers in JVM memory - * and data is lost when the application exits. - *
    + * An in memory implementation of {@link CustomerDao}, which stores the customers in JVM memory and + * data is lost when the application exits.
    * This implementation is useful as temporary database or for testing. */ public class InMemoryCustomerDao implements CustomerDao { - private Map idToCustomer = new HashMap<>(); + private final Map idToCustomer = new HashMap<>(); - /** - * An eagerly evaluated stream of customers stored in memory. - */ + /** An eagerly evaluated stream of customers stored in memory. */ @Override public Stream getAll() { return idToCustomer.values().stream(); @@ -56,7 +54,7 @@ public boolean add(final Customer customer) { if (getById(customer.getId()).isPresent()) { return false; } - + idToCustomer.put(customer.getId(), customer); return true; } diff --git a/data-access-object/src/test/java/com/iluwatar/dao/AppTest.java b/data-access-object/src/test/java/com/iluwatar/dao/AppTest.java new file mode 100644 index 000000000000..a43f37353341 --- /dev/null +++ b/data-access-object/src/test/java/com/iluwatar/dao/AppTest.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dao; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Tests that DAO example runs without errors. */ +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ + @Test + void shouldExecuteDaoWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/data-access-object/src/test/java/com/iluwatar/dao/CustomerTest.java b/data-access-object/src/test/java/com/iluwatar/dao/CustomerTest.java new file mode 100644 index 000000000000..f53c28935fea --- /dev/null +++ b/data-access-object/src/test/java/com/iluwatar/dao/CustomerTest.java @@ -0,0 +1,96 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dao; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Tests {@link Customer}. */ +class CustomerTest { + + private Customer customer; + private static final int ID = 1; + private static final String FIRSTNAME = "Winston"; + private static final String LASTNAME = "Churchill"; + + @BeforeEach + void setUp() { + customer = new Customer(ID, FIRSTNAME, LASTNAME); + } + + @Test + void getAndSetId() { + final var newId = 2; + customer.setId(newId); + assertEquals(newId, customer.getId()); + } + + @Test + void getAndSetFirstname() { + final var newFirstname = "Bill"; + customer.setFirstName(newFirstname); + assertEquals(newFirstname, customer.getFirstName()); + } + + @Test + void getAndSetLastname() { + final var newLastname = "Clinton"; + customer.setLastName(newLastname); + assertEquals(newLastname, customer.getLastName()); + } + + @Test + void notEqualWithDifferentId() { + final var newId = 2; + final var otherCustomer = new Customer(newId, FIRSTNAME, LASTNAME); + assertNotEquals(customer, otherCustomer); + assertNotEquals(customer.hashCode(), otherCustomer.hashCode()); + } + + @Test + void equalsWithSameObjectValues() { + final var otherCustomer = new Customer(ID, FIRSTNAME, LASTNAME); + assertEquals(customer, otherCustomer); + assertEquals(customer.hashCode(), otherCustomer.hashCode()); + } + + @Test + void equalsWithSameObjects() { + assertEquals(customer, customer); + assertEquals(customer.hashCode(), customer.hashCode()); + } + + @Test + void testToString() { + assertEquals( + String.format( + "Customer(id=%s, firstName=%s, lastName=%s)", + customer.getId(), customer.getFirstName(), customer.getLastName()), + customer.toString()); + } +} diff --git a/data-access-object/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java b/data-access-object/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java new file mode 100644 index 000000000000..2f116d108519 --- /dev/null +++ b/data-access-object/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java @@ -0,0 +1,260 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dao; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import javax.sql.DataSource; +import org.h2.jdbcx.JdbcDataSource; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +/** Tests {@link DbCustomerDao}. */ +class DbCustomerDaoTest { + + private static final String DB_URL = "jdbc:h2:mem:dao;DB_CLOSE_DELAY=-1"; + private DbCustomerDao dao; + private final Customer existingCustomer = new Customer(1, "Freddy", "Krueger"); + + /** + * Creates customers schema. + * + * @throws SQLException if there is any error while creating schema. + */ + @BeforeEach + void createSchema() throws SQLException { + try (var connection = DriverManager.getConnection(DB_URL); + var statement = connection.createStatement()) { + statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); + } + } + + /** Represents the scenario where DB connectivity is present. */ + @Nested + class ConnectionSuccess { + + /** + * Setup for connection success scenario. + * + * @throws Exception if any error occurs. + */ + @BeforeEach + void setUp() throws Exception { + var dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + dao = new DbCustomerDao(dataSource); + var result = dao.add(existingCustomer); + assertTrue(result); + } + + /** + * Represents the scenario when DAO operations are being performed on a non-existing customer. + */ + @Nested + class NonExistingCustomer { + + @Test + void addingShouldResultInSuccess() throws Exception { + try (var allCustomers = dao.getAll()) { + assumeTrue(allCustomers.count() == 1); + } + + final var nonExistingCustomer = new Customer(2, "Robert", "Englund"); + var result = dao.add(nonExistingCustomer); + assertTrue(result); + + assertCustomerCountIs(2); + assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get()); + } + + @Test + void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final var nonExistingCustomer = new Customer(2, "Robert", "Englund"); + var result = dao.delete(nonExistingCustomer); + + assertFalse(result); + assertCustomerCountIs(1); + } + + @Test + void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final var nonExistingId = getNonExistingCustomerId(); + final var newFirstname = "Douglas"; + final var newLastname = "MacArthur"; + final var customer = new Customer(nonExistingId, newFirstname, newLastname); + var result = dao.update(customer); + + assertFalse(result); + assertFalse(dao.getById(nonExistingId).isPresent()); + } + + @Test + void retrieveShouldReturnNoCustomer() throws Exception { + assertFalse(dao.getById(getNonExistingCustomerId()).isPresent()); + } + } + + /** + * Represents a scenario where DAO operations are being performed on an already existing + * customer. + */ + @Nested + class ExistingCustomer { + + @Test + void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { + var existingCustomer = new Customer(1, "Freddy", "Krueger"); + var result = dao.add(existingCustomer); + + assertFalse(result); + assertCustomerCountIs(1); + assertEquals(existingCustomer, dao.getById(existingCustomer.getId()).get()); + } + + @Test + void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { + var result = dao.delete(existingCustomer); + + assertTrue(result); + assertCustomerCountIs(0); + assertFalse(dao.getById(existingCustomer.getId()).isPresent()); + } + + @Test + void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() + throws Exception { + final var newFirstname = "Bernard"; + final var newLastname = "Montgomery"; + final var customer = new Customer(existingCustomer.getId(), newFirstname, newLastname); + var result = dao.update(customer); + + assertTrue(result); + + final var cust = dao.getById(existingCustomer.getId()).get(); + assertEquals(newFirstname, cust.getFirstName()); + assertEquals(newLastname, cust.getLastName()); + } + } + } + + /** + * Represents a scenario where DB connectivity is not present due to network issue, or DB service + * unavailable. + */ + @Nested + class ConnectivityIssue { + + private static final String EXCEPTION_CAUSE = "Connection not available"; + + /** + * setup a connection failure scenario. + * + * @throws SQLException if any error occurs. + */ + @BeforeEach + void setUp() throws SQLException { + dao = new DbCustomerDao(mockedDatasource()); + } + + private DataSource mockedDatasource() throws SQLException { + var mockedDataSource = mock(DataSource.class); + var mockedConnection = mock(Connection.class); + var exception = new SQLException(EXCEPTION_CAUSE); + doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString()); + doReturn(mockedConnection).when(mockedDataSource).getConnection(); + return mockedDataSource; + } + + @Test + void addingACustomerFailsWithExceptionAsFeedbackToClient() { + assertThrows(Exception.class, () -> dao.add(new Customer(2, "Bernard", "Montgomery"))); + } + + @Test + void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() { + assertThrows(Exception.class, () -> dao.delete(existingCustomer)); + } + + @Test + void updatingACustomerFailsWithFeedbackToTheClient() { + final var newFirstname = "Bernard"; + final var newLastname = "Montgomery"; + assertThrows( + Exception.class, + () -> dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname))); + } + + @Test + void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() { + assertThrows(Exception.class, () -> dao.getById(existingCustomer.getId())); + } + + @Test + void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() { + assertThrows(Exception.class, () -> dao.getAll()); + } + } + + /** + * Delete customer schema for fresh setup per test. + * + * @throws SQLException if any error occurs. + */ + @AfterEach + void deleteSchema() throws SQLException { + try (var connection = DriverManager.getConnection(DB_URL); + var statement = connection.createStatement()) { + statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); + } + } + + private void assertCustomerCountIs(int count) throws Exception { + try (var allCustomers = dao.getAll()) { + assertEquals(count, allCustomers.count()); + } + } + + /** + * An arbitrary number which does not correspond to an active Customer id. + * + * @return an int of a customer id which doesn't exist + */ + private int getNonExistingCustomerId() { + return 999; + } +} diff --git a/data-access-object/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java b/data-access-object/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java new file mode 100644 index 000000000000..93ce2475f2c8 --- /dev/null +++ b/data-access-object/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java @@ -0,0 +1,158 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dao; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +/** Tests {@link InMemoryCustomerDao}. */ +class InMemoryCustomerDaoTest { + + private InMemoryCustomerDao dao; + private static final Customer CUSTOMER = new Customer(1, "Freddy", "Krueger"); + + @BeforeEach + void setUp() { + dao = new InMemoryCustomerDao(); + assertTrue(dao.add(CUSTOMER)); + } + + /** + * Represents the scenario when the DAO operations are being performed on a non-existent customer. + */ + @Nested + class NonExistingCustomer { + + @Test + void addingShouldResultInSuccess() throws Exception { + try (var allCustomers = dao.getAll()) { + assumeTrue(allCustomers.count() == 1); + } + + final var nonExistingCustomer = new Customer(2, "Robert", "Englund"); + var result = dao.add(nonExistingCustomer); + assertTrue(result); + + assertCustomerCountIs(2); + assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get()); + } + + @Test + void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final var nonExistingCustomer = new Customer(2, "Robert", "Englund"); + var result = dao.delete(nonExistingCustomer); + + assertFalse(result); + assertCustomerCountIs(1); + } + + @Test + void updateShouldBeFailureAndNotAffectExistingCustomers() { + final var nonExistingId = getNonExistingCustomerId(); + final var newFirstname = "Douglas"; + final var newLastname = "MacArthur"; + final var customer = new Customer(nonExistingId, newFirstname, newLastname); + var result = dao.update(customer); + + assertFalse(result); + assertFalse(dao.getById(nonExistingId).isPresent()); + } + + @Test + void retrieveShouldReturnNoCustomer() throws Exception { + assertFalse(dao.getById(getNonExistingCustomerId()).isPresent()); + } + } + + /** + * Represents the scenario when the DAO operations are being performed on an already existing + * customer. + */ + @Nested + class ExistingCustomer { + + @Test + void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { + var result = dao.add(CUSTOMER); + + assertFalse(result); + assertCustomerCountIs(1); + assertEquals(CUSTOMER, dao.getById(CUSTOMER.getId()).get()); + } + + @Test + void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { + var result = dao.delete(CUSTOMER); + + assertTrue(result); + assertCustomerCountIs(0); + assertFalse(dao.getById(CUSTOMER.getId()).isPresent()); + } + + @Test + void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() + throws Exception { + final var newFirstname = "Bernard"; + final var newLastname = "Montgomery"; + final var customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname); + var result = dao.update(customer); + + assertTrue(result); + + final var cust = dao.getById(CUSTOMER.getId()).get(); + assertEquals(newFirstname, cust.getFirstName()); + assertEquals(newLastname, cust.getLastName()); + } + + @Test + void retriveShouldReturnTheCustomer() { + var optionalCustomer = dao.getById(CUSTOMER.getId()); + + assertTrue(optionalCustomer.isPresent()); + assertEquals(CUSTOMER, optionalCustomer.get()); + } + } + + /** + * An arbitrary number which does not correspond to an active Customer id. + * + * @return an int of a customer id which doesn't exist + */ + private int getNonExistingCustomerId() { + return 999; + } + + private void assertCustomerCountIs(int count) throws Exception { + try (var allCustomers = dao.getAll()) { + assertEquals(count, allCustomers.count()); + } + } +} diff --git a/data-bus/README.md b/data-bus/README.md index 257192e25234..ee687a52d1dd 100644 --- a/data-bus/README.md +++ b/data-bus/README.md @@ -1,33 +1,195 @@ --- -layout: pattern -title: Data Bus -folder: data-bus -permalink: /patterns/data-bus/ - -categories: Architectural -tags: - - Java - - Difficulty-Intermediate +title: "Data Bus Pattern in Java: Unifying Component Communication Efficiently" +shortTitle: Data Bus +description: "Explore the Data Bus pattern in Java for centralized communication and event handling. Learn how to decouple components, enhance scalability, and maintainability with practical examples and real-world applications." +category: Messaging +language: en +tag: + - Decoupling + - Event-driven + - Messaging + - Publish/subscribe + - Scalability --- -## Intent +## Also known as -Allows send of messages/events between components of an application -without them needing to know about each other. They only need to know -about the type of the message/event being sent. +* Event Bus +* Message Bus -![data bus pattern uml diagram](./etc/data-bus.urm.png "Data Bus pattern") +## Intent of Data Bus Design Pattern -## Applicability -Use Data Bus pattern when +The Data Bus design pattern aims to provide a centralized communication channel through which various components of a system can exchange data without being directly connected, thus promoting loose coupling and enhancing scalability and maintainability. -* you want your components to decide themselves which messages/events they want to receive -* you want to have many-to-many communication -* you want your components to know nothing about each other +## Detailed Explanation of Data Bus Pattern with Real-World Examples -## Related Patterns -Data Bus is similar to +Real-world example -* Mediator pattern with Data Bus Members deciding for themselves if they want to accept any given message -* Observer pattern but supporting many-to-many communication -* Publish/Subscribe pattern with the Data Bus decoupling the publisher and the subscriber +> Consider a large airport as an analogous real-world example of the Data Bus pattern. In an airport, various airlines, passengers, baggage handlers, and security personnel all need to communicate and share information. Instead of each entity communicating directly with every other entity, the airport uses a centralized announcement system (the Data Bus). Flight information, security alerts, and other critical updates are broadcast over this system, and each entity listens for the messages relevant to them. This setup allows the airport to decouple the communication process, ensuring that each entity only receives the information they need, while allowing the system to scale and integrate new entities without disrupting the existing ones. This is similar to how the Data Bus pattern in Java promotes centralized communication and event handling, enhancing system scalability and maintainability. + +In plain words + +> Data Bus is a design pattern that connects components of an application for communication based on the type of message or event being transferred. This pattern promotes decoupling, making it easier to scale and maintain the system by allowing components to communicate without direct dependencies. + +Sequence diagram + +![Data Bus Sequence Diagram](./etc/data-bus-sequence-diagram.png) + +## Programmatic Example of Data Bus Pattern in Java + +Say you have an app that enables online bookings and participation in events. You want the app to send notifications, such as event advertisements, to all ordinary members of the community or organization holding the events. However, you do not want to send such advertisements to event administrators or organizers. Instead, you want to send them notifications about the timing of new advertisements sent to all members. The Data Bus enables you to selectively notify community members by type (ordinary members or event administrators) by making their classes or components only accept messages of a certain type. Thus, ordinary members and administrators do not need to know about each other or the specific classes or components used to notify the entire community, except for knowing the type of messages being sent. + +In the online events app example above, we first define our `Member` interface and its implementations: `MessageCollectorMember` (ordinary community members) and `StatusMember` (event administrators or organizers). + +```java +public interface Member extends Consumer { + + void accept(DataType event); +} +``` + +Next, we implement a data bus to subscribe or unsubscribe members and to publish events to notify all community members. + +```java +public class DataBus { + + private static final DataBus INSTANCE = new DataBus(); + + private final Set listeners = new HashSet<>(); + + public static DataBus getInstance() { + return INSTANCE; + } + + public void subscribe(final Member member) { + this.listeners.add(member); + } + + public void unsubscribe(final Member member) { + this.listeners.remove(member); + } + + public void publish(final DataType event) { + event.setDataBus(this); + + listeners.forEach( + listener -> listener.accept(event)); + } +} +``` + +The `accept` method is applied to each member in the `publish` method. + +For ordinary community members (`MessageCollectorMember`), the `accept` method can handle only `MessageData` type messages. + +```java +public class MessageCollectorMember implements Member { + + private final String name; + + private final List messages = new ArrayList<>(); + + public MessageCollectorMember(String name) { + this.name = name; + } + + @Override + public void accept(final DataType data) { + if (data instanceof MessageData) { + handleEvent((MessageData) data); + } + } +} +``` + +For event administrators or organizers (`StatusMember`), the `accept` method can handle `StartingData` and `StoppingData` type messages. + +```java +public class StatusMember implements Member { + + private final int id; + + private LocalDateTime started; + + private LocalDateTime stopped; + + public StatusMember(int id) { + this.id = id; + } + + @Override + public void accept(final DataType data) { + if (data instanceof StartingData) { + handleEvent((StartingData) data); + } else if (data instanceof StoppingData) { + handleEvent((StoppingData) data); + } + } +} +``` + +Here is the `App` class to demonstrate the Data Bus pattern in action: + +```java +class App { + + public static void main(String[] args) { + final var bus = DataBus.getInstance(); + bus.subscribe(new StatusMember(1)); + bus.subscribe(new StatusMember(2)); + final var foo = new MessageCollectorMember("Foo"); + final var bar = new MessageCollectorMember("Bar"); + bus.subscribe(foo); + bus.publish(StartingData.of(LocalDateTime.now())); + } +} +``` + +When the data bus publishes a message, the output is as follows: + +``` +02:33:57.627 [main] INFO com.iluwatar.databus.members.StatusMember - Receiver 2 sees application started at 2022-10-26T02:33:57.613529100 +02:33:57.633 [main] INFO com.iluwatar.databus.members.StatusMember - Receiver 1 sees application started at 2022-10-26T02:33:57.613529100 +``` + +As shown, `MessageCollectorMembers` only accept messages of type `MessageData`, so they do not see the `StartingData` or `StoppingData` messages, which are only visible to `StatusMember` (the event administrators or organizers). This selective message handling prevents ordinary community members from receiving administrative notifications. + +## When to Use the Data Bus Pattern in Java + +* When multiple components need to share data or events but direct coupling is undesirable. +* In complex, event-driven systems where the flow of information varies dynamically. +* In distributed systems where components might be deployed across different environments. +* In microservices architectures for inter-service communication. + +## Real-World Applications of Data Bus Pattern in Java + +* Event handling systems in large-scale applications. +* Microservices architectures for inter-service communication. +* Real-time data processing systems, such as stock trading platforms. +* In frameworks like Spring, particularly with its application event mechanism. + +## Benefits and Trade-offs of Data Bus Pattern + +Benefits: + +* Loose Coupling: Components can interact without having direct dependencies on each other. +* Flexibility: New subscribers or publishers can be added without impacting existing components. +* Scalability: The pattern supports scaling components independently. +* Reusability: The bus and components can be reused across different systems. + +Trade-offs: + +* Complexity: Introducing a data bus can add complexity to the system architecture. +* Performance Overhead: The additional layer of communication may introduce latency. +* Debugging Difficulty: Tracing data flow through the bus can be challenging, especially in systems with many events. + +## Related Java Design Patterns + +* [Mediator](https://java-design-patterns.com/patterns/mediator/): Facilitates communication between components, but unlike Data Bus, it centralizes control. +* [Observer](https://java-design-patterns.com/patterns/observer/): Similar in nature to the publish-subscribe mechanism used in Data Bus for notifying changes to multiple objects. +* Publish/Subscribe: The Data Bus pattern is often implemented using the publish-subscribe mechanism, where publishers post messages to the bus without knowledge of the subscribers. + +## References and Credits + +* [Enterprise Integration Patterns](https://amzn.to/3J6WoYS) +* [Pattern-Oriented Software Architecture, Volume 4: A Pattern Language for Distributed Computing](https://amzn.to/3PTRGBM) diff --git a/data-bus/etc/data-bus-sequence-diagram.png b/data-bus/etc/data-bus-sequence-diagram.png new file mode 100644 index 000000000000..8924693923d4 Binary files /dev/null and b/data-bus/etc/data-bus-sequence-diagram.png differ diff --git a/data-bus/etc/data-bus.urm.puml b/data-bus/etc/data-bus.urm.puml new file mode 100644 index 000000000000..8ca7f85efb11 --- /dev/null +++ b/data-bus/etc/data-bus.urm.puml @@ -0,0 +1,82 @@ +@startuml +package com.iluwatar.databus { + class AbstractDataType { + - dataBus : DataBus + + AbstractDataType() + + getDataBus() : DataBus + + setDataBus(dataBus : DataBus) + } + ~class App { + ~ App() + + main(args : String[]) {static} + } + class DataBus { + - INSTANCE : DataBus {static} + - listeners : Set + + DataBus() + + getInstance() : DataBus {static} + + publish(event : DataType) + + subscribe(member : Member) + + unsubscribe(member : Member) + } + interface DataType { + + getDataBus() : DataBus {abstract} + + setDataBus(DataBus) {abstract} + } + interface Member { + + accept(DataType) {abstract} + } +} +package com.iluwatar.databus.data { + class MessageData { + - message : String + + MessageData(message : String) + + getMessage() : String + + of(message : String) : DataType {static} + } + class StartingData { + - when : LocalDateTime + + StartingData(when : LocalDateTime) + + getWhen() : LocalDateTime + + of(when : LocalDateTime) : DataType {static} + } + class StoppingData { + - when : LocalDateTime + + StoppingData(when : LocalDateTime) + + getWhen() : LocalDateTime + + of(when : LocalDateTime) : DataType {static} + } +} +package com.iluwatar.databus.members { + class MessageCollectorMember { + - LOGGER : Logger {static} + - messages : List + - name : String + + MessageCollectorMember(name : String) + + accept(data : DataType) + + getMessages() : List + - handleEvent(data : MessageData) + } + class StatusMember { + - LOGGER : Logger {static} + - id : int + - started : LocalDateTime + - stopped : LocalDateTime + + StatusMember(id : int) + + accept(data : DataType) + + getStarted() : LocalDateTime + + getStopped() : LocalDateTime + - handleEvent(data : StartingData) + - handleEvent(data : StoppingData) + } +} +AbstractDataType --> "-dataBus" DataBus +DataBus --> "-INSTANCE" DataBus +DataBus --> "-listeners" Member +AbstractDataType ..|> DataType +MessageData --|> AbstractDataType +StartingData --|> AbstractDataType +StoppingData --|> AbstractDataType +MessageCollectorMember ..|> Member +StatusMember ..|> Member +@enduml \ No newline at end of file diff --git a/data-bus/pom.xml b/data-bus/pom.xml index 6292b71fbe62..ef7c88acb413 100644 --- a/data-bus/pom.xml +++ b/data-bus/pom.xml @@ -1,8 +1,10 @@ - + - - 4.0.0 - - 1.16.14 - - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - data-bus - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.mockito - mockito-core - test - - + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + data-bus + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.databus.App + + + + + + + + diff --git a/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java b/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java index d57e4a014fdc..aa1ce3d45598 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java +++ b/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -46,22 +48,13 @@ of this software and associated documentation files (the "Software"), to deal package com.iluwatar.databus; -/** - * Base for data to send via the Data-Bus. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ +import lombok.Getter; +import lombok.Setter; + +/** Base for data to send via the Data-Bus. */ +@Getter +@Setter public class AbstractDataType implements DataType { private DataBus dataBus; - - @Override - public DataBus getDataBus() { - return dataBus; - } - - @Override - public void setDataBus(DataBus dataBus) { - this.dataBus = dataBus; - } } diff --git a/data-bus/src/main/java/com/iluwatar/databus/App.java b/data-bus/src/main/java/com/iluwatar/databus/App.java index b599bdc57fac..2c1d6b5e8a25 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/App.java +++ b/data-bus/src/main/java/com/iluwatar/databus/App.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,7 +22,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.databus; import com.iluwatar.databus.data.MessageData; @@ -28,44 +29,40 @@ import com.iluwatar.databus.data.StoppingData; import com.iluwatar.databus.members.MessageCollectorMember; import com.iluwatar.databus.members.StatusMember; - import java.time.LocalDateTime; /** - * The Data Bus pattern - *

    - * @see http://wiki.c2.com/?DataBusPattern - *

    The Data-Bus pattern provides a method where different parts of an application may - * pass messages between each other without needing to be aware of the other's existence.

    - *

    Similar to the {@code ObserverPattern}, members register themselves with the {@link DataBus} - * and may then receive each piece of data that is published to the Data-Bus. The member - * may react to any given message or not.

    - *

    It allows for Many-to-Many distribution of data, as there may be any number of - * publishers to a Data-Bus, and any number of members receiving the data. All members - * will receive the same data, the order each receives a given piece of data, is an - * implementation detail.

    - *

    Members may unsubscribe from the Data-Bus to stop receiving data.

    - *

    This example of the pattern implements a Synchronous Data-Bus, meaning that - * when data is published to the Data-Bus, the publish method will not return until - * all members have received the data and returned.

    - *

    The {@link DataBus} class is a Singleton.

    - *

    Members of the Data-Bus must implement the {@link Member} interface.

    - *

    Data to be published via the Data-Bus must implement the {@link DataType} interface.

    - *

    The {@code data} package contains example {@link DataType} implementations.

    - *

    The {@code members} package contains example {@link Member} implementations.

    - *

    The {@link StatusMember} demonstrates using the DataBus to publish a message - * to the Data-Bus when it receives a message.

    + * The Data Bus pattern. * - * @author Paul Campbell (pcampbell@kemitix.net) + * @see http://wiki.c2.com/?DataBusPattern + *

    The Data-Bus pattern provides a method where different parts of an application may pass + * messages between each other without needing to be aware of the other's existence. + *

    Similar to the {@code ObserverPattern}, members register themselves with the {@link + * DataBus} and may then receive each piece of data that is published to the Data-Bus. The + * member may react to any given message or not. + *

    It allows for Many-to-Many distribution of data, as there may be any number of publishers + * to a Data-Bus, and any number of members receiving the data. All members will receive the + * same data, the order each receives a given piece of data, is an implementation detail. + *

    Members may unsubscribe from the Data-Bus to stop receiving data. + *

    This example of the pattern implements a Synchronous Data-Bus, meaning that when data is + * published to the Data-Bus, the publish method will not return until all members have received + * the data and returned. + *

    The {@link DataBus} class is a Singleton. + *

    Members of the Data-Bus must implement the {@link Member} interface. + *

    Data to be published via the Data-Bus must implement the {@link DataType} interface. + *

    The {@code data} package contains example {@link DataType} implementations. + *

    The {@code members} package contains example {@link Member} implementations. + *

    The {@link StatusMember} demonstrates using the DataBus to publish a message to the + * Data-Bus when it receives a message. */ class App { public static void main(String[] args) { - final DataBus bus = DataBus.getInstance(); + final var bus = DataBus.getInstance(); bus.subscribe(new StatusMember(1)); bus.subscribe(new StatusMember(2)); - final MessageCollectorMember foo = new MessageCollectorMember("Foo"); - final MessageCollectorMember bar = new MessageCollectorMember("Bar"); + final var foo = new MessageCollectorMember("Foo"); + final var bar = new MessageCollectorMember("Bar"); bus.subscribe(foo); bus.publish(StartingData.of(LocalDateTime.now())); bus.publish(MessageData.of("Only Foo should see this")); diff --git a/data-bus/src/main/java/com/iluwatar/databus/DataBus.java b/data-bus/src/main/java/com/iluwatar/databus/DataBus.java index edaefe623499..f302d741f776 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/DataBus.java +++ b/data-bus/src/main/java/com/iluwatar/databus/DataBus.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,7 +22,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.databus; import java.util.HashSet; @@ -29,9 +30,7 @@ /** * The Data-Bus implementation. * - *

    This implementation uses a Singleton.

    - * - * @author Paul Campbell (pcampbell@kemitix.net) + *

    This implementation uses a Singleton. */ public class DataBus { diff --git a/data-bus/src/main/java/com/iluwatar/databus/DataType.java b/data-bus/src/main/java/com/iluwatar/databus/DataType.java index a3dd328705ba..b84797bf03ea 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/DataType.java +++ b/data-bus/src/main/java/com/iluwatar/databus/DataType.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -46,12 +48,7 @@ of this software and associated documentation files (the "Software"), to deal package com.iluwatar.databus; -/** - * Events are sent via the Data-Bus. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ - +/** Events are sent via the Data-Bus. */ public interface DataType { /** diff --git a/data-bus/src/main/java/com/iluwatar/databus/Member.java b/data-bus/src/main/java/com/iluwatar/databus/Member.java index c2ab7de32d7d..3d4e976409ac 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/Member.java +++ b/data-bus/src/main/java/com/iluwatar/databus/Member.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -48,11 +50,7 @@ of this software and associated documentation files (the "Software"), to deal import java.util.function.Consumer; -/** - * Members receive events from the Data-Bus. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ +/** Members receive events from the Data-Bus. */ public interface Member extends Consumer { void accept(DataType event); diff --git a/data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java b/data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java index ac541cf200cc..970fc6973050 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java +++ b/data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,29 +22,20 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.databus.data; import com.iluwatar.databus.AbstractDataType; import com.iluwatar.databus.DataType; +import lombok.AllArgsConstructor; +import lombok.Getter; -/** - * An event raised when a string message is sent. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ +/** An event raised when a string message is sent. */ +@Getter +@AllArgsConstructor public class MessageData extends AbstractDataType { private final String message; - public MessageData(String message) { - this.message = message; - } - - public String getMessage() { - return message; - } - public static DataType of(final String message) { return new MessageData(message); } diff --git a/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java b/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java index ac7391f1a236..554a0ff71780 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java +++ b/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,31 +22,21 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.databus.data; import com.iluwatar.databus.AbstractDataType; import com.iluwatar.databus.DataType; - import java.time.LocalDateTime; +import lombok.Getter; +import lombok.RequiredArgsConstructor; -/** - * An event raised when applications starts, containing the start time of the application. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ +/** An event raised when applications starts, containing the start time of the application. */ +@RequiredArgsConstructor +@Getter public class StartingData extends AbstractDataType { private final LocalDateTime when; - public StartingData(LocalDateTime when) { - this.when = when; - } - - public LocalDateTime getWhen() { - return when; - } - public static DataType of(final LocalDateTime when) { return new StartingData(when); } diff --git a/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java b/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java index 976fdc4e941e..090f312650a4 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java +++ b/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,31 +22,21 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.databus.data; import com.iluwatar.databus.AbstractDataType; import com.iluwatar.databus.DataType; - import java.time.LocalDateTime; +import lombok.Getter; +import lombok.RequiredArgsConstructor; -/** - * An event raised when applications stops, containing the stop time of the application. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ +/** An event raised when applications stops, containing the stop time of the application. */ +@RequiredArgsConstructor +@Getter public class StoppingData extends AbstractDataType { private final LocalDateTime when; - public StoppingData(LocalDateTime when) { - this.when = when; - } - - public LocalDateTime getWhen() { - return when; - } - public static DataType of(final LocalDateTime when) { return new StoppingData(when); } diff --git a/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java b/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java index a8ee94ad5403..8eb81da1ae8b 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java +++ b/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,30 +22,22 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.databus.members; import com.iluwatar.databus.DataType; import com.iluwatar.databus.Member; import com.iluwatar.databus.data.MessageData; - import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import java.util.logging.Logger; +import lombok.extern.slf4j.Slf4j; -/** - * Receiver of Data-Bus events that collects the messages from each {@link MessageData}. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ +/** Receiver of Data-Bus events that collects the messages from each {@link MessageData}. */ +@Slf4j public class MessageCollectorMember implements Member { - private static final Logger LOGGER = Logger.getLogger(MessageCollectorMember.class.getName()); - private final String name; - private List messages = new ArrayList<>(); + private final List messages = new ArrayList<>(); public MessageCollectorMember(String name) { this.name = name; @@ -57,11 +51,11 @@ public void accept(final DataType data) { } private void handleEvent(MessageData data) { - LOGGER.info(String.format("%s sees message %s", name, data.getMessage())); + LOGGER.info("{} sees message {}", name, data.getMessage()); messages.add(data.getMessage()); } public List getMessages() { - return Collections.unmodifiableList(messages); + return List.copyOf(messages); } } diff --git a/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java b/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java index 803e2df205c3..d6aab7730b02 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java +++ b/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,7 +22,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.databus.members; import com.iluwatar.databus.DataType; @@ -28,29 +29,23 @@ import com.iluwatar.databus.data.MessageData; import com.iluwatar.databus.data.StartingData; import com.iluwatar.databus.data.StoppingData; - import java.time.LocalDateTime; -import java.util.logging.Logger; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; -/** - * Receiver of Data-Bus events. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ +/** Receiver of Data-Bus events. */ +@Getter +@Slf4j +@RequiredArgsConstructor public class StatusMember implements Member { - private static final Logger LOGGER = Logger.getLogger(StatusMember.class.getName()); - private final int id; private LocalDateTime started; private LocalDateTime stopped; - public StatusMember(int id) { - this.id = id; - } - @Override public void accept(final DataType data) { if (data instanceof StartingData) { @@ -62,21 +57,13 @@ public void accept(final DataType data) { private void handleEvent(StartingData data) { started = data.getWhen(); - LOGGER.info(String.format("Receiver #%d sees application started at %s", id, started)); + LOGGER.info("Receiver {} sees application started at {}", id, started); } private void handleEvent(StoppingData data) { stopped = data.getWhen(); - LOGGER.info(String.format("Receiver #%d sees application stopping at %s", id, stopped)); - LOGGER.info(String.format("Receiver #%d sending goodbye message", id)); + LOGGER.info("Receiver {} sees application stopping at {}", id, stopped); + LOGGER.info("Receiver {} sending goodbye message", id); data.getDataBus().publish(MessageData.of(String.format("Goodbye cruel world from #%d!", id))); } - - public LocalDateTime getStarted() { - return started; - } - - public LocalDateTime getStopped() { - return stopped; - } } diff --git a/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java b/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java index 83d5386ace05..a948201b4d76 100644 --- a/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java +++ b/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,53 +24,46 @@ */ package com.iluwatar.databus; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.never; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import static org.mockito.BDDMockito.then; -import static org.mockito.Mockito.never; - -/** - * Tests for {@link DataBus}. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ -public class DataBusTest { +/** Tests for {@link DataBus}. */ +class DataBusTest { - @Mock - private Member member; + @Mock private Member member; - @Mock - private DataType event; + @Mock private DataType event; @BeforeEach - public void setUp() { - MockitoAnnotations.initMocks(this); + void setUp() { + MockitoAnnotations.openMocks(this); } @Test - public void publishedEventIsReceivedBySubscribedMember() { - //given - final DataBus dataBus = DataBus.getInstance(); + void publishedEventIsReceivedBySubscribedMember() { + // given + final var dataBus = DataBus.getInstance(); dataBus.subscribe(member); - //when + // when dataBus.publish(event); - //then + // then then(member).should().accept(event); } @Test - public void publishedEventIsNotReceivedByMemberAfterUnsubscribing() { - //given - final DataBus dataBus = DataBus.getInstance(); + void publishedEventIsNotReceivedByMemberAfterUnsubscribing() { + // given + final var dataBus = DataBus.getInstance(); dataBus.subscribe(member); dataBus.unsubscribe(member); - //when + // when dataBus.publish(event); - //then + // then then(member).should(never()).accept(event); } - } diff --git a/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java b/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java index be705d6e7671..e0f881108df7 100644 --- a/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java +++ b/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,43 +24,37 @@ */ package com.iluwatar.databus.members; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.databus.data.MessageData; import com.iluwatar.databus.data.StartingData; -import org.junit.jupiter.api.Test; - import java.time.LocalDateTime; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests for {@link MessageCollectorMember}. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ -public class MessageCollectorMemberTest { +/** Tests for {@link MessageCollectorMember}. */ +class MessageCollectorMemberTest { @Test - public void collectMessageFromMessageData() { - //given - final String message = "message"; - final MessageData messageData = new MessageData(message); - final MessageCollectorMember collector = new MessageCollectorMember("collector"); - //when + void collectMessageFromMessageData() { + // given + final var message = "message"; + final var messageData = new MessageData(message); + final var collector = new MessageCollectorMember("collector"); + // when collector.accept(messageData); - //then + // then assertTrue(collector.getMessages().contains(message)); } @Test - public void collectIgnoresMessageFromOtherDataTypes() { - //given - final StartingData startingData = new StartingData(LocalDateTime.now()); - final MessageCollectorMember collector = new MessageCollectorMember("collector"); - //when + void collectIgnoresMessageFromOtherDataTypes() { + // given + final var startingData = new StartingData(LocalDateTime.now()); + final var collector = new MessageCollectorMember("collector"); + // when collector.accept(startingData); - //then + // then assertEquals(0, collector.getMessages().size()); } - } diff --git a/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java b/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java index 41c0fccca726..b7aa8b826084 100644 --- a/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java +++ b/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,60 +24,54 @@ */ package com.iluwatar.databus.members; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + import com.iluwatar.databus.DataBus; import com.iluwatar.databus.data.MessageData; import com.iluwatar.databus.data.StartingData; import com.iluwatar.databus.data.StoppingData; -import org.junit.jupiter.api.Test; - import java.time.LocalDateTime; import java.time.Month; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -/** - * Tests for {@link StatusMember}. - * - * @author Paul Campbell (pcampbell@kemitix.net) - */ -public class StatusMemberTest { +/** Tests for {@link StatusMember}. */ +class StatusMemberTest { @Test - public void statusRecordsTheStartTime() { - //given - final LocalDateTime startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9); - final StartingData startingData = new StartingData(startTime); - final StatusMember statusMember = new StatusMember(1); - //when + void statusRecordsTheStartTime() { + // given + final var startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9); + final var startingData = new StartingData(startTime); + final var statusMember = new StatusMember(1); + // when statusMember.accept(startingData); - //then + // then assertEquals(startTime, statusMember.getStarted()); } @Test - public void statusRecordsTheStopTime() { - //given - final LocalDateTime stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12); - final StoppingData stoppingData = new StoppingData(stop); + void statusRecordsTheStopTime() { + // given + final var stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12); + final var stoppingData = new StoppingData(stop); stoppingData.setDataBus(DataBus.getInstance()); - final StatusMember statusMember = new StatusMember(1); - //when + final var statusMember = new StatusMember(1); + // when statusMember.accept(stoppingData); - //then + // then assertEquals(stop, statusMember.getStopped()); } @Test - public void statusIgnoresMessageData() { - //given - final MessageData messageData = new MessageData("message"); - final StatusMember statusMember = new StatusMember(1); - //when + void statusIgnoresMessageData() { + // given + final var messageData = new MessageData("message"); + final var statusMember = new StatusMember(1); + // when statusMember.accept(messageData); - //then + // then assertNull(statusMember.getStarted()); assertNull(statusMember.getStopped()); } - } diff --git a/data-locality/README.md b/data-locality/README.md new file mode 100644 index 000000000000..a59103b3f89b --- /dev/null +++ b/data-locality/README.md @@ -0,0 +1,173 @@ +--- +title: "Data Locality Pattern in Java: Boosting Performance with Efficient Data Management" +shortTitle: Data Locality +description: "Learn about the Data Locality pattern in Java, a technique to optimize performance by improving cache utilization and minimizing data access times. Ideal for game development and high-performance computing." +category: Performance optimization +language: en +tag: + - Caching + - Data access + - Game programming + - Memory management + - Performance +--- + +## Also known as + +* Cache-Friendly Design +* Data-Oriented Design + +## Intent of Data Locality Design Pattern + +The Data Locality design pattern aims to minimize data access times and improve cache utilization by arranging data in memory to take advantage of spatial locality. This pattern is particularly useful in high-performance computing, real-time data processing, and game development where access speed is crucial. + +## Detailed Explanation of Data Locality Pattern with Real-World Examples + +Real-world example + +> Consider a supermarket where items are arranged based on purchase patterns and categories for efficiency. Just like the Data Locality pattern organizes data in memory for quick access, the supermarket places frequently bought items together and in easily accessible areas. This layout minimizes the time shoppers spend searching for items, enhancing their shopping experience by ensuring that related and popular items are close at hand, much like how data locality improves cache utilization and reduces access latency in computing. + +In plain words + +> The Data Locality pattern organizes data in memory to reduce access times and improve performance by ensuring that data frequently accessed together is stored close together. This is crucial for high-performance applications like game engines and real-time data processing systems. + +Mind map + +![Data Locality mind map](./etc/data-locality-mind-map.png) + +Flowchart + +![Data Locality flowchart](./etc/data-locality-flowchart.png) + +## Programmatic Example of Data Locality Pattern in Java + +The Data Locality pattern is a design pattern that aims to improve performance by arranging data in memory to take advantage of spatial locality. This pattern is particularly useful in high-performance computing and game development where access speed is crucial. + +In the data-locality module, the pattern is demonstrated using a game loop that processes a bunch of game entities. These entities are decomposed into different domains: AI, physics, and rendering. + +The `GameEntity` class is the main class that represents a game entity. It contains an array of `AiComponent`, `PhysicsComponent`, and `RenderComponent` objects. These components represent different aspects of a game entity. + +```java +public class GameEntity { + private final AiComponent[] aiComponents; + private final PhysicsComponent[] physicsComponents; + private final RenderComponent[] renderComponents; + // Other properties and methods... +} +``` + +The `GameEntity` class has a start method that initializes all the components. + +```java +public void start() { + for (int i = 0; i < numEntities; i++) { + aiComponents[i] = new AiComponent(); + physicsComponents[i] = new PhysicsComponent(); + renderComponents[i] = new RenderComponent(); + } +} +``` + +The `GameEntity` class also has an update method that updates all the components. This method demonstrates the data locality pattern. Instead of updating all aspects of a single entity at a time (AI, physics, and rendering), it updates the same aspect (e.g., AI) for all entities first, then moves on to the next aspect (e.g., physics). This approach improves cache utilization because it's more likely that the data needed for the update is already in the cache. + +```java +public void update() { + for (int i = 0; i < numEntities; i++) { + aiComponents[i].update(); + } + for (int i = 0; i < numEntities; i++) { + physicsComponents[i].update(); + } + for (int i = 0; i < numEntities; i++) { + renderComponents[i].update(); + } +} +``` + +The `Application` class contains the main method that creates a `GameEntity` object and starts the game loop. + +```java +public class Application { + public static void main(String[] args) { + var gameEntity = new GameEntity(NUM_ENTITIES); + gameEntity.start(); + gameEntity.update(); + } +} +``` + +The console output: + +``` +10:19:52.155 [main] INFO com.iluwatar.data.locality.Application -- Start Game Application using Data-Locality pattern +10:19:52.157 [main] INFO com.iluwatar.data.locality.game.GameEntity -- Init Game with #Entity : 5 +10:19:52.158 [main] INFO com.iluwatar.data.locality.game.GameEntity -- Start Game +10:19:52.158 [main] INFO com.iluwatar.data.locality.game.component.manager.AiComponentManager -- Start AI Game Component +10:19:52.158 [main] INFO com.iluwatar.data.locality.game.component.manager.PhysicsComponentManager -- Start Physics Game Component +10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.manager.RenderComponentManager -- Start Render Game Component +10:19:52.159 [main] INFO com.iluwatar.data.locality.game.GameEntity -- Update Game Component +10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.manager.AiComponentManager -- Update AI Game Component +10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.AiComponent -- update AI component +10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.AiComponent -- update AI component +10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.AiComponent -- update AI component +10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.AiComponent -- update AI component +10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.AiComponent -- update AI component +10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.manager.PhysicsComponentManager -- Update Physics Game Component +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.PhysicsComponent -- Update physics component of game +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.PhysicsComponent -- Update physics component of game +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.PhysicsComponent -- Update physics component of game +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.PhysicsComponent -- Update physics component of game +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.PhysicsComponent -- Update physics component of game +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.manager.RenderComponentManager -- Update Render Game Component +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.RenderComponent -- Render Component +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.RenderComponent -- Render Component +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.RenderComponent -- Render Component +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.RenderComponent -- Render Component +10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.RenderComponent -- Render Component +``` + +In this way, the data-locality module demonstrates the Data Locality pattern. By updating all components of the same type together, it increases the likelihood that the data needed for the update is already in the cache, thereby improving performance. + +## When to Use the Data Locality Pattern in Java + +This pattern is applicable in scenarios where large datasets are processed and performance is critical. It's particularly useful in: + +* Game development for efficient rendering and physics calculations. +* High-performance computing tasks that require rapid access to large data sets. +* Real-time data processing systems where latency is a critical factor. +* Scientific computing applications needing optimized matrix operations. +* Data-intensive applications requiring enhanced memory access patterns. + +## Real-World Applications of Data Locality Pattern in Java + +* Game engines (e.g., Unity, Unreal Engine) to optimize entity and component data access. +* High-performance matrix libraries in scientific computing to optimize matrix operations. +* Real-time streaming data processing systems for efficient data manipulation and access. + +## Benefits and Trade-offs of Data Locality Pattern + +Benefits: + +* Improved Cache Utilization: By enhancing spatial locality, data frequently accessed together is stored close together in memory, improving cache hit rates. +* Reduced Access Latency: Minimizes the time taken to fetch data from memory, leading to performance improvements. +* Enhanced Performance: Overall system performance is improved due to reduced memory access times and increased efficiency in data processing. + +Trade-offs: + +* Complexity in Implementation: Managing data layout can add complexity to the system design and implementation. +* Maintenance Overhead: As data access patterns evolve, the layout may need to be re-evaluated, adding to the maintenance overhead. +* Less Flexibility: The tight coupling of data layout to access patterns can reduce flexibility in how data structures are used and evolved over time. + +## Related Java Design Patterns + +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used in conjunction with Data Locality to share data efficiently among multiple objects. +* [Object Pool](https://java-design-patterns.com/patterns/object-pool/): Often used together to manage a group of initialized objects that can be reused, further optimizing memory usage and access. +* [Iterator](https://java-design-patterns.com/patterns/iterator/): Facilitates navigation through a collection of data laid out with data locality in mind. + +## References and Credits + +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Game Programming Patterns](https://amzn.to/3vK8c0d) +* [High-Performance Java Persistence](https://amzn.to/3TMc8Wd) +* [Java Performance: The Definitive Guide](https://amzn.to/3Ua392J) +* [Game Programming Patterns Optimization Patterns: Data Locality](http://gameprogrammingpatterns.com/data-locality.html) diff --git a/data-locality/etc/data-locality-flowchart.png b/data-locality/etc/data-locality-flowchart.png new file mode 100644 index 000000000000..deedabbdfb8b Binary files /dev/null and b/data-locality/etc/data-locality-flowchart.png differ diff --git a/data-locality/etc/data-locality-mind-map.png b/data-locality/etc/data-locality-mind-map.png new file mode 100644 index 000000000000..c2761f45bf5a Binary files /dev/null and b/data-locality/etc/data-locality-mind-map.png differ diff --git a/data-locality/etc/data-locality.urm.png b/data-locality/etc/data-locality.urm.png new file mode 100644 index 000000000000..d19873739551 Binary files /dev/null and b/data-locality/etc/data-locality.urm.png differ diff --git a/data-locality/etc/data-locality.urm.puml b/data-locality/etc/data-locality.urm.puml new file mode 100644 index 000000000000..1e2d3e6793cb --- /dev/null +++ b/data-locality/etc/data-locality.urm.puml @@ -0,0 +1,80 @@ +@startuml +package com.iluwatar.data.locality.game.component.manager { + class AiComponentManager { + - AI_COMPONENTS : Component[] {static} + - LOGGER : Logger {static} + - MAX_ENTITIES : int {static} + - numEntities : int + + AiComponentManager(numEntities : int) + + start() + + update() + } + class PhysicsComponentManager { + - LOGGER : Logger {static} + - MAX_ENTITIES : int {static} + - PHYSICS_COMPONENTS : Component[] {static} + - numEntities : int + + PhysicsComponentManager(numEntities : int) + + start() + + update() + } + class RenderComponentManager { + - LOGGER : Logger {static} + - MAX_ENTITIES : int {static} + - RENDER_COMPONENTS : Component[] {static} + - numEntities : int + + RenderComponentManager(numEntities : int) + + render() + + start() + } +} +package com.iluwatar.data.locality { + class Application { + - LOGGER : Logger {static} + - NUM_ENTITIES : int {static} + + Application() + + main(args : String[]) {static} + } +} +package com.iluwatar.data.locality.game { + class GameEntity { + - LOGGER : Logger {static} + - aiComponentManager : AiComponentManager + - physicsComponentManager : PhysicsComponentManager + - renderComponentManager : RenderComponentManager + + GameEntity(numEntities : int) + + start() + + update() + } +} +package com.iluwatar.data.locality.game.component { + class AiComponent { + - LOGGER : Logger {static} + + AiComponent() + + render() + + update() + } + interface Component { + + render() {abstract} + + update() {abstract} + } + class PhysicsComponent { + - LOGGER : Logger {static} + + PhysicsComponent() + + render() + + update() + } + class RenderComponent { + - LOGGER : Logger {static} + + RenderComponent() + + render() + + update() + } +} +GameEntity --> "-physicsComponentManager" PhysicsComponentManager +GameEntity --> "-aiComponentManager" AiComponentManager +GameEntity --> "-renderComponentManager" RenderComponentManager +AiComponent ..|> Component +PhysicsComponent ..|> Component +RenderComponent ..|> Component +@enduml \ No newline at end of file diff --git a/data-locality/pom.xml b/data-locality/pom.xml new file mode 100644 index 000000000000..593f6793473a --- /dev/null +++ b/data-locality/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + data-locality + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.data.locality.Application + + + + + + + + + diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/Application.java b/data-locality/src/main/java/com/iluwatar/data/locality/Application.java new file mode 100644 index 000000000000..862fa11732bf --- /dev/null +++ b/data-locality/src/main/java/com/iluwatar/data/locality/Application.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.data.locality; + +import com.iluwatar.data.locality.game.GameEntity; +import lombok.extern.slf4j.Slf4j; + +/** + * Use the Data Locality pattern is when you have a performance problem. Take advantage of that to + * improve performance by increasing data locality — keeping data in contiguous memory in the order + * that you process it. + * + *

    Example: Game loop that processes a bunch of game entities. Those entities are decomposed into + * different domains  — AI, physics, and rendering — using the Component pattern. + */ +@Slf4j +public class Application { + + private static final int NUM_ENTITIES = 5; + + /** Start game loop with each component have NUM_ENTITIES instance. */ + public static void main(String[] args) { + LOGGER.info("Start Game Application using Data-Locality pattern"); + var gameEntity = new GameEntity(NUM_ENTITIES); + gameEntity.start(); + gameEntity.update(); + } +} diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java new file mode 100644 index 000000000000..92ce918a7345 --- /dev/null +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java @@ -0,0 +1,77 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.data.locality.game; + +import com.iluwatar.data.locality.game.component.manager.AiComponentManager; +import com.iluwatar.data.locality.game.component.manager.PhysicsComponentManager; +import com.iluwatar.data.locality.game.component.manager.RenderComponentManager; +import lombok.extern.slf4j.Slf4j; + +/** + * The game Entity maintains a big array of pointers . Each spin of the game loop, we need to run + * the following: + * + *

    Update the AI components. + * + *

    Update the physics components for them. + * + *

    Render them using their render components. + */ +@Slf4j +public class GameEntity { + + private final AiComponentManager aiComponentManager; + private final PhysicsComponentManager physicsComponentManager; + private final RenderComponentManager renderComponentManager; + + /** Init components. */ + public GameEntity(int numEntities) { + LOGGER.info("Init Game with #Entity : {}", numEntities); + aiComponentManager = new AiComponentManager(numEntities); + physicsComponentManager = new PhysicsComponentManager(numEntities); + renderComponentManager = new RenderComponentManager(numEntities); + } + + /** start all component. */ + public void start() { + LOGGER.info("Start Game"); + aiComponentManager.start(); + physicsComponentManager.start(); + renderComponentManager.start(); + } + + /** update all component. */ + public void update() { + LOGGER.info("Update Game Component"); + // Process AI. + aiComponentManager.update(); + + // update physics. + physicsComponentManager.update(); + + // Draw to screen. + renderComponentManager.render(); + } +} diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java new file mode 100644 index 000000000000..2f3cb043fcb1 --- /dev/null +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.data.locality.game.component; + +import lombok.extern.slf4j.Slf4j; + +/** Implementation of AI component for Game. */ +@Slf4j +public class AiComponent implements Component { + + /** Update ai component. */ + @Override + public void update() { + LOGGER.info("update AI component"); + } + + @Override + public void render() { + // Do Nothing. + } +} diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java new file mode 100644 index 000000000000..5775804fbc05 --- /dev/null +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.data.locality.game.component; + +/** Implement different Game component update and render process. */ +public interface Component { + + void update(); + + void render(); +} diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java new file mode 100644 index 000000000000..43b762aaf4ed --- /dev/null +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.data.locality.game.component; + +import lombok.extern.slf4j.Slf4j; + +/** Implementation of Physics Component of Game. */ +@Slf4j +public class PhysicsComponent implements Component { + + /** update physics component of game. */ + @Override + public void update() { + LOGGER.info("Update physics component of game"); + } + + @Override + public void render() { + // do nothing + } +} diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java new file mode 100644 index 000000000000..c04b2bc8fa80 --- /dev/null +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.data.locality.game.component; + +import lombok.extern.slf4j.Slf4j; + +/** Implementation of Render Component of Game. */ +@Slf4j +public class RenderComponent implements Component { + + @Override + public void update() { + // do nothing + } + + /** render. */ + @Override + public void render() { + LOGGER.info("Render Component"); + } +} diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java new file mode 100644 index 000000000000..a69d77b13da4 --- /dev/null +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java @@ -0,0 +1,59 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.data.locality.game.component.manager; + +import com.iluwatar.data.locality.game.component.AiComponent; +import com.iluwatar.data.locality.game.component.Component; +import java.util.stream.IntStream; +import lombok.extern.slf4j.Slf4j; + +/** AI component manager for Game. */ +@Slf4j +public class AiComponentManager { + + private static final int MAX_ENTITIES = 10000; + + private final int numEntities; + + private final Component[] aiComponents = new AiComponent[MAX_ENTITIES]; + + public AiComponentManager(int numEntities) { + this.numEntities = numEntities; + } + + /** start AI component of Game. */ + public void start() { + LOGGER.info("Start AI Game Component"); + IntStream.range(0, numEntities).forEach(i -> aiComponents[i] = new AiComponent()); + } + + /** Update AI component of Game. */ + public void update() { + LOGGER.info("Update AI Game Component"); + IntStream.range(0, numEntities) + .filter(i -> aiComponents.length > i && aiComponents[i] != null) + .forEach(i -> aiComponents[i].update()); + } +} diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java new file mode 100644 index 000000000000..c9b1a9bbeb10 --- /dev/null +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java @@ -0,0 +1,60 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.data.locality.game.component.manager; + +import com.iluwatar.data.locality.game.component.Component; +import com.iluwatar.data.locality.game.component.PhysicsComponent; +import java.util.stream.IntStream; +import lombok.extern.slf4j.Slf4j; + +/** Physics component Manager for Game. */ +@Slf4j +public class PhysicsComponentManager { + + private static final int MAX_ENTITIES = 10000; + + private final int numEntities; + + private final Component[] physicsComponents = new PhysicsComponent[MAX_ENTITIES]; + + public PhysicsComponentManager(int numEntities) { + this.numEntities = numEntities; + } + + /** Start physics component of Game. */ + public void start() { + LOGGER.info("Start Physics Game Component "); + IntStream.range(0, numEntities).forEach(i -> physicsComponents[i] = new PhysicsComponent()); + } + + /** Update physics component of Game. */ + public void update() { + LOGGER.info("Update Physics Game Component "); + // Process physics. + IntStream.range(0, numEntities) + .filter(i -> physicsComponents.length > i && physicsComponents[i] != null) + .forEach(i -> physicsComponents[i].update()); + } +} diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java new file mode 100644 index 000000000000..cff4bc3ac40a --- /dev/null +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java @@ -0,0 +1,60 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.data.locality.game.component.manager; + +import com.iluwatar.data.locality.game.component.Component; +import com.iluwatar.data.locality.game.component.RenderComponent; +import java.util.stream.IntStream; +import lombok.extern.slf4j.Slf4j; + +/** Render component manager for Game. */ +@Slf4j +public class RenderComponentManager { + + private static final int MAX_ENTITIES = 10000; + + private final int numEntities; + + private final Component[] renderComponents = new RenderComponent[MAX_ENTITIES]; + + public RenderComponentManager(int numEntities) { + this.numEntities = numEntities; + } + + /** Start render component. */ + public void start() { + LOGGER.info("Start Render Game Component "); + IntStream.range(0, numEntities).forEach(i -> renderComponents[i] = new RenderComponent()); + } + + /** render component. */ + public void render() { + LOGGER.info("Update Render Game Component "); + // Process Render. + IntStream.range(0, numEntities) + .filter(i -> renderComponents.length > i && renderComponents[i] != null) + .forEach(i -> renderComponents[i].render()); + } +} diff --git a/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java b/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java new file mode 100644 index 000000000000..badf5aadd027 --- /dev/null +++ b/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.data.locality; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Test Game Application */ +class ApplicationTest { + + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link Application#main(String[])} throws an + * exception. + */ + @Test + void shouldExecuteGameApplicationWithoutException() { + assertDoesNotThrow(() -> Application.main(new String[] {})); + } +} diff --git a/data-mapper/README.md b/data-mapper/README.md index 075e8eecef15..b3bcb97f6f7b 100644 --- a/data-mapper/README.md +++ b/data-mapper/README.md @@ -1,25 +1,171 @@ --- -layout: pattern -title: Data Mapper -folder: data-mapper -permalink: /patterns/data-mapper/ -categories: Persistence Tier -tags: - - Java - - Difficulty-Beginner +title: "Data Mapper Pattern in Java: Decoupling Data Storage from Business Logic" +shortTitle: Data Mapper +description: "Explore the Data Mapper pattern in Java, which decouples database operations from business logic. Learn how to implement and utilize this pattern to enhance maintainability and flexibility in your Java applications." +category: Behavioral +language: en +tag: + - Data access + - Decoupling + - Domain + - Object mapping + - Persistence --- -## Intent -A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself +## Also known as -![alt text](./etc/data-mapper.png "Data Mapper") +* Object-Relational Mapping (ORM) + +## Intent of the Data Mapper Pattern + +The Data Mapper pattern aims to create an abstraction layer between the database and the business logic, allowing them to evolve independently. It maps data from the database objects to in-memory data structures and vice versa, minimizing direct dependencies between the application's core logic and the underlying database structure. This decoupling is essential in promoting maintainability and flexibility in Java programming. + +## Detailed Explanation of Data Mapper Pattern with Real-World Examples + +Real-world example + +> Consider a library system where books are stored in a database with complex relationships and various attributes such as title, author, publication year, and genre. In this scenario, a Data Mapper pattern can be used to map the database records of books to in-memory objects in the application. The Data Mapper would handle the retrieval, storage, and update of book objects in the database, allowing the application's business logic to work directly with the book objects without concern for the underlying database structure. This separation makes it easier to change the database schema without affecting the business logic, and vice versa. + +In plain words + +> A layer of mappers that moves data between objects and a database while keeping them independent of each other. + +Wikipedia says + +> A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in-memory data representation (the domain layer). The goal of the pattern is to keep the in-memory representation and the persistent data store independent of each other and the data mapper itself. This is useful when one needs to model and enforce strict business processes on the data in the domain layer that do not map neatly to the persistent data store. + +Sequence diagram + +![Data Mapper sequence diagram](./etc/data-mapper-sequence-diagram.png) + +## Programmatic Example of Data Mapper Pattern in Java + +The Data Mapper is a design pattern that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. This pattern promotes the [Single Responsibility Principle](https://java-design-patterns.com/principles/#single-responsibility-principle) and [Separation of Concerns](https://java-design-patterns.com/principles/#separation-of-concerns). + +In the data-mapper module, the pattern is demonstrated using a `Student` class and a `StudentDataMapper` interface. + +The `Student` class is a simple POJO (Plain Old Java Object) that represents a student. It has properties like studentId, name, and grade. + +```java +public class Student { + private int studentId; + private String name; + private char grade; + // ... +} +``` + +The `StudentDataMapper` interface defines the operations that can be performed on `Student` objects. These operations include `insert`, `update`, `delete`, and `find`. + +```java +public interface StudentDataMapper { + void insert(final Student student); + + void update(final Student student); + + void delete(final Student student); + + Optional find(final int studentId); + // ... +} +``` + +The `StudentDataMapperImpl` class implements the `StudentDataMapper` interface. It contains the actual logic for interacting with the database. + +```java +public class StudentDataMapperImpl implements StudentDataMapper { + // ... + @Override + public void insert(final Student student) { + // Insert student into the database + } + + @Override + public void update(final Student student) { + // Update student in the database + } + + @Override + public void delete(final Student student) { + // Delete student from the database + } + + @Override + public Optional find(final int studentId) { + // Find student in the database + } + // ... +} +``` + +The `App` class contains the main method that demonstrates the use of the `StudentDataMapper`. It creates a `Student` object, inserts it into the database, finds it, updates it, and finally deletes it. + +```java +public class App { + public static void main(final String... args) { + final var mapper = new StudentDataMapperImpl(); + var student = new Student(1, "Adam", 'A'); + mapper.insert(student); + final var studentToBeFound = mapper.find(student.getStudentId()); + student = new Student(student.getStudentId(), "AdamUpdated", 'A'); + mapper.update(student); + mapper.delete(student); + } +} +``` + +Program output: + +``` +13:54:29.234 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Student(studentId=1, name=Adam, grade=A), is inserted +13:54:29.237 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Optional[Student(studentId=1, name=Adam, grade=A)], is searched +13:54:29.237 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Student(studentId=1, name=AdamUpdated, grade=A), is updated +13:54:29.238 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Student(studentId=1, name=AdamUpdated, grade=A), is going to be deleted +``` + +## When to Use the Data Mapper Pattern in Java -## Applicability Use the Data Mapper in any of the following situations -* when you want to decouple data objects from DB access layer -* when you want to write multiple data retrieval/persistence implementations +* When there's a need to decouple the in-memory objects from the database entities to promote the [Single Responsibility Principle](https://java-design-patterns.com/principles/#single-responsibility-principle) and [Separation of Concerns](https://java-design-patterns.com/principles/#separation-of-concerns). +* In applications requiring an ORM tool to bridge the gap between object-oriented models and relational databases. +* When working with complex database schemas where direct data manipulation and object creation lead to cumbersome and error-prone code. + +## Data Mapper Pattern Java Tutorials + +* [Spring Boot RowMapper (ZetCode)](https://zetcode.com/springboot/rowmapper/) +* [Spring BeanPropertyRowMapper tutorial (ZetCode)](https://zetcode.com/spring/beanpropertyrowmapper/) +* [Data Transfer Object Pattern in Java - Implementation and Mapping (StackAbuse)](https://stackabuse.com/data-transfer-object-pattern-in-java-implementation-and-mapping/) + +## Real-World Applications of Data Mapper Pattern in Java + +* ORM frameworks such as Hibernate in Java. +* Data access layers in enterprise applications where business logic and database management are kept separate. +* Applications requiring database interactions without tying the code to a specific database implementation. + +## Benefits and Trade-offs of Data Mapper Pattern + +Benefits: + +* Promotes [Single Responsibility Principle](https://java-design-patterns.com/principles/#single-responsibility-principle) by separating persistence logic from business logic. +* Enhances maintainability and readability by centralizing data interaction logic. +* Improves application's ability to adapt to changes in the database schema with minimal changes to the business logic. + +Trade-offs: + +* Introduces complexity through the additional abstraction layer. +* Might lead to performance overhead due to the abstraction layer, especially in large-scale applications or with complex queries. +* Requires developers to learn and understand the abstraction layer in addition to the database and ORM framework being used. + +## Related Java Design Patterns + +* Active Record: Combines data access logic and business logic in the domain entities themselves, contrary to Data Mapper's separation of concerns. +* Object–Relational Mapping (ORM): A technique to map object-oriented programming language data to a relational database. +* [Repository](https://java-design-patterns.com/patterns/repository/): Provides an abstraction of the data layer, acting as a collection of domain objects in memory. +* [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Manages transactions and keeps track of the objects affected by a business transaction to ensure changes are consistent and transactional. -## Credits +## References and Credits -* [Data Mapper](http://richard.jp.leguen.ca/tutoring/soen343-f2010/tutorials/implementing-data-mapper/) +* [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3xyEFag) +* [Java Persistence with Hibernate](https://amzn.to/3VNzlKe) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/data-mapper/etc/data-mapper-sequence-diagram.png b/data-mapper/etc/data-mapper-sequence-diagram.png new file mode 100644 index 000000000000..c59b23a67649 Binary files /dev/null and b/data-mapper/etc/data-mapper-sequence-diagram.png differ diff --git a/data-mapper/etc/data-mapper.urm.puml b/data-mapper/etc/data-mapper.urm.puml new file mode 100644 index 000000000000..3b32411d11c9 --- /dev/null +++ b/data-mapper/etc/data-mapper.urm.puml @@ -0,0 +1,43 @@ +@startuml +package com.iluwatar.datamapper { + class App { + - STUDENT_STRING : String {static} + - log : Logger {static} + - App() + + main(args : String[]) {static} + } + class Student { + - grade : char + - name : String + - serialVersionUID : long {static} + - studentId : int + + Student(studentId : int, name : String, grade : char) + + equals(inputObject : Object) : boolean + + getGrade() : char + + getName() : String + + getStudentId() : int + + hashCode() : int + + setGrade(grade : char) + + setName(name : String) + + setStudentId(studentId : int) + + toString() : String + } + interface StudentDataMapper { + + delete(Student) {abstract} + + find(int) : Optional {abstract} + + insert(Student) {abstract} + + update(Student) {abstract} + } + class StudentDataMapperImpl { + - students : List + + StudentDataMapperImpl() + + delete(studentToBeDeleted : Student) + + find(studentId : int) : Optional + + getStudents() : List + + insert(studentToBeInserted : Student) + + update(studentToBeUpdated : Student) + } +} +StudentDataMapperImpl --> "-students" Student +StudentDataMapperImpl ..|> StudentDataMapper +@enduml \ No newline at end of file diff --git a/data-mapper/pom.xml b/data-mapper/pom.xml index aadcabd3d540..40e8c3cee51d 100644 --- a/data-mapper/pom.xml +++ b/data-mapper/pom.xml @@ -1,50 +1,70 @@ - - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - data-mapper - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - log4j - log4j - - - + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + data-mapper + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.datamapper.App + + + + + + + + + diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/App.java b/data-mapper/src/main/java/com/iluwatar/datamapper/App.java index 5fcd0d9ea04c..3a7ed69f9711 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/App.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/App.java @@ -1,77 +1,81 @@ -/** - * The MIT License Copyright (c) 2016 Amit Dixit - * - * 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.datamapper; - -import java.util.Optional; - -import org.apache.log4j.Logger; - -/** - * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the - * database. Its responsibility is to transfer data between the two and also to isolate them from - * each other. With Data Mapper the in-memory objects needn't know even that there's a database - * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The - * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper , - * Data Mapper itself is even unknown to the domain layer. - *

    - * The below example demonstrates basic CRUD operations: Create, Read, Update, and Delete. - * - */ -public final class App { - - private static Logger log = Logger.getLogger(App.class); - - /** - * Program entry point. - * - * @param args command line args. - */ - public static void main(final String... args) { - - /* Create new data mapper for type 'first' */ - final StudentDataMapper mapper = new StudentDataMapperImpl(); - - /* Create new student */ - Student student = new Student(1, "Adam", 'A'); - - /* Add student in respectibe store */ - mapper.insert(student); - - log.debug("App.main(), student : " + student + ", is inserted"); - - /* Find this student */ - final Optional studentToBeFound = mapper.find(student.getStudentId()); - - log.debug("App.main(), student : " + studentToBeFound + ", is searched"); - - /* Update existing student object */ - student = new Student(student.getStudentId(), "AdamUpdated", 'A'); - - /* Update student in respectibe db */ - mapper.update(student); - - log.debug("App.main(), student : " + student + ", is updated"); - log.debug("App.main(), student : " + student + ", is going to be deleted"); - - /* Delete student in db */ - mapper.delete(student); - } - - private App() {} -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datamapper; + +import lombok.extern.slf4j.Slf4j; + +/** + * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the + * database. Its responsibility is to transfer data between the two and also to isolate them from + * each other. With Data Mapper the in-memory objects needn't know even that there's a database + * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The + * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper , + * Data Mapper itself is even unknown to the domain layer. + * + *

    The below example demonstrates basic CRUD operations: Create, Read, Update, and Delete. + */ +@Slf4j +public final class App { + + private static final String STUDENT_STRING = "App.main(), student : "; + + /** + * Program entry point. + * + * @param args command line args. + */ + public static void main(final String... args) { + + /* Create new data mapper for type 'first' */ + final var mapper = new StudentDataMapperImpl(); + + /* Create new student */ + var student = new Student(1, "Adam", 'A'); + + /* Add student in respectibe store */ + mapper.insert(student); + + LOGGER.debug(STUDENT_STRING + student + ", is inserted"); + + /* Find this student */ + final var studentToBeFound = mapper.find(student.getStudentId()); + + LOGGER.debug(STUDENT_STRING + studentToBeFound + ", is searched"); + + /* Update existing student object */ + student = new Student(student.getStudentId(), "AdamUpdated", 'A'); + + /* Update student in respectibe db */ + mapper.update(student); + + LOGGER.debug(STUDENT_STRING + student + ", is updated"); + LOGGER.debug(STUDENT_STRING + student + ", is going to be deleted"); + + /* Delete student in db */ + mapper.delete(student); + } + + private App() {} +} diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java b/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java index a6995b06d6fe..f02dcef33dfe 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java @@ -1,40 +1,45 @@ -/** - * The MIT License Copyright (c) 2016 Amit Dixit +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 + * 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 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. + * 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.datamapper; +import java.io.Serial; + /** - * Using Runtime Exception for avoiding dependancy on implementation exceptions. This helps in + * Using Runtime Exception for avoiding dependency on implementation exceptions. This helps in * decoupling. - * - * @author amit.dixit - * */ public final class DataMapperException extends RuntimeException { - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; /** * Constructs a new runtime exception with the specified detail message. The cause is not * initialized, and may subsequently be initialized by a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for later retrieval by the - * {@link #getMessage()} method. + * {@link #getMessage()} method. */ public DataMapperException(final String message) { super(message); diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java b/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java index d9c3d389f545..8d8a42116a06 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java @@ -1,140 +1,48 @@ -/** - * The MIT License Copyright (c) 2016 Amit Dixit - * - * 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.datamapper; - - -import java.io.Serializable; - -/** - * Class defining Student - */ -public final class Student implements Serializable { - - private static final long serialVersionUID = 1L; - - private int studentId; - private String name; - private char grade; - - - /** - * Use this constructor to create a Student with all details - * - * @param studentId as unique student id - * @param name as student name - * @param grade as respective grade of student - */ - public Student(final int studentId, final String name, final char grade) { - this.studentId = studentId; - this.name = name; - this.grade = grade; - } - - /** - * - * @return the student id - */ - public int getStudentId() { - return studentId; - } - - /** - * - * @param studentId as unique student id - */ - public void setStudentId(final int studentId) { - this.studentId = studentId; - } - - /** - * - * @return name of student - */ - public String getName() { - return name; - } - - /** - * - * @param name as 'name' of student - */ - public void setName(final String name) { - this.name = name; - } - - /** - * - * @return grade of student - */ - public char getGrade() { - return grade; - } - - /** - * - * @param grade as 'grade of student' - */ - public void setGrade(final char grade) { - this.grade = grade; - } - - /** - * - */ - @Override - public boolean equals(final Object inputObject) { - - boolean isEqual = false; - - /* Check if both objects are same */ - if (this == inputObject) { - - isEqual = true; - } else if (inputObject != null && getClass() == inputObject.getClass()) { - - final Student inputStudent = (Student) inputObject; - - /* If student id matched */ - if (this.getStudentId() == inputStudent.getStudentId()) { - - isEqual = true; - } - } - - return isEqual; - } - - /** - * - */ - @Override - public int hashCode() { - - /* Student id is assumed to be unique */ - return this.getStudentId(); - } - - /** - * - */ - @Override - public String toString() { - return "Student [studentId=" + studentId + ", name=" + name + ", grade=" + grade + "]"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datamapper; + +import java.io.Serial; +import java.io.Serializable; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** Class defining Student. */ +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@ToString +@Getter +@Setter +@AllArgsConstructor +public final class Student implements Serializable { + + @Serial private static final long serialVersionUID = 1L; + + @EqualsAndHashCode.Include private int studentId; + private String name; + private char grade; +} diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java index cb93f46973fe..ab28bd3dc4e7 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java @@ -1,35 +1,39 @@ -/** - * The MIT License Copyright (c) 2016 Amit Dixit - * - * 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.datamapper; - -import java.util.Optional; - -/** - * Interface lists out the possible behaviour for all possible student mappers - */ -public interface StudentDataMapper { - - Optional find(int studentId); - - void insert(Student student) throws DataMapperException; - - void update(Student student) throws DataMapperException; - - void delete(Student student) throws DataMapperException; -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datamapper; + +import java.util.Optional; + +/** Interface lists out the possible behaviour for all possible student mappers. */ +public interface StudentDataMapper { + + Optional find(int studentId); + + void insert(Student student) throws DataMapperException; + + void update(Student student) throws DataMapperException; + + void delete(Student student) throws DataMapperException; +} diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java index 685a439ac60c..67ddc0ce6f1a 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java @@ -1,105 +1,74 @@ -/** - * The MIT License Copyright (c) 2016 Amit Dixit +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * - * 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 + * The MIT License + * Copyright © 2014-2022 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 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. + * 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.datamapper; import java.util.ArrayList; import java.util.List; import java.util.Optional; +import lombok.Getter; -/** - * Implementation of Actions on Students Data - */ +/** Implementation of Actions on Students Data. */ +@Getter public final class StudentDataMapperImpl implements StudentDataMapper { /* Note: Normally this would be in the form of an actual database */ - private List students = new ArrayList<>(); + private final List students = new ArrayList<>(); @Override public Optional find(int studentId) { - - /* Compare with existing students */ - for (final Student student : this.getStudents()) { - - /* Check if student is found */ - if (student.getStudentId() == studentId) { - - return Optional.of(student); - } - } - - /* Return empty value */ - return Optional.empty(); + return this.getStudents().stream().filter(x -> x.getStudentId() == studentId).findFirst(); } @Override public void update(Student studentToBeUpdated) throws DataMapperException { - - - /* Check with existing students */ - if (this.getStudents().contains(studentToBeUpdated)) { - - /* Get the index of student in list */ - final int index = this.getStudents().indexOf(studentToBeUpdated); - - /* Update the student in list */ - this.getStudents().set(index, studentToBeUpdated); - - } else { - - /* Throw user error after wrapping in a runtime exception */ - throw new DataMapperException("Student [" + studentToBeUpdated.getName() + "] is not found"); - } + String name = studentToBeUpdated.getName(); + Integer index = + Optional.of(studentToBeUpdated) + .map(Student::getStudentId) + .flatMap(this::find) + .map(students::indexOf) + .orElseThrow(() -> new DataMapperException("Student [" + name + "] is not found")); + students.set(index, studentToBeUpdated); } @Override public void insert(Student studentToBeInserted) throws DataMapperException { - - /* Check with existing students */ - if (!this.getStudents().contains(studentToBeInserted)) { - - /* Add student in list */ - this.getStudents().add(studentToBeInserted); - - } else { - - /* Throw user error after wrapping in a runtime exception */ - throw new DataMapperException("Student already [" + studentToBeInserted.getName() + "] exists"); + Optional student = find(studentToBeInserted.getStudentId()); + if (student.isPresent()) { + String name = studentToBeInserted.getName(); + throw new DataMapperException("Student already [" + name + "] exists"); } + + students.add(studentToBeInserted); } @Override public void delete(Student studentToBeDeleted) throws DataMapperException { - - /* Check with existing students */ - if (this.getStudents().contains(studentToBeDeleted)) { - - /* Delete the student from list */ - this.getStudents().remove(studentToBeDeleted); - - } else { - - /* Throw user error after wrapping in a runtime exception */ - throw new DataMapperException("Student [" + studentToBeDeleted.getName() + "] is not found"); + if (!students.remove(studentToBeDeleted)) { + String name = studentToBeDeleted.getName(); + throw new DataMapperException("Student [" + name + "] is not found"); } } - - public List getStudents() { - return this.students; - } } diff --git a/data-mapper/src/main/resources/log4j.xml b/data-mapper/src/main/resources/log4j.xml deleted file mode 100644 index 14f043ff7576..000000000000 --- a/data-mapper/src/main/resources/log4j.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java index 5c665a4e470d..a7118721dc36 100644 --- a/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java +++ b/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java @@ -1,33 +1,44 @@ -/** - * The MIT License Copyright (c) 2016 Amit Dixit - * - * 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.datamapper; - -import org.junit.jupiter.api.Test; - -/** - * Tests that Data-Mapper example runs without errors. - */ -public final class AppTest { - - @Test - public void test() { - final String[] args = {}; - App.main(args); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datamapper; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +/** Tests that Data-Mapper example runs without errors. */ +final class AppTest { + + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow((Executable) App::main); + } +} diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java index 5f63cf045ce4..53782b7eb6eb 100644 --- a/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java +++ b/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java @@ -1,26 +1,33 @@ -/** - * The MIT License Copyright (c) 2016 Amit Dixit +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 + * 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 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. + * 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.datamapper; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.Test; /** * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the @@ -29,41 +36,42 @@ * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper , * Data Mapper itself is even unknown to the domain layer. + * *

    */ -public class DataMapperTest { +class DataMapperTest { - /** - * This test verify that first data mapper is able to perform all CRUD operations on Student - */ + /** This test verify that first data mapper is able to perform all CRUD operations on Student */ @Test - public void testFirstDataMapper() { + void testFirstDataMapper() { /* Create new data mapper of first type */ - final StudentDataMapper mapper = new StudentDataMapperImpl(); + final var mapper = new StudentDataMapperImpl(); /* Create new student */ - Student student = new Student(1, "Adam", 'A'); + var studentId = 1; + var student = new Student(studentId, "Adam", 'A'); /* Add student in respectibe db */ mapper.insert(student); /* Check if student is added in db */ - assertEquals(student.getStudentId(), mapper.find(student.getStudentId()).get().getStudentId()); + assertEquals(studentId, mapper.find(student.getStudentId()).get().getStudentId()); /* Update existing student object */ - student = new Student(student.getStudentId(), "AdamUpdated", 'A'); + var updatedName = "AdamUpdated"; + student = new Student(student.getStudentId(), updatedName, 'A'); /* Update student in respectibe db */ mapper.update(student); /* Check if student is updated in db */ - assertEquals(mapper.find(student.getStudentId()).get().getName(), "AdamUpdated"); + assertEquals(updatedName, mapper.find(student.getStudentId()).get().getName()); /* Delete student in db */ mapper.delete(student); /* Result should be false */ - assertEquals(false, mapper.find(student.getStudentId()).isPresent()); + assertFalse(mapper.find(student.getStudentId()).isPresent()); } } diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java index 523a6509a324..237ea7a3cad6 100644 --- a/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java +++ b/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java @@ -1,55 +1,58 @@ -/** - * The MIT License Copyright (c) 2016 Amit Dixit +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * - * 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 + * The MIT License + * Copyright © 2014-2022 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 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. + * 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.datamapper; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; -/** - * Tests {@link Student}. - */ -public final class StudentTest { +/** Tests {@link Student}. */ +final class StudentTest { - @Test /** - * This API tests the equality behaviour of Student object - * Object Equality should work as per logic defined in equals method + * This API tests the equality behaviour of Student object Object Equality should work as per + * logic defined in equals method * * @throws Exception if any execution error during test */ - public void testEquality() throws Exception { + @Test + void testEquality() { /* Create some students */ - final Student firstStudent = new Student(1, "Adam", 'A'); - final Student secondStudent = new Student(2, "Donald", 'B'); - final Student secondSameStudent = new Student(2, "Donald", 'B'); - final Student firstSameStudent = firstStudent; + final var firstStudent = new Student(1, "Adam", 'A'); + final var secondStudent = new Student(2, "Donald", 'B'); + final var secondSameStudent = new Student(2, "Donald", 'B'); /* Check equals functionality: should return 'true' */ - assertTrue(firstStudent.equals(firstSameStudent)); + assertEquals(firstStudent, firstStudent); /* Check equals functionality: should return 'false' */ - assertFalse(firstStudent.equals(secondStudent)); + assertNotEquals(firstStudent, secondStudent); /* Check equals functionality: should return 'true' */ - assertTrue(secondStudent.equals(secondSameStudent)); + assertEquals(secondStudent, secondSameStudent); } } diff --git a/data-transfer-object/README.md b/data-transfer-object/README.md index ad9b9f4e2198..6248676013ae 100644 --- a/data-transfer-object/README.md +++ b/data-transfer-object/README.md @@ -1,30 +1,218 @@ --- -layout: pattern -title: Data Transfer Object -folder: data-transfer-object -permalink: /patterns/data-transfer-object/ -categories: Architectural -tags: - - Java - - KISS - - YAGNI - - Difficulty-Beginner +title: "Data Transfer Object Pattern in Java: Simplifying Data Exchange Between Subsystems" +shortTitle: Data Transfer Object (DTO) +description: "Learn about the Data Transfer Object (DTO) pattern, its implementation, and practical uses in Java applications. Optimize data transfer between layers with this structural design pattern." +category: Structural +language: en +tag: + - Client-server + - Data transfer + - Decoupling + - Layered architecture + - Optimization --- -## Intent -Pass data with multiple attributes in one shot from client to server, -to avoid multiple calls to remote server. +## Also known as -![alt text](./etc/data-transfer-object.urm.png "data-transfer-object") +* Transfer Object +* Value Object -## Applicability -Use the Data Transfer Object pattern when +## Intent of Data Transfer Object Design Pattern -* 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. +The Data Transfer Object (DTO) pattern is used to transfer data between software application subsystems or layers, particularly in the context of network calls or database retrieval in Java applications. It reduces the number of method calls by aggregating the data in a single transfer. -## Credits +## Detailed Explanation of Data Transfer Object Pattern with Real-World Examples -* [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) +Real-world example + +> Imagine a large company with several departments (e.g., Sales, HR, and IT) needing to share employee information efficiently. Instead of each department querying and retrieving data like name, address, and role individually, they use a courier service to bundle this data into a single package. This package, representing a Data Transfer Object (DTO), allows the departments to easily receive and process comprehensive employee data without making multiple requests. This simplifies data handling, reduces communication overhead, and ensures a standardized format across the company. + +In plain words + +> Using DTO, relevant information can be fetched with a single backend query. + +Wikipedia says + +> In the field of programming a data transfer object (DTO) is an object that carries data between processes. The motivation for its use is that communication between processes is usually done resorting to remote interfaces (e.g. web services), where each call is an expensive operation. Because the majority of the cost of each call is related to the round-trip time between the client and the server, one way of reducing the number of calls is to use an object (the DTO) that aggregates the data that would have been transferred by the several calls, but that is served by one call only. + +Sequence diagram + +![Data Transfer Object sequence diagram](./etc/dto-sequence-diagram.png) + +## Programmatic Example of DTO Pattern in Java + +Let's first introduce our simple `CustomerDTO` record. + +```java +public record CustomerDto(String id, String firstName, String lastName) {} +``` + +`CustomerResource` record acts as the server for customer information. + +```java +public record CustomerResource(List customers) { + + public void save(CustomerDto customer) { + customers.add(customer); + } + + public void delete(String customerId) { + customers.removeIf(customer -> customer.id().equals(customerId)); + } +} +``` + +Now fetching customer information is easy since we have the DTOs. The 2nd example uses `ProductDTO` similarly. + +```java +public class App { + + public static void main(String[] args) { + + // Example 1: Customer DTO + var customerOne = new CustomerDto("1", "Kelly", "Brown"); + var customerTwo = new CustomerDto("2", "Alfonso", "Bass"); + var customers = new ArrayList<>(List.of(customerOne, customerTwo)); + + var customerResource = new CustomerResource(customers); + + LOGGER.info("All customers:"); + var allCustomers = customerResource.customers(); + printCustomerDetails(allCustomers); + + LOGGER.info("----------------------------------------------------------"); + + LOGGER.info("Deleting customer with id {1}"); + customerResource.delete(customerOne.id()); + allCustomers = customerResource.customers(); + printCustomerDetails(allCustomers); + + LOGGER.info("----------------------------------------------------------"); + + LOGGER.info("Adding customer three}"); + var customerThree = new CustomerDto("3", "Lynda", "Blair"); + customerResource.save(customerThree); + allCustomers = customerResource.customers(); + printCustomerDetails(allCustomers); + + // Example 2: Product DTO + + Product tv = Product.builder().id(1L).name("TV").supplier("Sony").price(1000D).cost(1090D).build(); + Product microwave = + Product.builder() + .id(2L) + .name("microwave") + .supplier("Delonghi") + .price(1000D) + .cost(1090D).build(); + Product refrigerator = + Product.builder() + .id(3L) + .name("refrigerator") + .supplier("Botsch") + .price(1000D) + .cost(1090D).build(); + Product airConditioner = + Product.builder() + .id(4L) + .name("airConditioner") + .supplier("LG") + .price(1000D) + .cost(1090D).build(); + List products = + new ArrayList<>(Arrays.asList(tv, microwave, refrigerator, airConditioner)); + ProductResource productResource = new ProductResource(products); + + LOGGER.info( + "####### List of products including sensitive data just for admins: \n {}", + Arrays.toString(productResource.getAllProductsForAdmin().toArray())); + LOGGER.info( + "####### List of products for customers: \n {}", + Arrays.toString(productResource.getAllProductsForCustomer().toArray())); + + LOGGER.info("####### Going to save Sony PS5 ..."); + ProductDto.Request.Create createProductRequestDto = + new ProductDto.Request.Create() + .setName("PS5") + .setCost(1000D) + .setPrice(1220D) + .setSupplier("Sony"); + productResource.save(createProductRequestDto); + LOGGER.info( + "####### List of products after adding PS5: {}", + Arrays.toString(productResource.products().toArray())); + } + + private static void printCustomerDetails(List allCustomers) { + allCustomers.forEach(customer -> LOGGER.info(customer.firstName())); + } +} +``` + +The console output: + +``` +11:10:51.838 [main] INFO com.iluwatar.datatransfer.App -- All customers: +11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Kelly +11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Alfonso +11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- ---------------------------------------------------------- +11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Deleting customer with id {1} +11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Alfonso +11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- ---------------------------------------------------------- +11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Adding customer three} +11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Alfonso +11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Lynda +11:10:51.848 [main] INFO com.iluwatar.datatransfer.App -- ####### List of products including sensitive data just for admins: + [Private{id=1, name='TV', price=1000.0, cost=1090.0}, Private{id=2, name='microwave', price=1000.0, cost=1090.0}, Private{id=3, name='refrigerator', price=1000.0, cost=1090.0}, Private{id=4, name='airConditioner', price=1000.0, cost=1090.0}] +11:10:51.852 [main] INFO com.iluwatar.datatransfer.App -- ####### List of products for customers: + [Public{id=1, name='TV', price=1000.0}, Public{id=2, name='microwave', price=1000.0}, Public{id=3, name='refrigerator', price=1000.0}, Public{id=4, name='airConditioner', price=1000.0}] +11:10:51.852 [main] INFO com.iluwatar.datatransfer.App -- ####### Going to save Sony PS5 ... +11:10:51.856 [main] INFO com.iluwatar.datatransfer.App -- ####### List of products after adding PS5: [Product{id=1, name='TV', price=1000.0, cost=1090.0, supplier='Sony'}, Product{id=2, name='microwave', price=1000.0, cost=1090.0, supplier='Delonghi'}, Product{id=3, name='refrigerator', price=1000.0, cost=1090.0, supplier='Botsch'}, Product{id=4, name='airConditioner', price=1000.0, cost=1090.0, supplier='LG'}, Product{id=5, name='PS5', price=1220.0, cost=1000.0, supplier='Sony'}] +``` + +## When to Use the Data Transfer Object Pattern in Java + +Use the Data Transfer Object pattern when: + +* When you need to optimize network traffic by reducing the number of calls, especially in a client-server architecture. +* In scenarios where batch processing of data is preferred over individual processing. +* When working with remote interfaces, to encapsulate the data transfer in a serializable object that can be easily transmitted. + +## Data Transfer Object Pattern Java Tutorials + +* [Data Transfer Object Pattern in Java - Implementation and Mapping (StackAbuse)](https://stackabuse.com/data-transfer-object-pattern-in-java-implementation-and-mapping/) +* [Design Pattern - Transfer Object Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/transfer_object_pattern.htm) +* [The DTO Pattern (Baeldung)](https://www.baeldung.com/java-dto-pattern) + +## Real-World Applications of DTO Pattern in Java + +* Remote Method Invocation (RMI) in Java, where DTOs are used to pass data across network. +* Enterprise JavaBeans (EJB), particularly when data needs to be transferred from EJBs to clients. +* Various web service frameworks where DTOs encapsulate request and response data. + +## Benefits and Trade-offs of Data Transfer Object Pattern + +Benefits: + +* Reduces network calls, thereby improving application performance. +* Decouples the client from the server, leading to more modular and maintainable code. +* Simplifies data transmission over the network by aggregating data into single objects. + +Trade-offs: + +* Introduces additional classes into the application, which may increase complexity. +* Can lead to redundant data structures that mirror domain models, potentially causing synchronization issues. +* May encourage design that leads to an anemic domain model, where business logic is separated from data. + +## Related Patterns + +* [Composite Entity](https://java-design-patterns.com/patterns/composite-entity/): DTOs may be used to represent composite entities, particularly in persistence mechanisms. +* [Facade](https://java-design-patterns.com/patterns/facade/): Similar to DTO, a Facade may aggregate multiple calls into one, improving efficiency. +* [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Often involves using DTOs to transfer data across the boundary between the service layer and its clients. + +## References and Credits + +* [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cKndQp) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) +* [Data Transfer Object (Microsoft)](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 index 15f777aad60c..66236f32dd14 100644 --- a/data-transfer-object/etc/data-transfer-object.ucls +++ b/data-transfer-object/etc/data-transfer-object.ucls @@ -1,7 +1,7 @@ - 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 000000000000..ee96c37ca967 --- /dev/null +++ b/data-transfer-object/etc/data-transfer-object.urm.puml @@ -0,0 +1,27 @@ +@startuml +package com.iluwatar.datatransfer { + class CustomerClientApp { + - LOGGER : Logger {static} + + 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/etc/dto-sequence-diagram.png b/data-transfer-object/etc/dto-sequence-diagram.png new file mode 100644 index 000000000000..3fd59695e552 Binary files /dev/null and b/data-transfer-object/etc/dto-sequence-diagram.png differ diff --git a/data-transfer-object/pom.xml b/data-transfer-object/pom.xml index 17ad1f83fbc5..5370250f6959 100644 --- a/data-transfer-object/pom.xml +++ b/data-transfer-object/pom.xml @@ -1,8 +1,10 @@ - + - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - data-transfer-object - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - log4j - log4j - - + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + data-transfer-object + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.datatransfer.App + + + + + + + + diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java new file mode 100644 index 000000000000..0a6fc9f041d5 --- /dev/null +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java @@ -0,0 +1,143 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datatransfer; + +import com.iluwatar.datatransfer.customer.CustomerDto; +import com.iluwatar.datatransfer.customer.CustomerResource; +import com.iluwatar.datatransfer.product.Product; +import com.iluwatar.datatransfer.product.ProductDto; +import com.iluwatar.datatransfer.product.ProductResource; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import lombok.extern.slf4j.Slf4j; + +/** + * 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 the first example, {@link App} is a customer details consumer i.e. client to request for + * customer details to server. {@link CustomerResource} act as server to serve customer information. + * {@link CustomerDto} is data transfer object to share customer information. + * + *

    In the second example, {@link App} is a product details consumer i.e. client to request for + * product details to server. {@link ProductResource} acts as server to serve product information. + * {@link ProductDto} is data transfer object to share product information. + * + *

    The pattern implementation is a bit different in each of the examples. The first can be + * thought as a traditional example and the second is an enum based implementation. + */ +@Slf4j +public class App { + + /** + * Method as act client and request to server for details. + * + * @param args program argument. + */ + public static void main(String[] args) { + + // Example 1: Customer DTO + var customerOne = new CustomerDto("1", "Kelly", "Brown"); + var customerTwo = new CustomerDto("2", "Alfonso", "Bass"); + var customers = new ArrayList<>(List.of(customerOne, customerTwo)); + + var customerResource = new CustomerResource(customers); + + LOGGER.info("All customers:"); + var allCustomers = customerResource.customers(); + printCustomerDetails(allCustomers); + + LOGGER.info("----------------------------------------------------------"); + + LOGGER.info("Deleting customer with id {1}"); + customerResource.delete(customerOne.id()); + allCustomers = customerResource.customers(); + printCustomerDetails(allCustomers); + + LOGGER.info("----------------------------------------------------------"); + + LOGGER.info("Adding customer three}"); + var customerThree = new CustomerDto("3", "Lynda", "Blair"); + customerResource.save(customerThree); + allCustomers = customerResource.customers(); + printCustomerDetails(allCustomers); + + // Example 2: Product DTO + + Product tv = + Product.builder().id(1L).name("TV").supplier("Sony").price(1000D).cost(1090D).build(); + Product microwave = + Product.builder() + .id(2L) + .name("microwave") + .supplier("Delonghi") + .price(1000D) + .cost(1090D) + .build(); + Product refrigerator = + Product.builder() + .id(3L) + .name("refrigerator") + .supplier("Botsch") + .price(1000D) + .cost(1090D) + .build(); + Product airConditioner = + Product.builder() + .id(4L) + .name("airConditioner") + .supplier("LG") + .price(1000D) + .cost(1090D) + .build(); + List products = + new ArrayList<>(Arrays.asList(tv, microwave, refrigerator, airConditioner)); + ProductResource productResource = new ProductResource(products); + + LOGGER.info( + "####### List of products including sensitive data just for admins: \n {}", + Arrays.toString(productResource.getAllProductsForAdmin().toArray())); + LOGGER.info( + "####### List of products for customers: \n {}", + Arrays.toString(productResource.getAllProductsForCustomer().toArray())); + + LOGGER.info("####### Going to save Sony PS5 ..."); + ProductDto.Request.Create createProductRequestDto = + new ProductDto.Request.Create() + .setName("PS5") + .setCost(1000D) + .setPrice(1220D) + .setSupplier("Sony"); + productResource.save(createProductRequestDto); + LOGGER.info( + "####### List of products after adding PS5: {}", + Arrays.toString(productResource.products().toArray())); + } + + private static void printCustomerDetails(List allCustomers) { + allCustomers.forEach(customer -> LOGGER.info(customer.firstName())); + } +} 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 deleted file mode 100644 index f5fcebe03a0b..000000000000 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerClientApp.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * 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 deleted file mode 100644 index 7dedf891c087..000000000000 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerDto.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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 deleted file mode 100644 index a4926d08c134..000000000000 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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/main/java/com/iluwatar/datatransfer/customer/CustomerDto.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerDto.java new file mode 100644 index 000000000000..64e44f64dfe4 --- /dev/null +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerDto.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datatransfer.customer; + +/** + * {@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 record CustomerDto(String id, String firstName, String lastName) {} diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerResource.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerResource.java new file mode 100644 index 000000000000..427c87521af1 --- /dev/null +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerResource.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datatransfer.customer; + +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 record CustomerResource(List customers) { + /** + * Save new customer. + * + * @param customer save new customer to list. + */ + public void save(CustomerDto customer) { + customers.add(customer); + } + + /** + * Delete customer with given id. + * + * @param customerId delete customer with id {@code customerId} + */ + public void delete(String customerId) { + customers.removeIf(customer -> customer.id().equals(customerId)); + } +} diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java new file mode 100644 index 000000000000..a29fda1589cd --- /dev/null +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datatransfer.product; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** {@link Product} is a entity class for product entity. This class act as entity in the demo. */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public final class Product { + private Long id; + private String name; + private Double price; + private Double cost; + private String supplier; + + @Override + public String toString() { + return "Product{" + + "id=" + + id + + ", name='" + + name + + '\'' + + ", price=" + + price + + ", cost=" + + cost + + ", supplier='" + + supplier + + '\'' + + '}'; + } +} diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductDto.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductDto.java new file mode 100644 index 000000000000..d254e2fc1ce3 --- /dev/null +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductDto.java @@ -0,0 +1,256 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datatransfer.product; + +/** + * {@link ProductDto} 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 enum ProductDto { + ; + + /** + * This is Request class which consist of Create or any other request DTO's you might want to use + * in your API. + */ + public enum Request { + ; + + /** This is Create dto class for requesting create new product. */ + public static final class Create implements Name, Price, Cost, Supplier { + private String name; + private Double price; + private Double cost; + private String supplier; + + @Override + public String getName() { + return name; + } + + public Create setName(String name) { + this.name = name; + return this; + } + + @Override + public Double getPrice() { + return price; + } + + public Create setPrice(Double price) { + this.price = price; + return this; + } + + @Override + public Double getCost() { + return cost; + } + + public Create setCost(Double cost) { + this.cost = cost; + return this; + } + + @Override + public String getSupplier() { + return supplier; + } + + public Create setSupplier(String supplier) { + this.supplier = supplier; + return this; + } + } + } + + /** + * This is Response class which consist of any response DTO's you might want to provide to your + * clients. + */ + public enum Response { + ; + + /** This is Public dto class for API response with the lowest data security. */ + public static final class Public implements Id, Name, Price { + private Long id; + private String name; + private Double price; + + @Override + public Long getId() { + return id; + } + + public Public setId(Long id) { + this.id = id; + return this; + } + + @Override + public String getName() { + return name; + } + + public Public setName(String name) { + this.name = name; + return this; + } + + @Override + public Double getPrice() { + return price; + } + + public Public setPrice(Double price) { + this.price = price; + return this; + } + + @Override + public String toString() { + return "Public{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + '}'; + } + } + + /** This is Private dto class for API response with the highest data security. */ + public static final class Private implements Id, Name, Price, Cost { + private Long id; + private String name; + private Double price; + private Double cost; + + @Override + public Long getId() { + return id; + } + + public Private setId(Long id) { + this.id = id; + return this; + } + + @Override + public String getName() { + return name; + } + + public Private setName(String name) { + this.name = name; + return this; + } + + @Override + public Double getPrice() { + return price; + } + + public Private setPrice(Double price) { + this.price = price; + return this; + } + + @Override + public Double getCost() { + return cost; + } + + public Private setCost(Double cost) { + this.cost = cost; + return this; + } + + @Override + public String toString() { + return "Private{" + + "id=" + + id + + ", name='" + + name + + '\'' + + ", price=" + + price + + ", cost=" + + cost + + '}'; + } + } + } + + /** Use this interface whenever you want to provide the product Id in your DTO. */ + private interface Id { + /** + * Unique identifier of the product. + * + * @return : id of the product. + */ + Long getId(); + } + + /** Use this interface whenever you want to provide the product Name in your DTO. */ + private interface Name { + /** + * The name of the product. + * + * @return : name of the product. + */ + String getName(); + } + + /** Use this interface whenever you want to provide the product Price in your DTO. */ + private interface Price { + /** + * The amount we sell a product for. This data is not confidential + * + * @return : price of the product. + */ + Double getPrice(); + } + + /** Use this interface whenever you want to provide the product Cost in your DTO. */ + private interface Cost { + /** + * The amount that it costs us to purchase this product For the amount we sell a product for, + * see the {@link Price Price} parameter. This data is confidential + * + * @return : cost of the product. + */ + Double getCost(); + } + + /** Use this interface whenever you want to provide the product Supplier in your DTO. */ + private interface Supplier { + /** + * The name of supplier of the product or its manufacturer. This data is highly + * confidential + * + * @return : supplier of the product. + */ + String getSupplier(); + } +} diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java new file mode 100644 index 000000000000..d0b3fcbd7932 --- /dev/null +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java @@ -0,0 +1,82 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datatransfer.product; + +import java.util.List; + +/** + * The resource class which serves product information. This class act as server in the demo. Which + * has all product details. + */ +public record ProductResource(List products) { + /** + * Get all products. + * + * @return : all products in list but in the scheme of private dto. + */ + public List getAllProductsForAdmin() { + return products.stream() + .map( + p -> + new ProductDto.Response.Private() + .setId(p.getId()) + .setName(p.getName()) + .setCost(p.getCost()) + .setPrice(p.getPrice())) + .toList(); + } + + /** + * Get all products. + * + * @return : all products in list but in the scheme of public dto. + */ + public List getAllProductsForCustomer() { + return products.stream() + .map( + p -> + new ProductDto.Response.Public() + .setId(p.getId()) + .setName(p.getName()) + .setPrice(p.getPrice())) + .toList(); + } + + /** + * Save new product. + * + * @param createProductDto save new product to list. + */ + public void save(ProductDto.Request.Create createProductDto) { + products.add( + Product.builder() + .id((long) (products.size() + 1)) + .name(createProductDto.getName()) + .supplier(createProductDto.getSupplier()) + .price(createProductDto.getPrice()) + .cost(createProductDto.getCost()) + .build()); + } +} diff --git a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java new file mode 100644 index 000000000000..d0e32976c4f7 --- /dev/null +++ b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datatransfer; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} 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 deleted file mode 100644 index db669b785f1f..000000000000 --- a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.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/data-transfer-object/src/test/java/com/iluwatar/datatransfer/customer/CustomerResourceTest.java b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/customer/CustomerResourceTest.java new file mode 100644 index 000000000000..006fd0b23bf8 --- /dev/null +++ b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/customer/CustomerResourceTest.java @@ -0,0 +1,73 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.datatransfer.customer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** tests {@link CustomerResource}. */ +class CustomerResourceTest { + + @Test + void shouldGetAllCustomers() { + var customers = List.of(new CustomerDto("1", "Melody", "Yates")); + var customerResource = new CustomerResource(customers); + var allCustomers = customerResource.customers(); + + assertEquals(1, allCustomers.size()); + assertEquals("1", allCustomers.get(0).id()); + assertEquals("Melody", allCustomers.get(0).firstName()); + assertEquals("Yates", allCustomers.get(0).lastName()); + } + + @Test + void shouldSaveCustomer() { + var customer = new CustomerDto("1", "Rita", "Reynolds"); + var customerResource = new CustomerResource(new ArrayList<>()); + + customerResource.save(customer); + + var allCustomers = customerResource.customers(); + assertEquals("1", allCustomers.get(0).id()); + assertEquals("Rita", allCustomers.get(0).firstName()); + assertEquals("Reynolds", allCustomers.get(0).lastName()); + } + + @Test + void shouldDeleteCustomer() { + var customer = new CustomerDto("1", "Terry", "Nguyen"); + var customers = new ArrayList<>(List.of(customer)); + var customerResource = new CustomerResource(customers); + + customerResource.delete(customer.id()); + + var allCustomers = customerResource.customers(); + assertTrue(allCustomers.isEmpty()); + } +} diff --git a/decorator/README.md b/decorator/README.md index 9998b9938220..a7b0bb9ad8b9 100644 --- a/decorator/README.md +++ b/decorator/README.md @@ -1,28 +1,31 @@ --- -layout: pattern -title: Decorator -folder: decorator -permalink: /patterns/decorator/ -categories: Structural -tags: - - Java - - Gang Of Four - - Difficulty-Beginner +title: "Decorator Pattern in Java: Extending Classes Dynamically" +shortTitle: Decorator +description: "Learn how the Decorator Design Pattern enhances flexibility in Java programming by allowing dynamic addition of responsibilities to objects without modifying their existing code. Explore real-world examples and implementation." +category: Structural +language: en +tag: + - Enhancement + - Extensibility + - Gang of Four + - Object composition + - Wrapping --- ## Also known as -Wrapper -## Intent -Attach additional responsibilities to an object dynamically. -Decorators provide a flexible alternative to subclassing for extending -functionality. +* Smart Proxy +* Wrapper -## Explanation +## Intent of Decorator Design Pattern -Real world example +The Decorator pattern allows for the dynamic addition of responsibilities to objects without modifying their existing code. It achieves this by providing a way to "wrap" objects within objects of similar interface, enhancing Java design patterns flexibility. -> 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. +## Detailed Explanation of Decorator Pattern with Real-World Examples + +Real-world example + +> Imagine a coffee shop where you can customize your coffee order. You start with a basic coffee, and you can add different ingredients like milk, sugar, whipped cream, and so on. Each addition is like a decorator in the Decorator design pattern. The base coffee object can be decorated with additional functionality (flavors, toppings) dynamically. For example, you can start with a plain coffee object, then wrap it with a milk decorator, followed by a sugar decorator, and finally a whipped cream decorator. Each decorator adds new features or modifies the behavior of the coffee object, similar to how the Decorator pattern works in software design. In plain words @@ -30,105 +33,157 @@ In plain words 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. +> 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 as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified. + +Sequence diagram -**Programmatic Example** +![Decorator sequence diagram](./etc/decorator-sequence-diagram.png) -Let's take the troll example. First of all we have a simple troll implementing the troll interface +## Programmatic Example of Decorator Pattern in Java + +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. + +First, we have a `SimpleTroll` implementing the `Troll` interface: ```java public interface Troll { - void attack(); - int getAttackPower(); - void fleeBattle(); + void attack(); + + int getAttackPower(); + + void fleeBattle(); } +@Slf4j 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 void attack() { + LOGGER.info("The troll tries to grab you!"); + } - @Override - public int getAttackPower() { - return 10; - } + @Override + public int getAttackPower() { + return 10; + } - @Override - public void fleeBattle() { - LOGGER.info("The troll shrieks in horror and runs away!"); - } + @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 +Next, we want to add a club for the troll. We can do it dynamically by using a decorator: ```java +@Slf4j +@RequiredArgsConstructor public class ClubbedTroll implements Troll { - private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class); + private final Troll decorated; - private Troll decorated; + @Override + public void attack() { + decorated.attack(); + LOGGER.info("The troll swings at you with a club!"); + } - public ClubbedTroll(Troll decorated) { - this.decorated = decorated; - } + @Override + public int getAttackPower() { + return decorated.getAttackPower() + 10; + } - @Override - public void attack() { - decorated.attack(); - LOGGER.info("The troll swings at you with a club!"); - } + @Override + public void fleeBattle() { + decorated.fleeBattle(); + } +} +``` - @Override - public int getAttackPower() { - return decorated.getAttackPower() + 10; - } +Here's the troll in action: - @Override - public void fleeBattle() { - decorated.fleeBattle(); - } +```java + public static void main(String[] args) { + + // simple troll + LOGGER.info("A simple looking troll approaches."); + var troll = new SimpleTroll(); + troll.attack(); + troll.fleeBattle(); + LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower()); + + // change the behavior of the simple troll by adding a decorator + LOGGER.info("A troll with huge club surprises you."); + var clubbedTroll = new ClubbedTroll(troll); + clubbedTroll.attack(); + clubbedTroll.fleeBattle(); + LOGGER.info("Clubbed troll power: {}.\n", clubbedTroll.getAttackPower()); } ``` -Here's the troll in action +Program output: -```java -// 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 = new ClubbedTroll(troll); -troll.attack(); // The troll tries to grab you! The troll swings at you with a club! -troll.fleeBattle(); // The troll shrieks in horror and runs away! ``` +11:34:18.098 [main] INFO com.iluwatar.decorator.App -- A simple looking troll approaches. +11:34:18.100 [main] INFO com.iluwatar.decorator.SimpleTroll -- The troll tries to grab you! +11:34:18.100 [main] INFO com.iluwatar.decorator.SimpleTroll -- The troll shrieks in horror and runs away! +11:34:18.100 [main] INFO com.iluwatar.decorator.App -- Simple troll power: 10. + +11:34:18.100 [main] INFO com.iluwatar.decorator.App -- A troll with huge club surprises you. +11:34:18.101 [main] INFO com.iluwatar.decorator.SimpleTroll -- The troll tries to grab you! +11:34:18.101 [main] INFO com.iluwatar.decorator.ClubbedTroll -- The troll swings at you with a club! +11:34:18.101 [main] INFO com.iluwatar.decorator.SimpleTroll -- The troll shrieks in horror and runs away! +11:34:18.101 [main] INFO com.iluwatar.decorator.App -- Clubbed troll power: 20. +``` + +## When to Use the Decorator Pattern in Java + +Decorator is used to: + +* Add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects, a key feature of Java design patterns. +* For responsibilities that can be withdrawn. +* When extending a class is impractical due to the proliferation of subclasses that could result. +* For when a class definition might be hidden or otherwise unavailable for subclassing. + +## Decorator Pattern Java Tutorials + +* [Decorator Design Pattern in Java Example (DigitalOcean)](https://www.digitalocean.com/community/tutorials/decorator-design-pattern-in-java-example) + +## Real-World Applications of Decorator Pattern in Java + +* GUI toolkits often use decorators to dynamically add behaviors like scrolling, borders, or layout management to components. +* The [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) and [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) classes in Java are well-known examples utilizing the Decorator pattern. +* [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-) +* [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-) +* [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-) + +## Benefits and Trade-offs of Decorator Pattern + +Benefits: -## Applicability -Use Decorator +* Greater flexibility than static inheritance. +* Avoids feature-laden classes high up in the hierarchy, showcasing the power of Java design patterns. +* A decorator and its component aren't identical. +* Responsibilities can be added or removed at runtime. -* To add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects -* For responsibilities that can be withdrawn -* When extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing +Trade-offs: -## Tutorial -* [Decorator Pattern Tutorial](https://www.journaldev.com/1540/decorator-design-pattern-in-java-example) +* A decorator and its component aren't identical, so tests for object type will fail. +* Decorators can lead to a system with lots of small objects that look alike to the programmer, making the desired configuration hard to achieve. +* Overuse can complicate the code structure due to the introduction of numerous small classes. -## Real world examples - * [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), - [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) and [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) - * [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-) - * [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-) - * [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-) +## Related Java Design Patterns +* [Adapter](https://java-design-patterns.com/patterns/adapter/): A decorator changes an object's responsibilities, while an adapter changes an object's interface. +* [Composite](https://java-design-patterns.com/patterns/composite/): Decorators can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities—it isn't intended for object aggregation. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Decorator lets you change the skin of an object, while Strategy lets you change the guts. -## Credits +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) -* [Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions](http://www.amazon.com/Functional-Programming-Java-Harnessing-Expressions/dp/1937785467/ref=sr_1_1) -* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Functional Programming in Java](https://amzn.to/3JUIc5Q) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/4aKFTgS) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/decorator/etc/decorator-sequence-diagram.png b/decorator/etc/decorator-sequence-diagram.png new file mode 100644 index 000000000000..edf3ea5c31ef Binary files /dev/null and b/decorator/etc/decorator-sequence-diagram.png differ diff --git a/decorator/etc/decorator.urm.png b/decorator/etc/decorator.urm.png new file mode 100644 index 000000000000..141c0563f0c6 Binary files /dev/null and b/decorator/etc/decorator.urm.png differ diff --git a/decorator/etc/decorator.urm.puml b/decorator/etc/decorator.urm.puml new file mode 100644 index 000000000000..edfd927600f5 --- /dev/null +++ b/decorator/etc/decorator.urm.puml @@ -0,0 +1,32 @@ +@startuml +package com.iluwatar.decorator { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class ClubbedTroll { + - LOGGER : Logger {static} + - decorated : Troll + + ClubbedTroll(decorated : Troll) + + attack() + + fleeBattle() + + getAttackPower() : int + } + class SimpleTroll { + - LOGGER : Logger {static} + + SimpleTroll() + + attack() + + fleeBattle() + + getAttackPower() : int + } + interface Troll { + + attack() {abstract} + + fleeBattle() {abstract} + + getAttackPower() : int {abstract} + } +} +ClubbedTroll --> "-decorated" Troll +ClubbedTroll ..|> Troll +SimpleTroll ..|> Troll +@enduml \ No newline at end of file diff --git a/decorator/pom.xml b/decorator/pom.xml index d4e2a887d49f..380e3a6347e1 100644 --- a/decorator/pom.xml +++ b/decorator/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT decorator - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.decorator.App + + + + + + + + diff --git a/decorator/src/main/java/com/iluwatar/decorator/App.java b/decorator/src/main/java/com/iluwatar/decorator/App.java index 5b072b9c2dc5..150258380148 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/App.java +++ b/decorator/src/main/java/com/iluwatar/decorator/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,44 +24,40 @@ */ package com.iluwatar.decorator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * * The Decorator pattern is a more flexible alternative to subclassing. The Decorator class - * implements the same interface as the target and uses aggregation to "decorate" calls to the + * implements the same interface as the target and uses composition to "decorate" calls to the * target. Using the Decorator pattern it is possible to change the behavior of the class during * runtime. - *

    - * In this example we show how the simple {@link SimpleTroll} first attacks and then flees the battle. - * Then we decorate the {@link SimpleTroll} with a {@link ClubbedTroll} and perform the attack again. You - * can see how the behavior changes after the decoration. - * + * + *

    In this example we show how the simple {@link SimpleTroll} first attacks and then flees the + * battle. Then we decorate the {@link SimpleTroll} with a {@link ClubbedTroll} and perform the + * attack again. You can see how the behavior changes after the decoration. */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { // simple troll LOGGER.info("A simple looking troll approaches."); - Troll troll = new SimpleTroll(); + var troll = new SimpleTroll(); troll.attack(); troll.fleeBattle(); - LOGGER.info("Simple troll power {}.\n", troll.getAttackPower()); + LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower()); // change the behavior of the simple troll by adding a decorator LOGGER.info("A troll with huge club surprises you."); - troll = new ClubbedTroll(troll); - troll.attack(); - troll.fleeBattle(); - LOGGER.info("Clubbed troll power {}.\n", troll.getAttackPower()); + var clubbedTroll = new ClubbedTroll(troll); + clubbedTroll.attack(); + clubbedTroll.fleeBattle(); + LOGGER.info("Clubbed troll power: {}.\n", clubbedTroll.getAttackPower()); } } diff --git a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java b/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java index edaa334a5976..10110facdacb 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,15 @@ */ package com.iluwatar.decorator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; -/** - * Decorator that adds a club for the troll - */ +/** Decorator that adds a club for the troll. */ +@Slf4j +@RequiredArgsConstructor public class ClubbedTroll implements Troll { - private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class); - - private Troll decorated; - - public ClubbedTroll(Troll decorated) { - this.decorated = decorated; - } + private final Troll decorated; @Override public void attack() { diff --git a/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java b/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java index 5d5e0518381d..2c178961190b 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.decorator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * SimpleTroll implements {@link Troll} interface directly. - * - */ +/** SimpleTroll implements {@link Troll} interface directly. */ +@Slf4j 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!"); diff --git a/decorator/src/main/java/com/iluwatar/decorator/Troll.java b/decorator/src/main/java/com/iluwatar/decorator/Troll.java index ffc7e5b527d9..8c2ff391309e 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/Troll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/Troll.java @@ -1,38 +1,35 @@ -/** - * 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; - -/** - * - * Interface for trolls - * - */ -public interface Troll { - - void attack(); - - int getAttackPower(); - - void fleeBattle(); - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; + +/** Interface for trolls. */ +public interface Troll { + + void attack(); + + int getAttackPower(); + + void fleeBattle(); +} diff --git a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java index 35cc76dbdd8d..9170574468c0 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,19 @@ */ package com.iluwatar.decorator; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java index 5221eb2da0dc..8f06a971236c 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,26 +24,24 @@ */ package com.iluwatar.decorator; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; 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; -/** - * Tests for {@link ClubbedTroll} - */ -public class ClubbedTrollTest { +import org.junit.jupiter.api.Test; + +/** Tests for {@link ClubbedTroll} */ +class ClubbedTrollTest { @Test - public void testClubbedTroll() throws Exception { + void testClubbedTroll() { // Create a normal troll first, but make sure we can spy on it later on. - final Troll simpleTroll = spy(new SimpleTroll()); + final var simpleTroll = spy(new SimpleTroll()); // Now we want to decorate the troll to make it stronger ... - final Troll clubbed = new ClubbedTroll(simpleTroll); + final var clubbed = new ClubbedTroll(simpleTroll); assertEquals(20, clubbed.getAttackPower()); verify(simpleTroll, times(1)).getAttackPower(); diff --git a/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java index 14d944b2eefb..fd14fb9da10e 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,39 +24,36 @@ */ package com.iluwatar.decorator; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Tests for {@link SimpleTroll} - */ -public class SimpleTrollTest { +/** Tests for {@link SimpleTroll} */ +class SimpleTrollTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(SimpleTroll.class); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } @Test - public void testTrollActions() throws Exception { - final SimpleTroll troll = new SimpleTroll(); + void testTrollActions() { + final var troll = new SimpleTroll(); assertEquals(10, troll.getAttackPower()); troll.attack(); @@ -66,11 +65,11 @@ public void testTrollActions() throws Exception { assertEquals(2, appender.getLogSize()); } - private class InMemoryAppender extends AppenderBase { + private static class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); + private final List log = new LinkedList<>(); - public InMemoryAppender(Class clazz) { + InMemoryAppender(Class clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } @@ -80,11 +79,11 @@ protected void append(ILoggingEvent eventObject) { log.add(eventObject); } - public String getLastMessage() { + String getLastMessage() { return log.get(log.size() - 1).getMessage(); } - public int getLogSize() { + int getLogSize() { return log.size(); } } diff --git a/delegation/README.md b/delegation/README.md index e5c0c63760c4..d12b92c370af 100644 --- a/delegation/README.md +++ b/delegation/README.md @@ -1,30 +1,157 @@ --- -layout: pattern -title: Delegation -folder: delegation -permalink: /patterns/delegation/ -categories: Behavioral -tags: - - Java - - Difficulty-Beginner +title: "Delegation Pattern in Java: Mastering Efficient Task Assignment" +shortTitle: Delegation +description: "Explore the Delegation Design Pattern in Java with real-world examples, class diagrams, and its benefits. Learn how to enhance your code flexibility and reuse." +category: Behavioral +language: en +tag: + - Decoupling + - Delegation + - Object composition --- ## Also known as -Proxy Pattern -## Intent -It is a technique where an object expresses certain behavior to the outside but in -reality delegates responsibility for implementing that behaviour to an associated object. +* Helper +* Surrogate -![alt text](./etc/delegation.png "Delegate") +## Intent of Delegation Design Pattern -## Applicability -Use the Delegate pattern in order to achieve the following +To allow an object to delegate responsibility for a task to another helper object. -* Reduce the coupling of methods to their class -* Components that behave identically, but realize that this situation can change in the future. +## Detailed Explanation of Delegation Pattern with Real-World Examples -## Credits +Real-world example +> In a restaurant, the head chef delegates tasks to sous-chefs: one manages grilling, another handles salads, and a third is in charge of desserts. Each sous-chef specializes in their area, allowing the head chef to focus on overall kitchen management. This mirrors the Delegation design pattern, where a main object delegates specific tasks to helper objects, each expert in their domain. + +In plain words + +> Delegation is a design pattern where an object passes on a task to a helper object. + +Wikipedia says + +> In object-oriented programming, delegation refers to evaluating a member (property or method) of one object (the receiver) in the context of another original object (the sender). Delegation can be done explicitly, by passing the sending object to the receiving object, which can be done in any object-oriented language; or implicitly, by the member lookup rules of the language, which requires language support for the feature. + +Sequence diagram + +![Delegation sequence diagram](./etc/delegation-sequence-diagram.png) + +## Programmatic Example of Delegation Pattern in Java + +Let's consider a printing example. + +We have an interface `Printer` and three implementations `CanonPrinter`, `EpsonPrinter` and `HpPrinter`. + +```java +public interface Printer { + void print(final String message); +} + +@Slf4j +public class CanonPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("Canon Printer : {}", message); + } +} + +@Slf4j +public class EpsonPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("Epson Printer : {}", message); + } +} + +@Slf4j +public class HpPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("HP Printer : {}", message); + } +} +``` + +The `PrinterController` can be used as a `Printer` by delegating any work handled by this interface to an object implementing it. + +```java +public class PrinterController implements Printer { + + private final Printer printer; + + public PrinterController(Printer printer) { + this.printer = printer; + } + + @Override + public void print(String message) { + printer.print(message); + } +} +``` + +In the client code, printer controllers can print messages differently depending on the object they're delegating that work to. + +```java +public class App { + + private static final String MESSAGE_TO_PRINT = "hello world"; + + public static void main(String[] args) { + var hpPrinterController = new PrinterController(new HpPrinter()); + var canonPrinterController = new PrinterController(new CanonPrinter()); + var epsonPrinterController = new PrinterController(new EpsonPrinter()); + + hpPrinterController.print(MESSAGE_TO_PRINT); + canonPrinterController.print(MESSAGE_TO_PRINT); + epsonPrinterController.print(MESSAGE_TO_PRINT); + } +} +``` + +Program output: + +``` +HP Printer:hello world +Canon Printer:hello world +Epson Printer:hello world +``` + +## When to Use the Delegation Pattern in Java + +* When you want to pass responsibility from one class to another without inheritance. +* To achieve composition-based reuse instead of inheritance-based. +* When you need to use several interchangeable helper classes at runtime. + +## Real-World Applications of Delegation Pattern in Java + +* Java's java.awt.event package, where listeners are often used to handle events. +* Wrapper classes in Java's Collections Framework (java.util.Collections), which delegate to other collection objects. +* In Spring Framework, delegation is used extensively in the IoC container where beans delegate tasks to other beans. + +## Benefits and Trade-offs of Delegation Pattern + +Benefits: + +* Reduces subclassing: Objects can delegate operations to different objects and change them at runtime, reducing the need for subclassing. +* Encourages reuse: Delegation promotes the reuse of the helper object's code. +* Increases flexibility: By delegating tasks to helper objects, you can change the behavior of your classes at runtime. + +Trade-offs: + +* Runtime Overhead: Delegation can introduce additional layers of indirection, which may result in slight performance costs. +* Complexity: The design can become more complicated since it involves additional classes and interfaces to manage delegation. + +## Related Java Design Patterns + +* [Composite](https://java-design-patterns.com/patterns/composite/): Delegation can be used within a composite pattern to delegate component-specific behavior to child components. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Delegation is often used in the strategy pattern where a context object delegates tasks to a strategy object. +* https://java-design-patterns.com/patterns/proxy/: The proxy pattern is a form of delegation where a proxy object controls access to another object, which it delegates work to. + +## References and Credits + +* [Effective Java](https://amzn.to/4aGE7gX) +* [Head First Design Patterns](https://amzn.to/3J9tuaB) +* [Refactoring: Improving the Design of Existing Code](https://amzn.to/3VOcRsw) * [Delegate Pattern: Wikipedia ](https://en.wikipedia.org/wiki/Delegation_pattern) -* [Proxy Pattern: Wikipedia ](https://en.wikipedia.org/wiki/Proxy_pattern) diff --git a/delegation/etc/delegation-sequence-diagram.png b/delegation/etc/delegation-sequence-diagram.png new file mode 100644 index 000000000000..2d07f712d4cb Binary files /dev/null and b/delegation/etc/delegation-sequence-diagram.png differ diff --git a/delegation/etc/delegation.urm.puml b/delegation/etc/delegation.urm.puml new file mode 100644 index 000000000000..169f7103f061 --- /dev/null +++ b/delegation/etc/delegation.urm.puml @@ -0,0 +1,39 @@ +@startuml +package com.iluwatar.delegation.simple.printers { + class CanonPrinter { + - LOGGER : Logger {static} + + CanonPrinter() + + print(message : String) + } + class EpsonPrinter { + - LOGGER : Logger {static} + + EpsonPrinter() + + print(message : String) + } + class HpPrinter { + - LOGGER : Logger {static} + + HpPrinter() + + print(message : String) + } +} +package com.iluwatar.delegation.simple { + class App { + - MESSAGE_TO_PRINT : String {static} + + App() + + main(args : String[]) {static} + } + interface Printer { + + print(String) {abstract} + } + class PrinterController { + - printer : Printer + + PrinterController(printer : Printer) + + print(message : String) + } +} +PrinterController --> "-printer" Printer +PrinterController ..|> Printer +CanonPrinter ..|> Printer +EpsonPrinter ..|> Printer +HpPrinter ..|> Printer +@enduml \ No newline at end of file diff --git a/delegation/pom.xml b/delegation/pom.xml index 6c7c710d5b58..ec9c1c76a1cb 100644 --- a/delegation/pom.xml +++ b/delegation/pom.xml @@ -1,8 +1,10 @@ - - - - java-design-patterns - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - - delegation - - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - \ No newline at end of file + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + delegation + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.delegation.simple.App + + + + + + + + + diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/App.java b/delegation/src/main/java/com/iluwatar/delegation/simple/App.java index 5f410d09bb8a..a7c6dff3a0fd 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/App.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -27,34 +29,35 @@ import com.iluwatar.delegation.simple.printers.HpPrinter; /** - * The delegate pattern provides a mechanism to abstract away the implementation and control of the desired action. - * The class being called in this case {@link PrinterController} is not responsible for the actual desired action, - * but is actually delegated to a helper class either {@link CanonPrinter}, {@link EpsonPrinter} or {@link HpPrinter}. - * The consumer does not have or require knowledge of the actual class carrying out the action, only the - * container on which they are calling. + * The delegate pattern provides a mechanism to abstract away the implementation and control of the + * desired action. The class being called in this case {@link PrinterController} is not responsible + * for the actual desired action, but is actually delegated to a helper class either {@link + * CanonPrinter}, {@link EpsonPrinter} or {@link HpPrinter}. The consumer does not have or require + * knowledge of the actual class carrying out the action, only the container on which they are + * calling. * - * In this example the delegates are {@link EpsonPrinter}, {@link HpPrinter} and {@link CanonPrinter} they all implement - * {@link Printer}. The {@link PrinterController} class also implements {@link Printer}. However neither provide the - * functionality of {@link Printer} by printing to the screen, they actually call upon the instance of {@link Printer} - * that they were instantiated with. Therefore delegating the behaviour to another class. + *

    In this example the delegates are {@link EpsonPrinter}, {@link HpPrinter} and {@link + * CanonPrinter} they all implement {@link Printer}. The {@link PrinterController} class also + * implements {@link Printer}. However, neither provide the functionality of {@link Printer} by + * printing to the screen, they actually call upon the instance of {@link Printer} that they were + * instantiated with. Therefore, delegating the behaviour to another class. */ public class App { - public static final String MESSAGE_TO_PRINT = "hello world"; + private static final String MESSAGE_TO_PRINT = "hello world"; /** - * Program entry point + * Program entry point. * * @param args command line args */ public static void main(String[] args) { - PrinterController hpPrinterController = new PrinterController(new HpPrinter()); - PrinterController canonPrinterController = new PrinterController(new CanonPrinter()); - PrinterController epsonPrinterController = new PrinterController(new EpsonPrinter()); + var hpPrinterController = new PrinterController(new HpPrinter()); + var canonPrinterController = new PrinterController(new CanonPrinter()); + var epsonPrinterController = new PrinterController(new EpsonPrinter()); hpPrinterController.print(MESSAGE_TO_PRINT); canonPrinterController.print(MESSAGE_TO_PRINT); epsonPrinterController.print(MESSAGE_TO_PRINT); } - } diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java b/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java index ee4d54938a86..2b92d9dbd807 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -37,7 +39,8 @@ public interface Printer { /** * Method that takes a String to print to the screen. This will be implemented on both the - * controller and the delegate allowing the controller to call the same method on the delegate class. + * controller and the delegate allowing the controller to call the same method on the delegate + * class. * * @param message to be printed to the screen */ diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java b/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java index c54f611ee213..28488d4855db 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,10 +25,10 @@ package com.iluwatar.delegation.simple; /** - * Delegator Class to delegate the implementation of the Printer. - * This ensures two things: - * - when the actual implementation of the Printer class changes the delegation will still be operational - * - the actual benefit is observed when there are more than one implementors and they share a delegation control + * Delegator Class to delegate the implementation of the Printer. This ensures two things: - when + * the actual implementation of the Printer class changes the delegation will still be operational - + * the actual benefit is observed when there are more than one implementor, and they share a + * delegation control */ public class PrinterController implements Printer { @@ -37,10 +39,10 @@ public PrinterController(Printer printer) { } /** - * This method is implemented from {@link Printer} however instead on providing an - * implementation, it instead calls upon the class passed through the constructor. This is the delegate, - * hence the pattern. Therefore meaning that the caller does not care of the implementing class only the owning - * controller. + * This method is implemented from {@link Printer} however instead on providing an implementation, + * it instead calls upon the class passed through the constructor. This is the delegate, hence the + * pattern. Therefore, meaning that the caller does not care of the implementing class only the + * owning controller. * * @param message to be printed to the screen */ diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java index 8f024122f15f..7447522569f3 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,25 +25,20 @@ package com.iluwatar.delegation.simple.printers; import com.iluwatar.delegation.simple.Printer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * Specialised Implementation of {@link Printer} for a Canon Printer, in - * this case the message to be printed is appended to "Canon Printer : " + * Specialised Implementation of {@link Printer} for a Canon Printer, in this case the message to be + * printed is appended to "Canon Printer : ". * * @see Printer */ +@Slf4j public class CanonPrinter implements Printer { - private static final Logger LOGGER = LoggerFactory.getLogger(CanonPrinter.class); - - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void print(String message) { LOGGER.info("Canon Printer : {}", message); } - } diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java index fb763d21a862..9ede17dedf15 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,25 +25,20 @@ package com.iluwatar.delegation.simple.printers; import com.iluwatar.delegation.simple.Printer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * Specialised Implementation of {@link Printer} for a Epson Printer, in - * this case the message to be printed is appended to "Epson Printer : " + * Specialised Implementation of {@link Printer} for an Epson Printer, in this case the message to + * be printed is appended to "Epson Printer : ". * * @see Printer */ +@Slf4j public class EpsonPrinter implements Printer { - private static final Logger LOGGER = LoggerFactory.getLogger(EpsonPrinter.class); - - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void print(String message) { LOGGER.info("Epson Printer : {}", message); } - } diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java index d80bb7aa7c9f..a7f210bcab44 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,25 +25,20 @@ package com.iluwatar.delegation.simple.printers; import com.iluwatar.delegation.simple.Printer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * Specialised Implementation of {@link Printer} for a HP Printer, in - * this case the message to be printed is appended to "HP Printer : " + * Specialised Implementation of {@link Printer} for an HP Printer, in this case the message to be + * printed is appended to "HP Printer : ". * * @see Printer */ +@Slf4j public class HpPrinter implements Printer { - private static final Logger LOGGER = LoggerFactory.getLogger(HpPrinter.class); - - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void print(String message) { LOGGER.info("HP Printer : {}", message); } - } diff --git a/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java b/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java index ffdc96b807bd..8ad967c9d63f 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,19 @@ */ package com.iluwatar.delegation.simple; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * Application Test Entry - */ -public class AppTest { +/** Application Test Entry */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java index 422da5685ffc..7160eb56a273 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,71 +24,66 @@ */ package com.iluwatar.delegation.simple; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import com.iluwatar.delegation.simple.printers.CanonPrinter; import com.iluwatar.delegation.simple.printers.EpsonPrinter; import com.iluwatar.delegation.simple.printers.HpPrinter; +import java.util.LinkedList; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Test for Delegation Pattern - */ -public class DelegateTest { +/** Test for Delegation Pattern */ +class DelegateTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } private static final String MESSAGE = "Test Message Printed"; @Test - public void testCanonPrinter() throws Exception { - PrinterController printerController = new PrinterController(new CanonPrinter()); + void testCanonPrinter() { + var printerController = new PrinterController(new CanonPrinter()); printerController.print(MESSAGE); assertEquals("Canon Printer : Test Message Printed", appender.getLastMessage()); } @Test - public void testHpPrinter() throws Exception { - PrinterController printerController = new PrinterController(new HpPrinter()); + void testHpPrinter() { + var printerController = new PrinterController(new HpPrinter()); printerController.print(MESSAGE); assertEquals("HP Printer : Test Message Printed", appender.getLastMessage()); } @Test - public void testEpsonPrinter() throws Exception { - PrinterController printerController = new PrinterController(new EpsonPrinter()); + void testEpsonPrinter() { + var printerController = new PrinterController(new EpsonPrinter()); printerController.print(MESSAGE); assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage()); } - /** - * Logging Appender - */ - private class InMemoryAppender extends AppenderBase { + /** Logging Appender */ + private static class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); + private final List log = new LinkedList<>(); public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); @@ -106,5 +103,4 @@ public int getLogSize() { return log.size(); } } - } diff --git a/dependency-injection/README.md b/dependency-injection/README.md index 735f589b1555..c9a2848bdfde 100644 --- a/dependency-injection/README.md +++ b/dependency-injection/README.md @@ -1,26 +1,162 @@ --- -layout: pattern -title: Dependency Injection -folder: dependency-injection -permalink: /patterns/dependency-injection/ -categories: Behavioral -tags: - - Java - - Difficulty-Beginner +title: "Dependency Injection Pattern in Java: Boosting Maintainability with Loose Coupling" +shortTitle: Dependency Injection +description: "Learn about the Dependency Injection design pattern. Explore its benefits, real-world examples, class diagrams, and best practices for implementation in Java." +category: Creational +language: en +tag: + - Decoupling + - Dependency management + - Inversion of control --- -## Intent -Dependency Injection is a software design pattern in which one or -more dependencies (or services) are injected, or passed by reference, into a -dependent object (or client) and are made part of the client's state. The -pattern separates the creation of a client's dependencies from its own -behavior, which allows program designs to be loosely coupled and to follow the -inversion of control and single responsibility principles. +## Also known as -![alt text](./etc/dependency-injection.png "Dependency Injection") +* Inversion of Control (IoC) +* Dependency Inversion -## Applicability -Use the Dependency Injection pattern when +## Intent of Dependency Injection Design Pattern -* when you need to remove knowledge of concrete implementation from object -* to enable unit testing of classes in isolation using mock objects or stubs +To decouple the creation of object dependencies from their usage, allowing for more flexible and testable code. + +## Detailed Explanation of Dependency Injection Pattern with Real-World Examples + +Real-world example + +> Imagine a high-end restaurant where the chef needs various ingredients to prepare dishes. Instead of the chef personally going to different suppliers for each ingredient, a trusted supplier delivers all the required fresh ingredients daily. This allows the chef to focus on cooking without worrying about sourcing the ingredients. +> +> In the Dependency Injection design pattern, the trusted supplier acts as the "injector," providing the necessary dependencies (ingredients) to the chef (object). The chef can then use these dependencies without knowing where they came from, ensuring a clean separation between the creation and use of dependencies. This setup enhances efficiency, flexibility, and maintainability in the kitchen, much like in a software system. + +In plain words + +> Dependency Injection separates the creation of the client's dependencies from its own behavior. + +Wikipedia says + +> In software engineering, dependency injection is a technique in which an object receives other objects that it depends on. These other objects are called dependencies. + +Sequence diagram + +![Dependency Injection sequence diagram](./etc/dependency-injection-sequence-diagram.png) + +## Programmatic Example of Dependency Injection Pattern in Java + +The old wizard likes to fill his pipe and smoke tobacco once in a while. However, he doesn't want to depend on a single tobacco brand only but likes to be able to enjoy them all interchangeably. + +Let's first introduce the `Tobacco` interface and the concrete brands. + +```java + +@Slf4j +public abstract class Tobacco { + + public void smoke(Wizard wizard) { + LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(), + this.getClass().getSimpleName()); + } +} + +public class SecondBreakfastTobacco extends Tobacco { +} + +public class RivendellTobacco extends Tobacco { +} + +public class OldTobyTobacco extends Tobacco { +} +``` + +Next here's the `Wizard` class hierarchy. + +```java +public interface Wizard { + + void smoke(); +} + +public class AdvancedWizard implements Wizard { + + private final Tobacco tobacco; + + public AdvancedWizard(Tobacco tobacco) { + this.tobacco = tobacco; + } + + @Override + public void smoke() { + tobacco.smoke(this); + } +} +``` + +Finally, we can show how easy it is to give the old wizard any brand of tobacco. + +```java +public static void main(String[] args) { + var simpleWizard = new SimpleWizard(); + simpleWizard.smoke(); + + var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco()); + advancedWizard.smoke(); + + var advancedSorceress = new AdvancedSorceress(); + advancedSorceress.setTobacco(new SecondBreakfastTobacco()); + advancedSorceress.smoke(); + + var injector = Guice.createInjector(new TobaccoModule()); + var guiceWizard = injector.getInstance(GuiceWizard.class); + guiceWizard.smoke(); +} +``` + +The program output: + +``` +11:54:05.205 [main] INFO com.iluwatar.dependency.injection.Tobacco -- SimpleWizard smoking OldTobyTobacco +11:54:05.207 [main] INFO com.iluwatar.dependency.injection.Tobacco -- AdvancedWizard smoking SecondBreakfastTobacco +11:54:05.207 [main] INFO com.iluwatar.dependency.injection.Tobacco -- AdvancedSorceress smoking SecondBreakfastTobacco +11:54:05.308 [main] INFO com.iluwatar.dependency.injection.Tobacco -- GuiceWizard smoking RivendellTobacco +``` + +## When to Use the Dependency Injection Pattern in Java + +* When aiming to reduce the coupling between classes and increase the modularity of the application. +* In scenarios where the object creation process is complex or should be separated from the class usage. +* In applications requiring easier unit testing by allowing dependencies to be mocked or stubbed. +* Within frameworks or libraries that manage object lifecycles and dependencies, such as Spring or Jakarta EE (formerly Java EE). + +## Real-World Applications of Dependency Injection Pattern in Java + +* Frameworks like Spring, Jakarta EE, and Google Guice use Dependency Injection (DI) extensively to manage component lifecycles and dependencies. +* Desktop and web applications that require flexible architecture with easily interchangeable components. + +## Benefits and Trade-offs of Dependency Injection Pattern + +Benefits: + +* Enhances modularity and separation of concerns. +* Simplifies unit testing by allowing for easy mocking of dependencies. +* Increases flexibility and maintainability by promoting loose coupling. + +Trade-offs: + +* Can introduce complexity in the configuration, especially in large projects. +* Might increase the learning curve for developers unfamiliar with Dependency Injection patterns or frameworks. +* Requires careful management of object lifecycles and scopes. + +## Related Java Design Patterns + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) and [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Used to create instances that the DI mechanism will inject. +* [Service Locator](https://java-design-patterns.com/patterns/service-locator/): An alternative to DI for locating services or components, though it does not decouple the lookup process as effectively as DI. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used in conjunction with DI to provide a single instance of a service across the application. + +## References and Credits + +* [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3wRnjp5) +* [Dependency Injection: Design patterns using Spring and Guice](https://amzn.to/4aMyHkI) +* [Dependency Injection Principles, Practices, and Patterns](https://amzn.to/4aupmxe) +* [Google Guice: Agile Lightweight Dependency Injection Framework](https://amzn.to/4bTDbX0) +* [Java 9 Dependency Injection: Write loosely coupled code with Spring 5 and Guice](https://amzn.to/4ayCtxp) +* [Java Design Pattern Essentials](https://amzn.to/3xtPPxa) +* [Pro Java EE Spring Patterns: Best Practices and Design Strategies Implementing Java EE Patterns with the Spring Framework](https://amzn.to/3J6Teoh) +* [Spring in Action](https://amzn.to/4asnpSG) diff --git a/dependency-injection/etc/dependency-injection-sequence-diagram.png b/dependency-injection/etc/dependency-injection-sequence-diagram.png new file mode 100644 index 000000000000..dbd4d817f7a0 Binary files /dev/null and b/dependency-injection/etc/dependency-injection-sequence-diagram.png differ diff --git a/dependency-injection/etc/dependency-injection.urm.puml b/dependency-injection/etc/dependency-injection.urm.puml new file mode 100644 index 000000000000..84ed3c6dd321 --- /dev/null +++ b/dependency-injection/etc/dependency-injection.urm.puml @@ -0,0 +1,57 @@ +@startuml +package com.iluwatar.dependency.injection { + class AdvancedSorceress { + - tobacco : Tobacco + + AdvancedSorceress() + + setTobacco(tobacco : Tobacco) + + smoke() + } + class AdvancedWizard { + - tobacco : Tobacco + + AdvancedWizard(tobacco : Tobacco) + + smoke() + } + class App { + + App() + + main(args : String[]) {static} + } + class GuiceWizard { + - tobacco : Tobacco + + GuiceWizard(tobacco : Tobacco) + + smoke() + } + class OldTobyTobacco { + + OldTobyTobacco() + } + class RivendellTobacco { + + RivendellTobacco() + } + class SecondBreakfastTobacco { + + SecondBreakfastTobacco() + } + class SimpleWizard { + - tobacco : OldTobyTobacco + + SimpleWizard() + + smoke() + } + abstract class Tobacco { + - LOGGER : Logger {static} + + Tobacco() + + smoke(wizard : Wizard) + } + interface Wizard { + + smoke() {abstract} + } +} +AdvancedSorceress --> "-tobacco" Tobacco +SimpleWizard --> "-tobacco" OldTobyTobacco +AdvancedWizard --> "-tobacco" Tobacco +GuiceWizard --> "-tobacco" Tobacco +AdvancedSorceress ..|> Wizard +AdvancedWizard ..|> Wizard +GuiceWizard ..|> Wizard +OldTobyTobacco --|> Tobacco +RivendellTobacco --|> Tobacco +SecondBreakfastTobacco --|> Tobacco +SimpleWizard ..|> Wizard +@enduml \ No newline at end of file diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml index e8a499918def..f0626f2cd3a6 100644 --- a/dependency-injection/pom.xml +++ b/dependency-injection/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT dependency-injection - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -48,4 +52,23 @@ guice + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.dependency.injection.App + + + + + + + + diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java index 52256fd81264..0ebf875c2120 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java @@ -1,65 +1,42 @@ -/** - * 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.dependency.injection; - -/** - * The MIT License - * Copyright (c) 2014-2017 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. - */ - - -/** - * AdvancedSorceress implements inversion of control. It depends on abstraction that can be injected - * through its setter. - */ -public class AdvancedSorceress implements Wizard { - - private Tobacco tobacco; - - public void setTobacco(Tobacco tobacco) { - this.tobacco = tobacco; - } - - @Override - public void smoke() { - tobacco.smoke(this); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dependency.injection; + +import lombok.Setter; + +/** + * AdvancedSorceress implements inversion of control. It depends on abstraction that can be injected + * through its setter. + */ +@Setter +public class AdvancedSorceress implements Wizard { + + private Tobacco tobacco; + + @Override + public void smoke() { + tobacco.smoke(this); + } +} diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java index 913a8bd6e05a..4ef3835f2bf4 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,19 +24,16 @@ */ package com.iluwatar.dependency.injection; +import lombok.RequiredArgsConstructor; + /** - * * AdvancedWizard implements inversion of control. It depends on abstraction that can be injected * through its constructor. - * */ +@RequiredArgsConstructor public class AdvancedWizard implements Wizard { - private Tobacco tobacco; - - public AdvancedWizard(Tobacco tobacco) { - this.tobacco = tobacco; - } + private final Tobacco tobacco; @Override public void smoke() { diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java index a27160bf19e7..2f8ecf07fcfa 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -23,48 +25,47 @@ package com.iluwatar.dependency.injection; import com.google.inject.Guice; -import com.google.inject.Injector; /** * Dependency Injection pattern deals with how objects handle their dependencies. The pattern - * implements so called inversion of control principle. Inversion of control has two specific rules: + * implements so-called inversion of control principle. Inversion of control has two specific rules: * - High-level modules should not depend on low-level modules. Both should depend on abstractions. * - Abstractions should not depend on details. Details should depend on abstractions. - *

    - * In this example we show you three different wizards. The first one ({@link SimpleWizard}) is a + * + *

    In this example we show you three different wizards. The first one ({@link SimpleWizard}) is a * naive implementation violating the inversion of control principle. It depends directly on a * concrete implementation which cannot be changed. - *

    - * The second and third wizards({@link AdvancedWizard} and {@link AdvancedSorceress}) are more flexible. - * They do not depend on any concrete implementation but abstraction. They utilizes Dependency Injection - * pattern allowing their {@link Tobacco} dependency to be injected through constructor ({@link AdvancedWizard}) - * or setter ({@link AdvancedSorceress}). This way, handling the dependency is no longer the wizard's - * responsibility. It is resolved outside the wizard class. - *

    - * The fourth example takes the pattern a step further. It uses Guice framework for Dependency + * + *

    The second and third wizards({@link AdvancedWizard} and {@link AdvancedSorceress}) are more + * flexible. They do not depend on any concrete implementation but abstraction. They utilize + * Dependency Injection pattern allowing their {@link Tobacco} dependency to be injected through + * constructor ({@link AdvancedWizard}) or setter ({@link AdvancedSorceress}). This way, handling + * the dependency is no longer the wizard's responsibility. It is resolved outside the wizard class. + * + *

    The fourth example takes the pattern a step further. It uses Guice framework for Dependency * Injection. {@link TobaccoModule} binds a concrete implementation to abstraction. Injector is then * used to create {@link GuiceWizard} object with correct dependencies. */ public class App { /** - * Program entry point + * Program entry point. * * @param args command line args */ public static void main(String[] args) { - SimpleWizard simpleWizard = new SimpleWizard(); + var simpleWizard = new SimpleWizard(); simpleWizard.smoke(); - AdvancedWizard advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco()); + var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco()); advancedWizard.smoke(); - AdvancedSorceress advancedSorceress = new AdvancedSorceress(); + var advancedSorceress = new AdvancedSorceress(); advancedSorceress.setTobacco(new SecondBreakfastTobacco()); advancedSorceress.smoke(); - Injector injector = Guice.createInjector(new TobaccoModule()); - GuiceWizard guiceWizard = injector.getInstance(GuiceWizard.class); + var injector = Guice.createInjector(new TobaccoModule()); + var guiceWizard = injector.getInstance(GuiceWizard.class); guiceWizard.smoke(); } } diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java index 89db63f189bb..8230f975cb78 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,14 +27,12 @@ import javax.inject.Inject; /** - * * GuiceWizard implements inversion of control. Its dependencies are injected through its * constructor by Guice framework. - * */ public class GuiceWizard implements Wizard { - private Tobacco tobacco; + private final Tobacco tobacco; @Inject public GuiceWizard(Tobacco tobacco) { diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java index 68f45640526e..0bdd5479cdee 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,10 +24,5 @@ */ package com.iluwatar.dependency.injection; -/** - * - * OldTobyTobacco concrete {@link Tobacco} implementation - * - */ -public class OldTobyTobacco extends Tobacco { -} +/** OldTobyTobacco concrete {@link Tobacco} implementation. */ +public class OldTobyTobacco extends Tobacco {} diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java index 29a9c9c21e12..1238a759427e 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,10 +24,5 @@ */ package com.iluwatar.dependency.injection; -/** - * - * RivendellTobacco concrete {@link Tobacco} implementation - * - */ -public class RivendellTobacco extends Tobacco { -} +/** RivendellTobacco concrete {@link Tobacco} implementation. */ +public class RivendellTobacco extends Tobacco {} diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java index 4bc373dbaf48..34cf201f4862 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,10 +24,5 @@ */ package com.iluwatar.dependency.injection; -/** - * - * SecondBreakfastTobacco concrete {@link Tobacco} implementation - * - */ -public class SecondBreakfastTobacco extends Tobacco { -} +/** SecondBreakfastTobacco concrete {@link Tobacco} implementation. */ +public class SecondBreakfastTobacco extends Tobacco {} diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java index c800d70a076d..78459c687174 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,14 +25,12 @@ package com.iluwatar.dependency.injection; /** - * * Naive Wizard implementation violating the inversion of control principle. It should depend on * abstraction instead. - * */ public class SimpleWizard implements Wizard { - private OldTobyTobacco tobacco = new OldTobyTobacco(); + private final OldTobyTobacco tobacco = new OldTobyTobacco(); public void smoke() { tobacco.smoke(this); diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java index 9676e49e81e0..b1aa7e87cebe 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,14 @@ */ package com.iluwatar.dependency.injection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * Tobacco abstraction - * - */ +/** Tobacco abstraction. */ +@Slf4j public abstract class Tobacco { - private static final Logger LOGGER = LoggerFactory.getLogger(Tobacco.class); - public void smoke(Wizard wizard) { - LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(), - this.getClass().getSimpleName()); + LOGGER.info( + "{} smoking {}", wizard.getClass().getSimpleName(), this.getClass().getSimpleName()); } } diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java index 4f26b78a54cc..0dc6a6d3bb1f 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,11 +26,7 @@ import com.google.inject.AbstractModule; -/** - * - * Guice module for binding certain concrete {@link Tobacco} implementation. - * - */ +/** Guice module for binding certain concrete {@link Tobacco} implementation. */ public class TobaccoModule extends AbstractModule { @Override diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java index d4c4cbbb4842..4ba6417275a9 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,13 +24,8 @@ */ package com.iluwatar.dependency.injection; -/** - * - * Wizard interface - * - */ +/** Wizard interface. */ public interface Wizard { void smoke(); - } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java index da15b7c52c47..f2cf32db0038 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java @@ -1,77 +1,74 @@ -/** - * 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.dependency.injection; - -import com.iluwatar.dependency.injection.utils.InMemoryAppender; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - - -/** - * Date: 28/04/17 - 7:40 AM - * - * @author Stanislav Kapinus - */ - -public class AdvancedSorceressTest { - - private InMemoryAppender appender; - - @BeforeEach - public void setUp() { - appender = new InMemoryAppender(Tobacco.class); - } - - @AfterEach - public void tearDown() { - appender.stop(); - } - - /** - * Test if the {@link AdvancedSorceress} smokes whatever instance of {@link Tobacco} is passed to her - * through the setter's parameter - */ - @Test - public void testSmokeEveryThing() throws Exception { - - final Tobacco[] tobaccos = { - new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() - }; - - for (final Tobacco tobacco : tobaccos) { - final AdvancedSorceress advancedSorceress = new AdvancedSorceress(); - advancedSorceress.setTobacco(tobacco); - advancedSorceress.smoke(); - // Verify if the sorceress is smoking the correct tobacco ... - assertEquals("AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); - - } - - // ... and nothing else is happening. - assertEquals(tobaccos.length, appender.getLogSize()); - - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dependency.injection; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** AdvancedSorceressTest */ +class AdvancedSorceressTest { + + private InMemoryAppender appender; + + @BeforeEach + void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @AfterEach + void tearDown() { + appender.stop(); + } + + /** + * Test if the {@link AdvancedSorceress} smokes whatever instance of {@link Tobacco} is passed to + * her through the setter's parameter + */ + @Test + void testSmokeEveryThing() { + + List tobaccos = + List.of(new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco()); + + // Verify if the sorceress is smoking the correct tobacco ... + tobaccos.forEach( + tobacco -> { + final var advancedSorceress = new AdvancedSorceress(); + advancedSorceress.setTobacco(tobacco); + advancedSorceress.smoke(); + String lastMessage = appender.getLastMessage(); + assertEquals( + "AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), lastMessage); + }); + + // ... and nothing else is happening. + assertEquals(tobaccos.size(), appender.getLogSize()); + } +} diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java index 46e38cc3351a..7a1692db6784 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,30 +24,26 @@ */ package com.iluwatar.dependency.injection; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - - -/** - * Date: 12/10/15 - 8:40 PM - * - * @author Jeroen Meulemeester - */ -public class AdvancedWizardTest { +/** AdvancedWizardTest */ +class AdvancedWizardTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(Tobacco.class); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } @@ -54,24 +52,21 @@ public void tearDown() { * through the constructor parameter */ @Test - public void testSmokeEveryThing() throws Exception { - - final Tobacco[] tobaccos = { - new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() - }; + void testSmokeEveryThing() { - for (final Tobacco tobacco : tobaccos) { - final AdvancedWizard advancedWizard = new AdvancedWizard(tobacco); - advancedWizard.smoke(); + List tobaccos = + List.of(new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco()); - // Verify if the wizard is smoking the correct tobacco ... - assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); - - } + // Verify if the wizard is smoking the correct tobacco ... + tobaccos.forEach( + tobacco -> { + final AdvancedWizard advancedWizard = new AdvancedWizard(tobacco); + advancedWizard.smoke(); + String lastMessage = appender.getLastMessage(); + assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage); + }); // ... and nothing else is happening. - assertEquals(tobaccos.length, appender.getLogSize()); - + assertEquals(tobaccos.size(), appender.getLogSize()); } - } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java index fc8775942512..1894227ec1d0 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,19 @@ */ package com.iluwatar.dependency.injection; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java index 042a418556b4..400a079d9845 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,32 +24,28 @@ */ package com.iluwatar.dependency.injection; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.google.inject.AbstractModule; import com.google.inject.Guice; -import com.google.inject.Injector; import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Date: 12/10/15 - 8:57 PM - * - * @author Jeroen Meulemeester - */ -public class GuiceWizardTest { +/** GuiceWizardTest */ +class GuiceWizardTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(Tobacco.class); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } @@ -56,22 +54,22 @@ public void tearDown() { * through the constructor parameter */ @Test - public void testSmokeEveryThingThroughConstructor() throws Exception { + void testSmokeEveryThingThroughConstructor() { - final Tobacco[] tobaccos = { - new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() - }; + List tobaccos = + List.of(new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco()); - for (final Tobacco tobacco : tobaccos) { - final GuiceWizard guiceWizard = new GuiceWizard(tobacco); - guiceWizard.smoke(); - - // Verify if the wizard is smoking the correct tobacco ... - assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); - } + // Verify if the wizard is smoking the correct tobacco ... + tobaccos.forEach( + tobacco -> { + final GuiceWizard guiceWizard = new GuiceWizard(tobacco); + guiceWizard.smoke(); + String lastMessage = appender.getLastMessage(); + assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage); + }); // ... and nothing else is happening. - assertEquals(tobaccos.length, appender.getLogSize()); + assertEquals(tobaccos.size(), appender.getLogSize()); } /** @@ -79,32 +77,31 @@ public void testSmokeEveryThingThroughConstructor() throws Exception { * through the Guice google inject framework */ @Test - public void testSmokeEveryThingThroughInjectionFramework() throws Exception { - - @SuppressWarnings("unchecked") - final Class[] tobaccos = new Class[]{ - OldTobyTobacco.class, RivendellTobacco.class, SecondBreakfastTobacco.class - }; - - for (final Class tobaccoClass : tobaccos) { - // Configure the tobacco in the injection framework ... - final Injector injector = Guice.createInjector(new AbstractModule() { - @Override - protected void configure() { - bind(Tobacco.class).to(tobaccoClass); - } - }); - - // ... and create a new wizard with it - final GuiceWizard guiceWizard = injector.getInstance(GuiceWizard.class); - guiceWizard.smoke(); - - // Verify if the wizard is smoking the correct tobacco ... - assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), appender.getLastMessage()); - } + void testSmokeEveryThingThroughInjectionFramework() { + + List> tobaccos = + List.of(OldTobyTobacco.class, RivendellTobacco.class, SecondBreakfastTobacco.class); + + // Configure the tobacco in the injection framework ... + // ... and create a new wizard with it + // Verify if the wizard is smoking the correct tobacco ... + tobaccos.forEach( + tobaccoClass -> { + final var injector = + Guice.createInjector( + new AbstractModule() { + @Override + protected void configure() { + bind(Tobacco.class).to(tobaccoClass); + } + }); + final var guiceWizard = injector.getInstance(GuiceWizard.class); + guiceWizard.smoke(); + String lastMessage = appender.getLastMessage(); + assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), lastMessage); + }); // ... and nothing else is happening. - assertEquals(tobaccos.length, appender.getLogSize()); + assertEquals(tobaccos.size(), appender.getLogSize()); } - } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java index 4600a2598ef0..f9354b49b9d7 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,29 +24,25 @@ */ package com.iluwatar.dependency.injection; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.dependency.injection.utils.InMemoryAppender; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Date: 12/10/15 - 8:26 PM - * - * @author Jeroen Meulemeester - */ -public class SimpleWizardTest { +/** SimpleWizardTest */ +class SimpleWizardTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(Tobacco.class); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } @@ -53,11 +51,10 @@ public void tearDown() { * OldTobyTobacco} */ @Test - public void testSmoke() { - final SimpleWizard simpleWizard = new SimpleWizard(); + void testSmoke() { + final var simpleWizard = new SimpleWizard(); simpleWizard.smoke(); assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java index b79bf3d40b32..319216e187c4 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,18 +27,14 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.slf4j.LoggerFactory; - import java.util.LinkedList; import java.util.List; +import org.slf4j.LoggerFactory; - -/** - * InMemory Log Appender Util. - */ +/** InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); + private final List log = new LinkedList<>(); public InMemoryAppender(Class clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); diff --git a/dirty-flag/README.md b/dirty-flag/README.md index bea4d324bb69..bb46e315b3c5 100644 --- a/dirty-flag/README.md +++ b/dirty-flag/README.md @@ -1,26 +1,154 @@ --- -layout: pattern -title: Dirty Flag -folder: dirty-flag -permalink: /patterns/dirty-flag/ -categories: Other -tags: - - Java - - Difficulty-Beginner - - Performance +title: "Dirty Flag Pattern in Java: Optimizing Performance with Change Tracking" +shortTitle: Dirty Flag +description: "Learn about the Dirty Flag design pattern in Java for efficient state tracking and resource management. Avoid unnecessary computations with practical examples and use cases." +category: Behavioral +language: en +tag: + - Game programming + - Performance + - Resource management + - State tracking --- -## Intent -To avoid expensive re-acquisition of resources. The resources retain their identity, are kept in some -fast-access storage, and are re-used to avoid having to acquire them again. +## Also known as -![alt text](./etc/dirty-flag.png "Dirty Flag") +* Change Tracking +* Is-Modified Flag -## Applicability -Use the Dirty Flag pattern when +## Intent of Dirty Flag Design Pattern -* Repetitious acquisition, initialization, and release of the same resource causes unnecessary performance overhead. +The Dirty Flag design pattern is employed to avoid unnecessary computations or resource-heavy operations by maintaining a boolean flag that tracks whether the state of an object has changed ('dirty') or remains unchanged ('clean'). This flag, when set, indicates that a particular operation, such as recalculating or refreshing data, needs to be performed again to reflect the updated state. -## Credits +## Detailed Explanation of Dirty Flag Pattern with Real-World Examples -* [Design Patterns: Dirty Flag](https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/) +Real-world example + +> Imagine a library with an electronic catalog system that tracks which books are checked out and returned. Each book record has a "dirty flag" that gets marked whenever a book is checked out or returned. At the end of each day, the library staff reviews only those records marked as "dirty" to update the physical inventory, instead of checking every single book in the library. This system significantly reduces the effort and time required for daily inventory checks by focusing only on the items that have changed status, analogous to how the Dirty Flag design pattern minimizes resource-intensive operations by performing them only when necessary. + +In plain words + +> The Dirty Flag design pattern minimizes unnecessary operations by using a flag to track when an object's state has changed and an update is needed. + +Wikipedia says + +> A dirty bit or modified bit is a bit that is associated with a block of computer memory and indicates whether the corresponding block of memory has been modified. The dirty bit is set when the processor writes to (modifies) this memory. The bit indicates that its associated block of memory has been modified and has not been saved to storage yet. When a block of memory is to be replaced, its corresponding dirty bit is checked to see if the block needs to be written back to secondary memory before being replaced or if it can simply be removed. Dirty bits are used by the CPU cache and in the page replacement algorithms of an operating system. + +Flowchart + +![Dirty Flag flowchart](./etc/dirty-flag-flowchart.png) + +## Programmatic Example of Dirty Flag Pattern in Java + +The `DataFetcher` class is responsible for fetching data from a file. It has a dirty flag that indicates whether the data in the file has changed since the last fetch. + +```java +public class DataFetcher { + private long lastFetched; + private boolean isDirty = true; + // Other properties and methods... +} +``` + +The `DataFetcher` class has a fetch method that checks the dirty flag before fetching data. If the flag is true, it fetches the data from the file and sets the flag to false. If the flag is false, it returns the previously fetched data. + +```java +public List fetch() { + if (!isDirty) { + return data; + } + data = fetchFromDatabase(); + isDirty = false; + return data; +} +``` + +The `World` class uses the `DataFetcher` to fetch data. It has a `fetch` method that calls the `fetch` method of the `DataFetcher`. + +```java +public class World { + private final DataFetcher fetcher = new DataFetcher(); + + public List fetch() { + return fetcher.fetch(); + } +} +``` + +The `App` class contains the `main` method that demonstrates the use of the Dirty Flag pattern. It creates a `World` object and fetches data from it in a loop. The `World` object uses the `DataFetcher` to fetch data, and the `DataFetcher` only fetches data from the file if the dirty flag is true. + +```java +@Slf4j +public class App { + + public void run() { + final var executorService = Executors.newSingleThreadScheduledExecutor(); + executorService.scheduleAtFixedRate(new Runnable() { + final World world = new World(); + + @Override + public void run() { + var countries = world.fetch(); + LOGGER.info("Our world currently has the following countries:-"); + countries.stream().map(country -> "\t" + country).forEach(LOGGER::info); + } + }, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds. + } + + public static void main(String[] args) { + var app = new App(); + app.run(); + } +} +``` + +The program output is as follows: + +``` +12:06:02.612 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.DataFetcher -- world.txt is dirty! Re-fetching file content... +12:06:02.615 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- Our world currently has the following countries:- +12:06:02.616 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- UNITED_KINGDOM +12:06:02.616 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- MALAYSIA +12:06:02.616 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- UNITED_STATES +``` + +## When to Use the Dirty Flag Pattern in Java + +* When an operation is resource-intensive and only necessary after certain changes have occurred. +* In scenarios where checking for changes is significantly cheaper than performing the operation itself, enhancing cost-effectiveness. +* Within systems where objects maintain state that is expensive to update and the updates are infrequent, promoting performance efficiency. + +## Dirty Flag Pattern Java Tutorials + +* [89: Design Patterns: Dirty Flag (TakeUpCode)](https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/) + +## Real-World Applications of Dirty Flag Pattern in Java + +* Graphic rendering engines to update only parts of the scene that have changed, utilizing the Dirty Flag pattern for efficient rendering. +* Web applications for partial page rendering or caching strategies. +* Database applications for tracking changes in datasets to minimize write operations, ensuring efficient database management. + +## Benefits and Trade-offs of Dirty Flag Pattern + +Benefits: + +* Reduces computational and resource overhead by avoiding unnecessary operations, leading to performance gains. +* Can significantly improve performance in systems where operations are costly and changes are infrequent, fostering system optimization. +* Simplifies the decision-making process about when to perform certain operations, aiding in effective resource allocation. + +Trade-offs: + +* Introduces complexity by adding state management responsibility to the system. +* Requires diligent management of the flag to ensure it accurately reflects the state changes, avoiding stale or incorrect data. +* Potentially increases the risk of bugs related to improper flag resetting, impacting system reliability. + +## Related Java Design Patterns + +* [Observer](https://java-design-patterns.com/patterns/observer/): Can be used in conjunction to notify interested parties when the dirty flag is set or cleared. +* [Memento](https://java-design-patterns.com/patterns/memento/): Useful for storing the previous state of an object, which can work hand in hand with dirty flag logic to revert to clean states. +* [Command](https://java-design-patterns.com/patterns/command/): Commands can set the dirty flag when executed, indicating a change in state that requires attention. + +## References and Credits + +* [Game Programming Patterns](https://amzn.to/3PUzbgu) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) diff --git a/dirty-flag/etc/dirty-flag-flowchart.png b/dirty-flag/etc/dirty-flag-flowchart.png new file mode 100644 index 000000000000..02db0357be1a Binary files /dev/null and b/dirty-flag/etc/dirty-flag-flowchart.png differ diff --git a/dirty-flag/etc/dirty-flag.urm.puml b/dirty-flag/etc/dirty-flag.urm.puml new file mode 100644 index 000000000000..9685d3fdfbe4 --- /dev/null +++ b/dirty-flag/etc/dirty-flag.urm.puml @@ -0,0 +1,25 @@ +@startuml +package com.iluwatar.dirtyflag { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + + run() + } + class DataFetcher { + - LOGGER : Logger {static} + - filename : String + - lastFetched : long + + DataFetcher() + + fetch() : List + - isDirty(fileLastModified : long) : boolean + } + class World { + - countries : List + - df : DataFetcher + + World() + + fetch() : List + } +} +World --> "-df" DataFetcher +@enduml \ No newline at end of file diff --git a/dirty-flag/pom.xml b/dirty-flag/pom.xml index 76628a6be020..d6032c589320 100644 --- a/dirty-flag/pom.xml +++ b/dirty-flag/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT - com.iluwatar dirty-flag - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT dirty-flag http://maven.apache.org UTF-8 - - org.junit.jupiter - junit-jupiter-api - test + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -51,4 +54,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.dirtyflag.App + + + + + + + + diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java index 4d72b34da249..ed1ff06bba95 100644 --- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java +++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,61 +24,72 @@ */ package com.iluwatar.dirtyflag; -import java.util.List; import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; /** + * This application demonstrates the Dirty Flag pattern. The dirty flag behavioral pattern + * allows you to avoid expensive operations that would just need to be done again anyway. This is a + * simple pattern that really just explains how to add a bool value to your class that you can set + * anytime a property changes. This will let your class know that any results it may have previously + * calculated will need to be calculated again when they’re requested. Once the results are + * re-calculated, then the bool value can be cleared. * - * This application demonstrates the Dirty Flag pattern. The dirty flag behavioral pattern allows you to avoid - * expensive operations that would just need to be done again anyway. This is a simple pattern that really just explains - * how to add a bool value to your class that you can set anytime a property changes. This will let your class know that - * any results it may have previously calculated will need to be calculated again when they’re requested. Once the - * results are re-calculated, then the bool value can be cleared. - * - * There are some points that need to be considered before diving into using this pattern:- there are some things you’ll - * need to consider:- (1) Do you need it? This design pattern works well when the results to be calculated are difficult - * or resource intensive to compute. You want to save them. You also don’t want to be calculating them several times in - * a row when only the last one counts. (2) When do you set the dirty flag? Make sure that you set the dirty flag within - * the class itself whenever an important property changes. This property should affect the result of the calculated - * result and by changing the property, that makes the last result invalid. (3) When do you clear the dirty flag? It - * might seem obvious that the dirty flag should be cleared whenever the result is calculated with up-to-date - * information but there are other times when you might want to clear the flag. + *

    There are some points that need to be considered before diving into using this pattern:- there + * are some things you’ll need to consider:- (1) Do you need it? This design pattern works well when + * the results to be calculated are difficult or resource intensive to compute. You want to save + * them. You also don’t want to be calculating them several times in a row when only the last one + * counts. (2) When do you set the dirty flag? Make sure that you set the dirty flag within the + * class itself whenever an important property changes. This property should affect the result of + * the calculated result and by changing the property, that makes the last result invalid. (3) When + * do you clear the dirty flag? It might seem obvious that the dirty flag should be cleared whenever + * the result is calculated with up-to-date information but there are other times when you might + * want to clear the flag. * - * In this example, the {@link DataFetcher} holds the dirty flag. It fetches and re-fetches from world.txt - * when needed. {@link World} mainly serves the data to the front-end. + *

    In this example, the {@link DataFetcher} holds the dirty flag. It fetches and + * re-fetches from world.txt when needed. {@link World} mainly serves the data to the + * front-end. */ +@Slf4j public class App { - /** - * Program execution point - */ + + /** Program execution point. */ public void run() { + final var executorService = Executors.newSingleThreadScheduledExecutor(); + try { + executorService.scheduleAtFixedRate( + new Runnable() { + final World world = new World(); + + @Override + public void run() { + var countries = world.fetch(); + LOGGER.info("Our world currently has the following countries:-"); + countries.stream().map(country -> "\t" + country).forEach(LOGGER::info); + } + }, + 0, + 15, + TimeUnit.SECONDS); - final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - World world = new World(); - List countries = world.fetch(); - System.out.println("Our world currently has the following countries:-"); - for (String country : countries) { - System.out.println("\t" + country); - } - } - }, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds. + // Keep running for 45 seconds before shutdown (for demo purpose) + TimeUnit.SECONDS.sleep(45); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Thread was interrupted", e); + } finally { + executorService.shutdown(); + } } /** - * Program entry point + * Program entry point. * - * @param args - * command line args + * @param args command line args */ public static void main(String[] args) { - App app = new App(); - + var app = new App(); app.run(); } - } diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java index f3ebbb8b09f4..0d902b3c058b 100644 --- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java +++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -26,18 +28,15 @@ import java.io.File; import java.io.FileReader; import java.io.IOException; -import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; -/** - * A mock database manager -- Fetches data from a raw file. - * - * @author swaisuan - * - */ +/** A mock database manager -- Fetches data from a raw file. */ +@Slf4j public class DataFetcher { - private final String filename = "world.txt"; + private static final String FILENAME = "world.txt"; private long lastFetched; public DataFetcher() { @@ -54,28 +53,22 @@ private boolean isDirty(long fileLastModified) { /** * Fetches data/content from raw file. - * + * * @return List of strings */ public List fetch() { - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource(filename).getFile()); + var classLoader = getClass().getClassLoader(); + var file = new File(classLoader.getResource(FILENAME).getFile()); if (isDirty(file.lastModified())) { - System.out.println(filename + " is dirty! Re-fetching file content..."); - - List data = new ArrayList(); - try (BufferedReader br = new BufferedReader(new FileReader(file))) { - String line; - while ((line = br.readLine()) != null) { - data.add(line); - } + LOGGER.info(FILENAME + " is dirty! Re-fetching file content..."); + try (var br = new BufferedReader(new FileReader(file))) { + return br.lines().collect(Collectors.collectingAndThen(Collectors.toList(), List::copyOf)); } catch (IOException e) { - e.printStackTrace(); + LOGGER.error("An error occurred: ", e); } - return data; } - return new ArrayList(); + return List.of(); } } diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java index 7ab9f1d35c1c..bc876814b4d6 100644 --- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java +++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,34 +27,25 @@ import java.util.ArrayList; import java.util.List; -/** - * - * A middle-layer app that calls/passes along data from the back-end. - * - * @author swaisuan - * - */ +/** A middle-layer app that calls/passes along data from the back-end. */ public class World { private List countries; - private DataFetcher df; + private final DataFetcher df; public World() { - this.countries = new ArrayList(); + this.countries = new ArrayList<>(); this.df = new DataFetcher(); } /** - * * Calls {@link DataFetcher} to fetch data from back-end. - * + * * @return List of strings */ public List fetch() { - List data = df.fetch(); - + var data = df.fetch(); countries = data.isEmpty() ? countries : data; - return countries; } } diff --git a/dirty-flag/src/main/resources/world.txt b/dirty-flag/src/main/resources/world.txt index 1d9d654bf6dc..280ea370239c 100644 --- a/dirty-flag/src/main/resources/world.txt +++ b/dirty-flag/src/main/resources/world.txt @@ -1,26 +1,3 @@ -==== - 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. -==== - UNITED_KINGDOM MALAYSIA UNITED_STATES \ No newline at end of file diff --git a/dirty-flag/src/test/java/org/dirty/flag/AppTest.java b/dirty-flag/src/test/java/org/dirty/flag/AppTest.java index 50f107cd58c0..8e09b01928c3 100644 --- a/dirty-flag/src/test/java/org/dirty/flag/AppTest.java +++ b/dirty-flag/src/test/java/org/dirty/flag/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,19 +24,20 @@ */ package org.dirty.flag; -import java.io.IOException; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import com.iluwatar.dirtyflag.App; import org.junit.jupiter.api.Test; -import com.iluwatar.dirtyflag.App; +/** Tests that Dirty-Flag example runs without errors. */ +class AppTest { -/** - * Tests that Dirty-Flag example runs without errors. - */ -public class AppTest { + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java b/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java index 8f651b2678bb..7d512deafe7b 100644 --- a/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java +++ b/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,33 +24,25 @@ */ package org.dirty.flag; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.List; - -import org.junit.jupiter.api.Test; - import com.iluwatar.dirtyflag.DataFetcher; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class DirtyFlagTest { +/** Application test */ +class DirtyFlagTest { @Test - public void testIsDirty() { - DataFetcher df = new DataFetcher(); - List countries = df.fetch(); - assertTrue(!countries.isEmpty()); + void testIsDirty() { + var df = new DataFetcher(); + var countries = df.fetch(); + Assertions.assertFalse(countries.isEmpty()); } @Test - public void testIsNotDirty() { - DataFetcher df = new DataFetcher(); + void testIsNotDirty() { + var df = new DataFetcher(); df.fetch(); - List countries = df.fetch(); - assertTrue(countries.isEmpty()); + var countries = df.fetch(); + Assertions.assertTrue(countries.isEmpty()); } } diff --git a/domain-model/README.md b/domain-model/README.md new file mode 100644 index 000000000000..c6e019e1bdef --- /dev/null +++ b/domain-model/README.md @@ -0,0 +1,276 @@ +--- +title: "Domain Model Pattern in Java: Building Robust Business Logic" +shortTitle: Domain Model +description: "Learn about the Domain Model pattern in Java design with detailed explanations, examples, and applications. Improve your software's modularity, maintainability, and scalability." +category: Structural +language: en +tag: + - Abstraction + - Business + - Data processing + - Domain + - Encapsulation + - Layered architecture + - Persistence + - Polymorphism +--- + +## Also known as + +* Conceptual Model +* Domain Object Model + +## Intent of Domain Model Design Pattern + +The Domain Model pattern aims to create a conceptual model in your software that matches the real-world system it's designed to represent. It involves using rich domain objects that encapsulate both data and behavior relevant to the application domain, ensuring business logic is centralized. + +## Detailed Explanation of Domain Model Pattern with Real-World Examples + +Real-world example + +> Consider an online bookstore system that uses the Domain Model design pattern. In this system, various domain objects such as `Book`, `Author`, `Customer`, and `Order` encapsulate the core business logic and rules. For instance, the `Book` object contains attributes like title, author, price, and stock quantity, along with methods to manage these attributes. The `Order` object manages order details, calculates the total price, and verifies stock availability. This approach ensures that the business logic is centralized within the domain objects, making the system more modular, easier to maintain, and scalable as new features are added. + +In plain words + +> The Domain Model is an object model of the domain that incorporates both behavior and data. + +Mind map + +![Domain Model mind map](./etc/domain-model-mind-map.png) + +## Programmatic Example of Domain Model Pattern in Java + +Let's assume that we need to build an e-commerce web application. While analyzing requirements you will notice that there are few nouns you talk about repeatedly. It’s your Customer, and a Product the customer looks for. These two are your domain-specific classes and each of that classes will include some business logic specific to its domain. + +In the example of the e-commerce app, we need to deal with the domain logic of customers who want to buy products and return them if they want. We can use the domain model pattern and create classes `Customer` and `Product` where every single instance of that class incorporates both behavior and data and represents only one record in the underlying table. + +```java +public class Customer { + // Customer properties and methods +} + +public class Product { + // Product properties and methods +} +``` + +Data Access Objects (DAOs): These objects provide an abstract interface to the database. They are used to retrieve domain entities and save changes back to the database. In the provided code, `CustomerDaoImpl` and `ProductDaoImpl` are the DAOs. + +```java +public class CustomerDaoImpl implements CustomerDao { + // Implementation of the methods defined in the CustomerDao interface +} + +public class ProductDaoImpl implements ProductDao { + // Implementation of the methods defined in the ProductDao interface +} +``` + +Domain Logic: This is encapsulated within the domain entities. For example, the `Customer` class has methods like `buyProduct` and `returnProduct` which represent the actions a customer can perform. + +```java +public class Customer { + + // Other properties and methods... + + public void buyProduct(Product product) { + // Implementation of buying a product + } + + public void returnProduct(Product product) { + // Implementation of returning a product + } +} +``` + +Application: The `App` class uses the domain entities and their methods to implement the business logic of the application. + +```java +public class App { + + public static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; + + public static final String CREATE_SCHEMA_SQL = + "CREATE TABLE CUSTOMERS (name varchar primary key, money decimal);" + + "CREATE TABLE PRODUCTS (name varchar primary key, price decimal, expiration_date date);" + + "CREATE TABLE PURCHASES (" + + "product_name varchar references PRODUCTS(name)," + + "customer_name varchar references CUSTOMERS(name));"; + + public static final String DELETE_SCHEMA_SQL = + "DROP TABLE PURCHASES IF EXISTS;" + + "DROP TABLE CUSTOMERS IF EXISTS;" + + "DROP TABLE PRODUCTS IF EXISTS;"; + + public static void main(String[] args) throws Exception { + + // Create data source and create the customers, products and purchases tables + final var dataSource = createDataSource(); + deleteSchema(dataSource); + createSchema(dataSource); + + // create customer + var customerDao = new CustomerDaoImpl(dataSource); + + var tom = + Customer.builder() + .name("Tom") + .money(Money.of(USD, 30)) + .customerDao(customerDao) + .build(); + + tom.save(); + + // create products + var productDao = new ProductDaoImpl(dataSource); + + var eggs = + Product.builder() + .name("Eggs") + .price(Money.of(USD, 10.0)) + .expirationDate(LocalDate.now().plusDays(7)) + .productDao(productDao) + .build(); + + var butter = + Product.builder() + .name("Butter") + .price(Money.of(USD, 20.00)) + .expirationDate(LocalDate.now().plusDays(9)) + .productDao(productDao) + .build(); + + var cheese = + Product.builder() + .name("Cheese") + .price(Money.of(USD, 25.0)) + .expirationDate(LocalDate.now().plusDays(2)) + .productDao(productDao) + .build(); + + eggs.save(); + butter.save(); + cheese.save(); + + // show money balance of customer after each purchase + tom.showBalance(); + tom.showPurchases(); + + // buy eggs + tom.buyProduct(eggs); + tom.showBalance(); + + // buy butter + tom.buyProduct(butter); + tom.showBalance(); + + // trying to buy cheese, but receive a refusal + // because he didn't have enough money + tom.buyProduct(cheese); + tom.showBalance(); + + // return butter and get money back + tom.returnProduct(butter); + tom.showBalance(); + + // Tom can buy cheese now because he has enough money + // and there is a discount on cheese because it expires in 2 days + tom.buyProduct(cheese); + + tom.save(); + + // show money balance and purchases after shopping + tom.showBalance(); + tom.showPurchases(); + } + + private static DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setUrl(H2_DB_URL); + return dataSource; + } + + private static void deleteSchema(DataSource dataSource) throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(DELETE_SCHEMA_SQL); + } + } + + private static void createSchema(DataSource dataSource) throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(CREATE_SCHEMA_SQL); + } + } +} +``` + +The program output: + +```java +12:17:23.834 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 30.00 +12:17:23.836 [main] INFO com.iluwatar.domainmodel.Customer -- Tom didn't bought anything +12:17:23.841 [main] INFO com.iluwatar.domainmodel.Customer -- Tom want to buy Eggs($10,00)... +12:17:23.842 [main] INFO com.iluwatar.domainmodel.Customer -- Tom bought Eggs! +12:17:23.842 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 20.00 +12:17:23.842 [main] INFO com.iluwatar.domainmodel.Customer -- Tom want to buy Butter($20,00)... +12:17:23.843 [main] INFO com.iluwatar.domainmodel.Customer -- Tom bought Butter! +12:17:23.843 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 0.00 +12:17:23.843 [main] INFO com.iluwatar.domainmodel.Customer -- Tom want to buy Cheese($20,00)... +12:17:23.843 [main] ERROR com.iluwatar.domainmodel.Customer -- Not enough money! +12:17:23.843 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 0.00 +12:17:23.843 [main] INFO com.iluwatar.domainmodel.Customer -- Tom want to return Butter($20,00)... +12:17:23.844 [main] INFO com.iluwatar.domainmodel.Customer -- Tom returned Butter! +12:17:23.844 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 20.00 +12:17:23.844 [main] INFO com.iluwatar.domainmodel.Customer -- Tom want to buy Cheese($20,00)... +12:17:23.844 [main] INFO com.iluwatar.domainmodel.Customer -- Tom bought Cheese! +12:17:23.846 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 0.00 +12:17:23.846 [main] INFO com.iluwatar.domainmodel.Customer -- Tom bought: Eggs - $10.00, Cheese - $20.00 +``` + +## When to Use the Domain Model Pattern in Java + +* Appropriate in complex applications with rich business logic. +* When the business logic or domain complexity is high and requires a model that closely represents real-world entities and their relationships. +* Suitable for applications where domain experts are involved in the development process to ensure the model accurately reflects domain concepts. + +## Domain Model Pattern Java Tutorials + +* [Architecture patterns: domain model and friends (Inviqa)](https://inviqa.com/blog/architecture-patterns-domain-model-and-friends) + +## Real-World Applications of Domain Model Pattern in Java + +* Enterprise applications (ERP, CRM systems) +* Financial systems (banking, trading platforms) +* Healthcare applications (patient records management) +* E-commerce platforms (product catalogs, shopping carts) + +## Benefits and Trade-offs of Domain Model Pattern + +Benefits: + +* Improved Communication: Provides a common language for developers and domain experts, enhancing understanding and collaboration. +* Flexibility: Encapsulates business logic within domain entities, making it easier to modify and extend without affecting other system parts. +* Maintainability: A well-structured domain model can simplify maintenance and evolution of the application over time. +* Reusability: Domain classes can often be reused across different projects within the same domain. + +Trade-offs: + +* Complexity: Can introduce complexity, especially in simple applications where a domain model might be overkill. +* Performance Concerns: Rich domain objects with complex behaviors might lead to performance bottlenecks, requiring careful optimization. +* Learning Curve: Requires a good understanding of the domain and may involve a steep learning curve for developers unfamiliar with the domain concepts. + +## Related Java Design Patterns + +* [Data Access Object (DAO)](https://java-design-patterns.com/patterns/dao/): For abstracting and encapsulating all access to the data source. +* [Repository](https://java-design-patterns.com/patterns/repository/): Mediates between the domain and data mapping layers, acting like an in-memory domain object collection. +* [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation. +* [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Maintains a list of objects affected by a business transaction and coordinates the writing out of changes. + +## References and Credits + +* [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3vMCjnP) +* [Implementing Domain-Driven Design](https://amzn.to/4cUX4OL) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) +* [Domain Model (Martin Fowler)](https://martinfowler.com/eaaCatalog/domainModel.html) diff --git a/domain-model/etc/domain-model-mind-map.png b/domain-model/etc/domain-model-mind-map.png new file mode 100644 index 000000000000..38dcdf26d4bc Binary files /dev/null and b/domain-model/etc/domain-model-mind-map.png differ diff --git a/domain-model/etc/domain-model.urm.png b/domain-model/etc/domain-model.urm.png new file mode 100644 index 000000000000..9ba7e0ca484a Binary files /dev/null and b/domain-model/etc/domain-model.urm.png differ diff --git a/domain-model/etc/domain-model.urm.puml b/domain-model/etc/domain-model.urm.puml new file mode 100644 index 000000000000..03a6a65dfea5 --- /dev/null +++ b/domain-model/etc/domain-model.urm.puml @@ -0,0 +1,87 @@ +@startuml +package com.iluwatar.domainmodel { + class App { + + CREATE_SCHEMA_SQL : String {static} + + DELETE_SCHEMA_SQL : String {static} + + H2_DB_URL : String {static} + + App() + - createDataSource() : DataSource {static} + - createSchema(dataSource : DataSource) {static} + - deleteSchema(dataSource : DataSource) {static} + + main(args : String[]) {static} + } + class Customer { + - customerDao : CustomerDao + - money : Money + - name : String + - purchases : List + ~ Customer(customerDao : CustomerDao, purchases : List, name : String, money : Money) + + builder() : CustomerBuilder {static} + + buyProduct(product : Product) + + getCustomerDao() : CustomerDao + + getMoney() : Money + + getName() : String + + getPurchases() : List + - receiveMoney(amount : Money) + + returnProduct(product : Product) + + save() + + setMoney(money : Money) + + setName(name : String) + + setPurchases(purchases : List) + + showBalance() + + showPurchases() + - withdraw(amount : Money) + } + interface CustomerDao { + + addProduct(Product, Customer) {abstract} + + deleteProduct(Product, Customer) {abstract} + + findByName(String) : Optional {abstract} + + save(Customer) {abstract} + + update(Customer) {abstract} + } + class CustomerDaoImpl { + - dataSource : DataSource + + CustomerDaoImpl(userDataSource : DataSource) + + addProduct(product : Product, customer : Customer) + + deleteProduct(product : Product, customer : Customer) + + findByName(name : String) : Optional + + save(customer : Customer) + + update(customer : Customer) + } + class Product { + - expirationDate : LocalDate + - name : String + - price : Money + - productDao : ProductDao + + Product(productDao : ProductDao, name : String, price : Money, expirationDate : LocalDate) + + builder() : ProductBuilder {static} + - calculateDiscount() : Money + + getExpirationDate() : LocalDate + + getName() : String + + getPrice() : Money + + getProductDao() : ProductDao + + getSalePrice() : Money + + save() + + setExpirationDate(expirationDate : LocalDate) + + setName(name : String) + + setPrice(price : Money) + } + interface ProductDao { + + findByName(String) : Optional {abstract} + + save(Product) {abstract} + + update(Product) {abstract} + } + class ProductDaoImpl { + - dataSource : DataSource + + ProductDaoImpl(userDataSource : DataSource) + + findByName(name : String) : Optional + + save(product : Product) + + update(product : Product) + } +} +Product --> ProductDao +Customer --> CustomerDao +Customer --> Product +CustomerDaoImpl ..|> CustomerDao +ProductDaoImpl ..|> ProductDao +@enduml \ No newline at end of file diff --git a/domain-model/pom.xml b/domain-model/pom.xml new file mode 100644 index 000000000000..933c186790b0 --- /dev/null +++ b/domain-model/pom.xml @@ -0,0 +1,84 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + domain-model + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + com.h2database + h2 + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + org.joda + joda-money + 1.0.4 + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.domainmodel.App + + + + + + + + + diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/App.java b/domain-model/src/main/java/com/iluwatar/domainmodel/App.java new file mode 100644 index 000000000000..3f209a35a5f8 --- /dev/null +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/App.java @@ -0,0 +1,168 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import static org.joda.money.CurrencyUnit.USD; + +import java.sql.SQLException; +import java.time.LocalDate; +import javax.sql.DataSource; +import org.h2.jdbcx.JdbcDataSource; +import org.joda.money.Money; + +/** + * Domain Model pattern is a more complex solution for organizing domain logic than Transaction + * Script and Table Module. It provides an object-oriented way of dealing with complicated logic. + * Instead of having one procedure that handles all business logic for a user action like + * Transaction Script there are multiple objects and each of them handles a slice of domain logic + * that is relevant to it. The significant difference between Domain Model and Table Module pattern + * is that in Table Module a single class encapsulates all the domain logic for all records stored + * in table when in Domain Model every single class represents only one record in underlying table. + * + *

    In this example, we will use the Domain Model pattern to implement buying of products by + * customers in a Shop. The main method will create a customer and a few products. Customer will do + * a few purchases, try to buy product which are too expensive for him, return product which he + * bought to return money. + */ +public class App { + + public static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; + + public static final String CREATE_SCHEMA_SQL = + "CREATE TABLE CUSTOMERS (name varchar primary key, money decimal);" + + "CREATE TABLE PRODUCTS (name varchar primary key, price decimal, expiration_date date);" + + "CREATE TABLE PURCHASES (" + + "product_name varchar references PRODUCTS(name)," + + "customer_name varchar references CUSTOMERS(name));"; + + public static final String DELETE_SCHEMA_SQL = + "DROP TABLE PURCHASES IF EXISTS;" + + "DROP TABLE CUSTOMERS IF EXISTS;" + + "DROP TABLE PRODUCTS IF EXISTS;"; + + /** + * Program entry point. + * + * @param args command line arguments + * @throws Exception if any error occurs + */ + public static void main(String[] args) throws Exception { + + // Create data source and create the customers, products and purchases tables + final var dataSource = createDataSource(); + deleteSchema(dataSource); + createSchema(dataSource); + + // create customer + var customerDao = new CustomerDaoImpl(dataSource); + + var tom = + Customer.builder().name("Tom").money(Money.of(USD, 30)).customerDao(customerDao).build(); + + tom.save(); + + // create products + var productDao = new ProductDaoImpl(dataSource); + + var eggs = + Product.builder() + .name("Eggs") + .price(Money.of(USD, 10.0)) + .expirationDate(LocalDate.now().plusDays(7)) + .productDao(productDao) + .build(); + + var butter = + Product.builder() + .name("Butter") + .price(Money.of(USD, 20.00)) + .expirationDate(LocalDate.now().plusDays(9)) + .productDao(productDao) + .build(); + + var cheese = + Product.builder() + .name("Cheese") + .price(Money.of(USD, 25.0)) + .expirationDate(LocalDate.now().plusDays(2)) + .productDao(productDao) + .build(); + + eggs.save(); + butter.save(); + cheese.save(); + + // show money balance of customer after each purchase + tom.showBalance(); + tom.showPurchases(); + + // buy eggs + tom.buyProduct(eggs); + tom.showBalance(); + + // buy butter + tom.buyProduct(butter); + tom.showBalance(); + + // trying to buy cheese, but receive a refusal + // because he didn't have enough money + tom.buyProduct(cheese); + tom.showBalance(); + + // return butter and get money back + tom.returnProduct(butter); + tom.showBalance(); + + // Tom can buy cheese now because he has enough money + // and there is a discount on cheese because it expires in 2 days + tom.buyProduct(cheese); + + tom.save(); + + // show money balance and purchases after shopping + tom.showBalance(); + tom.showPurchases(); + } + + private static DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setUrl(H2_DB_URL); + return dataSource; + } + + private static void deleteSchema(DataSource dataSource) throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(DELETE_SCHEMA_SQL); + } + } + + private static void createSchema(DataSource dataSource) throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(CREATE_SCHEMA_SQL); + } + } +} diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/Customer.java b/domain-model/src/main/java/com/iluwatar/domainmodel/Customer.java new file mode 100644 index 000000000000..019a06c8470b --- /dev/null +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/Customer.java @@ -0,0 +1,146 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import lombok.Builder; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.joda.money.Money; + +/** + * This class organizes domain logic of customer. A single instance of this class contains both the + * data and behavior of a single customer. + */ +@Slf4j +@Getter +@Setter +@Builder +public class Customer { + + @NonNull private final CustomerDao customerDao; + @Builder.Default private List purchases = new ArrayList<>(); + @NonNull private String name; + @NonNull private Money money; + + /** Save customer or update if customer already exist. */ + public void save() { + try { + Optional customer = customerDao.findByName(name); + if (customer.isPresent()) { + customerDao.update(this); + } else { + customerDao.save(this); + } + } catch (SQLException ex) { + LOGGER.error(ex.getMessage()); + } + } + + /** + * Add product to purchases, save to db and withdraw money. + * + * @param product to buy. + */ + public void buyProduct(Product product) { + LOGGER.info( + String.format( + "%s want to buy %s($%.2f)...", + name, product.getName(), product.getSalePrice().getAmount())); + try { + withdraw(product.getSalePrice()); + } catch (IllegalArgumentException ex) { + LOGGER.error(ex.getMessage()); + return; + } + try { + customerDao.addProduct(product, this); + purchases.add(product); + LOGGER.info(String.format("%s bought %s!", name, product.getName())); + } catch (SQLException exception) { + receiveMoney(product.getSalePrice()); + LOGGER.error(exception.getMessage()); + } + } + + /** + * Remove product from purchases, delete from db and return money. + * + * @param product to return. + */ + public void returnProduct(Product product) { + LOGGER.info( + String.format( + "%s want to return %s($%.2f)...", + name, product.getName(), product.getSalePrice().getAmount())); + if (purchases.contains(product)) { + try { + customerDao.deleteProduct(product, this); + purchases.remove(product); + receiveMoney(product.getSalePrice()); + LOGGER.info(String.format("%s returned %s!", name, product.getName())); + } catch (SQLException ex) { + LOGGER.error(ex.getMessage()); + } + } else { + LOGGER.error(String.format("%s didn't buy %s...", name, product.getName())); + } + } + + /** Print customer's purchases. */ + public void showPurchases() { + Optional purchasesToShow = + purchases.stream() + .map(p -> p.getName() + " - $" + p.getSalePrice().getAmount()) + .reduce((p1, p2) -> p1 + ", " + p2); + + if (purchasesToShow.isPresent()) { + LOGGER.info(name + " bought: " + purchasesToShow.get()); + } else { + LOGGER.info(name + " didn't bought anything"); + } + } + + /** Print customer's money balance. */ + public void showBalance() { + LOGGER.info(name + " balance: " + money); + } + + private void withdraw(Money amount) throws IllegalArgumentException { + if (money.compareTo(amount) < 0) { + throw new IllegalArgumentException("Not enough money!"); + } + money = money.minus(amount); + } + + private void receiveMoney(Money amount) { + money = money.plus(amount); + } +} diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDao.java b/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDao.java new file mode 100644 index 000000000000..18db0ab0bd8d --- /dev/null +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDao.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import java.sql.SQLException; +import java.util.Optional; + +/** DAO interface for customer transactions. */ +public interface CustomerDao { + + Optional findByName(String name) throws SQLException; + + void update(Customer customer) throws SQLException; + + void save(Customer customer) throws SQLException; + + void addProduct(Product product, Customer customer) throws SQLException; + + void deleteProduct(Product product, Customer customer) throws SQLException; +} diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDaoImpl.java b/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDaoImpl.java new file mode 100644 index 000000000000..cff4e30bc079 --- /dev/null +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDaoImpl.java @@ -0,0 +1,110 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import static org.joda.money.CurrencyUnit.USD; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Optional; +import javax.sql.DataSource; +import org.joda.money.Money; + +/** Implementations for database operations of Customer. */ +public class CustomerDaoImpl implements CustomerDao { + + private final DataSource dataSource; + + public CustomerDaoImpl(final DataSource userDataSource) { + this.dataSource = userDataSource; + } + + @Override + public Optional findByName(String name) throws SQLException { + var sql = "select * from CUSTOMERS where name = ?;"; + + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql)) { + preparedStatement.setString(1, name); + + ResultSet rs = preparedStatement.executeQuery(); + + if (rs.next()) { + return Optional.of( + Customer.builder() + .name(rs.getString("name")) + .money(Money.of(USD, rs.getBigDecimal("money"))) + .customerDao(this) + .build()); + } else { + return Optional.empty(); + } + } + } + + @Override + public void update(Customer customer) throws SQLException { + var sql = "update CUSTOMERS set money = ? where name = ?;"; + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql)) { + preparedStatement.setBigDecimal(1, customer.getMoney().getAmount()); + preparedStatement.setString(2, customer.getName()); + preparedStatement.executeUpdate(); + } + } + + @Override + public void save(Customer customer) throws SQLException { + var sql = "insert into CUSTOMERS (name, money) values (?, ?)"; + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql)) { + preparedStatement.setString(1, customer.getName()); + preparedStatement.setBigDecimal(2, customer.getMoney().getAmount()); + preparedStatement.executeUpdate(); + } + } + + @Override + public void addProduct(Product product, Customer customer) throws SQLException { + var sql = "insert into PURCHASES (product_name, customer_name) values (?,?)"; + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql)) { + preparedStatement.setString(1, product.getName()); + preparedStatement.setString(2, customer.getName()); + preparedStatement.executeUpdate(); + } + } + + @Override + public void deleteProduct(Product product, Customer customer) throws SQLException { + var sql = "delete from PURCHASES where product_name = ? and customer_name = ?"; + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql)) { + preparedStatement.setString(1, product.getName()); + preparedStatement.setString(2, customer.getName()); + preparedStatement.executeUpdate(); + } + } +} diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/Product.java b/domain-model/src/main/java/com/iluwatar/domainmodel/Product.java new file mode 100644 index 000000000000..9d91779773ae --- /dev/null +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/Product.java @@ -0,0 +1,89 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import static org.joda.money.CurrencyUnit.USD; + +import java.math.RoundingMode; +import java.sql.SQLException; +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.Optional; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.joda.money.Money; + +/** + * This class organizes domain logic of product. A single instance of this class contains both the + * data and behavior of a single product. + */ +@Slf4j +@Getter +@Setter +@Builder +@AllArgsConstructor +public class Product { + + private static final int DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE = 4; + private static final double DISCOUNT_RATE = 0.2; + + @NonNull private final ProductDao productDao; + @NonNull private String name; + @NonNull private Money price; + @NonNull private LocalDate expirationDate; + + /** Save product or update if product already exist. */ + public void save() { + try { + Optional product = productDao.findByName(name); + if (product.isPresent()) { + productDao.update(this); + } else { + productDao.save(this); + } + } catch (SQLException ex) { + LOGGER.error(ex.getMessage()); + } + } + + /** Calculate sale price of product with discount. */ + public Money getSalePrice() { + return price.minus(calculateDiscount()); + } + + private Money calculateDiscount() { + if (ChronoUnit.DAYS.between(LocalDate.now(), expirationDate) + < DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE) { + + return price.multipliedBy(DISCOUNT_RATE, RoundingMode.DOWN); + } + + return Money.zero(USD); + } +} diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDao.java b/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDao.java new file mode 100644 index 000000000000..5a2644829565 --- /dev/null +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDao.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import java.sql.SQLException; +import java.util.Optional; + +/** DAO interface for product transactions. */ +public interface ProductDao { + + Optional findByName(String name) throws SQLException; + + void save(Product product) throws SQLException; + + void update(Product product) throws SQLException; +} diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDaoImpl.java b/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDaoImpl.java new file mode 100644 index 000000000000..6313e8afa1fb --- /dev/null +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDaoImpl.java @@ -0,0 +1,92 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import static org.joda.money.CurrencyUnit.USD; + +import java.sql.Date; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Optional; +import javax.sql.DataSource; +import org.joda.money.Money; + +/** Implementations for database transactions of Product. */ +public class ProductDaoImpl implements ProductDao { + + private final DataSource dataSource; + + public ProductDaoImpl(final DataSource userDataSource) { + this.dataSource = userDataSource; + } + + @Override + public Optional findByName(String name) throws SQLException { + var sql = "select * from PRODUCTS where name = ?;"; + + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql)) { + preparedStatement.setString(1, name); + + ResultSet rs = preparedStatement.executeQuery(); + + if (rs.next()) { + return Optional.of( + Product.builder() + .name(rs.getString("name")) + .price(Money.of(USD, rs.getBigDecimal("price"))) + .expirationDate(rs.getDate("expiration_date").toLocalDate()) + .productDao(this) + .build()); + } else { + return Optional.empty(); + } + } + } + + @Override + public void save(Product product) throws SQLException { + var sql = "insert into PRODUCTS (name, price, expiration_date) values (?, ?, ?)"; + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql)) { + preparedStatement.setString(1, product.getName()); + preparedStatement.setBigDecimal(2, product.getPrice().getAmount()); + preparedStatement.setDate(3, Date.valueOf(product.getExpirationDate())); + preparedStatement.executeUpdate(); + } + } + + @Override + public void update(Product product) throws SQLException { + var sql = "update PRODUCTS set price = ?, expiration_date = ? where name = ?;"; + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql)) { + preparedStatement.setBigDecimal(1, product.getPrice().getAmount()); + preparedStatement.setDate(2, Date.valueOf(product.getExpirationDate())); + preparedStatement.setString(3, product.getName()); + preparedStatement.executeUpdate(); + } + } +} diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/AppTest.java b/domain-model/src/test/java/com/iluwatar/domainmodel/AppTest.java new file mode 100644 index 000000000000..f15b33c2d1b3 --- /dev/null +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Tests that Domain Model example runs without errors. */ +final class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerDaoImplTest.java b/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerDaoImplTest.java new file mode 100644 index 000000000000..aeab249ba7c7 --- /dev/null +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerDaoImplTest.java @@ -0,0 +1,169 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import static org.joda.money.CurrencyUnit.USD; +import static org.junit.jupiter.api.Assertions.*; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDate; +import javax.sql.DataSource; +import org.joda.money.CurrencyUnit; +import org.joda.money.Money; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CustomerDaoImplTest { + + public static final String INSERT_CUSTOMER_SQL = "insert into CUSTOMERS values('customer', 100)"; + public static final String SELECT_CUSTOMERS_SQL = "select name, money from CUSTOMERS"; + public static final String INSERT_PURCHASES_SQL = + "insert into PURCHASES values('product', 'customer')"; + public static final String SELECT_PURCHASES_SQL = + "select product_name, customer_name from PURCHASES"; + + private DataSource dataSource; + private Product product; + private Customer customer; + private CustomerDao customerDao; + + @BeforeEach + void setUp() throws SQLException { + // create db schema + dataSource = TestUtils.createDataSource(); + + TestUtils.deleteSchema(dataSource); + TestUtils.createSchema(dataSource); + + // setup objects + customerDao = new CustomerDaoImpl(dataSource); + + customer = + Customer.builder() + .name("customer") + .money(Money.of(CurrencyUnit.USD, 100.0)) + .customerDao(customerDao) + .build(); + + product = + Product.builder() + .name("product") + .price(Money.of(USD, 100.0)) + .expirationDate(LocalDate.parse("2021-06-27")) + .productDao(new ProductDaoImpl(dataSource)) + .build(); + } + + @AfterEach + void tearDown() throws SQLException { + TestUtils.deleteSchema(dataSource); + } + + @Test + void shouldFindCustomerByName() throws SQLException { + var customer = customerDao.findByName("customer"); + + assertTrue(customer.isEmpty()); + + TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource); + + customer = customerDao.findByName("customer"); + + assertTrue(customer.isPresent()); + assertEquals("customer", customer.get().getName()); + assertEquals(Money.of(USD, 100), customer.get().getMoney()); + } + + @Test + void shouldSaveCustomer() throws SQLException { + customerDao.save(customer); + + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(SELECT_CUSTOMERS_SQL)) { + + assertTrue(rs.next()); + assertEquals(customer.getName(), rs.getString("name")); + assertEquals(customer.getMoney(), Money.of(USD, rs.getBigDecimal("money"))); + } + + assertThrows(SQLException.class, () -> customerDao.save(customer)); + } + + @Test + void shouldUpdateCustomer() throws SQLException { + TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource); + + customer.setMoney(Money.of(CurrencyUnit.USD, 99)); + + customerDao.update(customer); + + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(SELECT_CUSTOMERS_SQL)) { + + assertTrue(rs.next()); + assertEquals(customer.getName(), rs.getString("name")); + assertEquals(customer.getMoney(), Money.of(USD, rs.getBigDecimal("money"))); + assertFalse(rs.next()); + } + } + + @Test + void shouldAddProductToPurchases() throws SQLException { + TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource); + TestUtils.executeSQL(ProductDaoImplTest.INSERT_PRODUCT_SQL, dataSource); + + customerDao.addProduct(product, customer); + + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(SELECT_PURCHASES_SQL)) { + + assertTrue(rs.next()); + assertEquals(product.getName(), rs.getString("product_name")); + assertEquals(customer.getName(), rs.getString("customer_name")); + assertFalse(rs.next()); + } + } + + @Test + void shouldDeleteProductFromPurchases() throws SQLException { + TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource); + TestUtils.executeSQL(ProductDaoImplTest.INSERT_PRODUCT_SQL, dataSource); + TestUtils.executeSQL(INSERT_PURCHASES_SQL, dataSource); + + customerDao.deleteProduct(product, customer); + + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(SELECT_PURCHASES_SQL)) { + + assertFalse(rs.next()); + } + } +} diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerTest.java b/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerTest.java new file mode 100644 index 000000000000..9d5f83a92156 --- /dev/null +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerTest.java @@ -0,0 +1,113 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import static org.joda.money.CurrencyUnit.USD; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + +import java.sql.SQLException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Optional; +import org.joda.money.CurrencyUnit; +import org.joda.money.Money; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CustomerTest { + + private CustomerDao customerDao; + private Customer customer; + private Product product; + + @BeforeEach + void setUp() { + customerDao = mock(CustomerDao.class); + + customer = + Customer.builder() + .name("customer") + .money(Money.of(CurrencyUnit.USD, 100.0)) + .customerDao(customerDao) + .build(); + + product = + Product.builder() + .name("product") + .price(Money.of(USD, 100.0)) + .expirationDate(LocalDate.now().plusDays(10)) + .productDao(mock(ProductDao.class)) + .build(); + } + + @Test + void shouldSaveCustomer() throws SQLException { + when(customerDao.findByName("customer")).thenReturn(Optional.empty()); + + customer.save(); + + verify(customerDao, times(1)).save(customer); + + when(customerDao.findByName("customer")).thenReturn(Optional.of(customer)); + + customer.save(); + + verify(customerDao, times(1)).update(customer); + } + + @Test + void shouldAddProductToPurchases() { + product.setPrice(Money.of(USD, 200.0)); + + customer.buyProduct(product); + + assertEquals(customer.getPurchases(), new ArrayList<>()); + assertEquals(customer.getMoney(), Money.of(USD, 100)); + + product.setPrice(Money.of(USD, 100.0)); + + customer.buyProduct(product); + + assertEquals(new ArrayList<>(Arrays.asList(product)), customer.getPurchases()); + assertEquals(Money.zero(USD), customer.getMoney()); + } + + @Test + void shouldRemoveProductFromPurchases() { + customer.setPurchases(new ArrayList<>(Arrays.asList(product))); + + customer.returnProduct(product); + + assertEquals(new ArrayList<>(), customer.getPurchases()); + assertEquals(Money.of(USD, 200), customer.getMoney()); + + customer.returnProduct(product); + + assertEquals(new ArrayList<>(), customer.getPurchases()); + assertEquals(Money.of(USD, 200), customer.getMoney()); + } +} diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/ProductDaoImplTest.java b/domain-model/src/test/java/com/iluwatar/domainmodel/ProductDaoImplTest.java new file mode 100644 index 000000000000..7631c3581ec8 --- /dev/null +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/ProductDaoImplTest.java @@ -0,0 +1,127 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import static org.joda.money.CurrencyUnit.USD; +import static org.junit.jupiter.api.Assertions.*; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDate; +import javax.sql.DataSource; +import org.joda.money.Money; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ProductDaoImplTest { + + public static final String INSERT_PRODUCT_SQL = + "insert into PRODUCTS values('product', 100, DATE '2021-06-27')"; + public static final String SELECT_PRODUCTS_SQL = + "select name, price, expiration_date from PRODUCTS"; + + private DataSource dataSource; + private ProductDao productDao; + private Product product; + + @BeforeEach + void setUp() throws SQLException { + // create schema + dataSource = TestUtils.createDataSource(); + + TestUtils.deleteSchema(dataSource); + TestUtils.createSchema(dataSource); + + // setup objects + productDao = new ProductDaoImpl(dataSource); + + product = + Product.builder() + .name("product") + .price(Money.of(USD, 100.0)) + .expirationDate(LocalDate.parse("2021-06-27")) + .productDao(productDao) + .build(); + } + + @AfterEach + void tearDown() throws SQLException { + TestUtils.deleteSchema(dataSource); + } + + @Test + void shouldFindProductByName() throws SQLException { + var product = productDao.findByName("product"); + + assertTrue(product.isEmpty()); + + TestUtils.executeSQL(INSERT_PRODUCT_SQL, dataSource); + + product = productDao.findByName("product"); + + assertTrue(product.isPresent()); + assertEquals("product", product.get().getName()); + assertEquals(Money.of(USD, 100), product.get().getPrice()); + assertEquals(LocalDate.parse("2021-06-27"), product.get().getExpirationDate()); + } + + @Test + void shouldSaveProduct() throws SQLException { + + productDao.save(product); + + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(SELECT_PRODUCTS_SQL)) { + + assertTrue(rs.next()); + assertEquals(product.getName(), rs.getString("name")); + assertEquals(product.getPrice(), Money.of(USD, rs.getBigDecimal("price"))); + assertEquals(product.getExpirationDate(), rs.getDate("expiration_date").toLocalDate()); + } + + assertThrows(SQLException.class, () -> productDao.save(product)); + } + + @Test + void shouldUpdateProduct() throws SQLException { + TestUtils.executeSQL(INSERT_PRODUCT_SQL, dataSource); + + product.setPrice(Money.of(USD, 99.0)); + + productDao.update(product); + + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(SELECT_PRODUCTS_SQL)) { + + assertTrue(rs.next()); + assertEquals(product.getName(), rs.getString("name")); + assertEquals(product.getPrice(), Money.of(USD, rs.getBigDecimal("price"))); + assertEquals(product.getExpirationDate(), rs.getDate("expiration_date").toLocalDate()); + } + } +} diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/ProductTest.java b/domain-model/src/test/java/com/iluwatar/domainmodel/ProductTest.java new file mode 100644 index 000000000000..f3193ce9b6aa --- /dev/null +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/ProductTest.java @@ -0,0 +1,79 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import static org.joda.money.CurrencyUnit.USD; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + +import java.sql.SQLException; +import java.time.LocalDate; +import java.util.Optional; +import org.joda.money.Money; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ProductTest { + + private ProductDao productDao; + private Product product; + + @BeforeEach + void setUp() { + productDao = mock(ProductDaoImpl.class); + + product = + Product.builder() + .name("product") + .price(Money.of(USD, 100.0)) + .expirationDate(LocalDate.now().plusDays(10)) + .productDao(productDao) + .build(); + } + + @Test + void shouldSaveProduct() throws SQLException { + when(productDao.findByName("product")).thenReturn(Optional.empty()); + + product.save(); + + verify(productDao, times(1)).save(product); + + when(productDao.findByName("product")).thenReturn(Optional.of(product)); + + product.save(); + + verify(productDao, times(1)).update(product); + } + + @Test + void shouldGetSalePriceOfProduct() { + assertEquals(Money.of(USD, 100), product.getSalePrice()); + + product.setExpirationDate(LocalDate.now().plusDays(2)); + + assertEquals(Money.of(USD, 80), product.getSalePrice()); + } +} diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/TestUtils.java b/domain-model/src/test/java/com/iluwatar/domainmodel/TestUtils.java new file mode 100644 index 000000000000..8555cedc8b1d --- /dev/null +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/TestUtils.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.domainmodel; + +import java.sql.SQLException; +import javax.sql.DataSource; +import org.h2.jdbcx.JdbcDataSource; + +public class TestUtils { + + public static void executeSQL(String sql, DataSource dataSource) throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.executeUpdate(sql); + } + } + + public static void createSchema(DataSource dataSource) throws SQLException { + TestUtils.executeSQL(App.CREATE_SCHEMA_SQL, dataSource); + } + + public static void deleteSchema(DataSource dataSource) throws SQLException { + TestUtils.executeSQL(App.DELETE_SCHEMA_SQL, dataSource); + } + + public static DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setURL(App.H2_DB_URL); + return dataSource; + } +} diff --git a/double-buffer/README.md b/double-buffer/README.md new file mode 100644 index 000000000000..ab4d0b9b5b1a --- /dev/null +++ b/double-buffer/README.md @@ -0,0 +1,256 @@ +--- +title: "Double Buffer Pattern in Java: Enhancing Animation and Graphics Performance" +shortTitle: Double Buffer +description: "Learn how the Double Buffer Pattern in Java optimizes performance and ensures smooth graphics rendering for applications. Explore practical examples and real-world use cases." +category: Behavioral +language: en +tag: + - Buffering + - Game programming + - Optimization + - Performance +--- + +## Also known as + +* Buffer Switching +* Ping-Pong Buffer + +## Intent of Double Buffer Design Pattern + +The Double Buffer pattern in Java is designed to reduce rendering time and enhance performance in graphical or computational applications by utilizing two buffers. This pattern is crucial for smooth graphics rendering and is commonly used in game development and other real-time applications. + +## Detailed Explanation of Double Buffer Pattern with Real-World Examples + +Real-world example + +> Imagine a busy restaurant kitchen where chefs are constantly preparing dishes, and waitstaff are constantly picking up ready dishes to serve to customers. To avoid confusion and delays, the restaurant uses a double buffer system. They have two counters: one for chefs to place newly prepared dishes and another for waitstaff to pick up the dishes. While the chefs are filling one counter with prepared dishes, the waitstaff are simultaneously clearing the other counter by picking up dishes to serve. Once the waitstaff have cleared all dishes from their counter, they switch to the counter where the chefs have placed the newly prepared dishes, and the chefs start filling the now-empty counter. This system ensures a smooth and continuous workflow without either party waiting idly, maximizing efficiency and minimizing downtime. + +In plain words + +> It ensures a state that is being rendered correctly while that state is modifying incrementally. It is widely used in computer graphics. + +Wikipedia says + +> In computer science, multiple buffering is the use of more than one buffer to hold a block of data, so that a "reader" will see a complete (though perhaps old) version of the data, rather than a partially updated version of the data being created by a "writer". It is very commonly used for computer display images. + +Sequence diagram + +![Double Buffer sequence diagram](./etc/double-buffer-sequence-diagram.png) + +## Programmatic Example of Double Buffer Pattern in Java + +A typical example, and one that every game engine must address, is rendering. When the game draws the world the users see, it does so one piece at a time - the mountains in the distance, the rolling hills, the trees, each in its turn. If the user watched the view draw incrementally like that, the illusion of a coherent world would be shattered. The scene must update smoothly and quickly, displaying a series of complete frames, each appearing instantly. Double buffering solves the problem. + +`Buffer` interface that assures basic functionalities of a buffer. + +```java +public interface Buffer { + + void clear(int x, int y); + + void draw(int x, int y); + + void clearAll(); + + Pixel[] getPixels(); +} +``` + +One of the implementations of `Buffer` interface. + +```java +public class FrameBuffer implements Buffer { + + public static final int WIDTH = 10; + public static final int HEIGHT = 8; + + private final Pixel[] pixels = new Pixel[WIDTH * HEIGHT]; + + public FrameBuffer() { + clearAll(); + } + + @Override + public void clear(int x, int y) { + pixels[getIndex(x, y)] = Pixel.WHITE; + } + + @Override + public void draw(int x, int y) { + pixels[getIndex(x, y)] = Pixel.BLACK; + } + + @Override + public void clearAll() { + Arrays.fill(pixels, Pixel.WHITE); + } + + @Override + public Pixel[] getPixels() { + return pixels; + } + + private int getIndex(int x, int y) { + return x + WIDTH * y; + } +} +``` + +We support black and white pixels. + +```java +public enum Pixel { + + WHITE, + BLACK +} +``` + +`Scene` represents the game scene where current buffer has already been rendered. + +```java +@Slf4j +public class Scene { + + private final Buffer[] frameBuffers; + + private int current; + + private int next; + + public Scene() { + frameBuffers = new FrameBuffer[2]; + frameBuffers[0] = new FrameBuffer(); + frameBuffers[1] = new FrameBuffer(); + current = 0; + next = 1; + } + + public void draw(List> coordinateList) { + LOGGER.info("Start drawing next frame"); + LOGGER.info("Current buffer: " + current + " Next buffer: " + next); + frameBuffers[next].clearAll(); + coordinateList.forEach(coordinate -> { + var x = coordinate.getKey(); + var y = coordinate.getValue(); + frameBuffers[next].draw(x, y); + }); + LOGGER.info("Swap current and next buffer"); + swap(); + LOGGER.info("Finish swapping"); + LOGGER.info("Current buffer: " + current + " Next buffer: " + next); + } + + public Buffer getBuffer() { + LOGGER.info("Get current buffer: " + current); + return frameBuffers[current]; + } + + private void swap() { + current = current ^ next; + next = current ^ next; + current = current ^ next; + } + +} +``` + +Now, we can show the `App` class that drives the double buffering example. + +```java +@Slf4j +public class App { + + public static void main(String[] args) { + final var scene = new Scene(); + var drawPixels1 = List.of( + new MutablePair<>(1, 1), + new MutablePair<>(5, 6), + new MutablePair<>(3, 2) + ); + scene.draw(drawPixels1); + var buffer1 = scene.getBuffer(); + printBlackPixelCoordinate(buffer1); + + var drawPixels2 = List.of( + new MutablePair<>(3, 7), + new MutablePair<>(6, 1) + ); + scene.draw(drawPixels2); + var buffer2 = scene.getBuffer(); + printBlackPixelCoordinate(buffer2); + } + + private static void printBlackPixelCoordinate(Buffer buffer) { + StringBuilder log = new StringBuilder("Black Pixels: "); + var pixels = buffer.getPixels(); + for (var i = 0; i < pixels.length; ++i) { + if (pixels[i] == Pixel.BLACK) { + var y = i / FrameBuffer.WIDTH; + var x = i % FrameBuffer.WIDTH; + log.append(" (").append(x).append(", ").append(y).append(")"); + } + } + LOGGER.info(log.toString()); + } +} +``` + +The console output: + +```text +12:33:02.525 [main] INFO com.iluwatar.doublebuffer.Scene -- Start drawing next frame +12:33:02.529 [main] INFO com.iluwatar.doublebuffer.Scene -- Current buffer: 0 Next buffer: 1 +12:33:02.529 [main] INFO com.iluwatar.doublebuffer.Scene -- Swap current and next buffer +12:33:02.529 [main] INFO com.iluwatar.doublebuffer.Scene -- Finish swapping +12:33:02.529 [main] INFO com.iluwatar.doublebuffer.Scene -- Current buffer: 1 Next buffer: 0 +12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Get current buffer: 1 +12:33:02.530 [main] INFO com.iluwatar.doublebuffer.App -- Black Pixels: (1, 1) (3, 2) (5, 6) +12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Start drawing next frame +12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Current buffer: 1 Next buffer: 0 +12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Swap current and next buffer +12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Finish swapping +12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Current buffer: 0 Next buffer: 1 +12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Get current buffer: 0 +12:33:02.530 [main] INFO com.iluwatar.doublebuffer.App -- Black Pixels: (6, 1) (3, 7) +``` + +## When to Use the Double Buffer Pattern in Java + +* Real-time Applications: Ideal for video games, simulations, and GUI applications where frequent and smooth display updates are essential. +* High Computational Tasks: Suitable for applications that require intensive data preparation, enabling parallel processing and display. +* Minimizing Lag: Effective in reducing lag or stutter in data or graphics display. + +## Real-World Applications of Double Buffer Pattern in Java + +* Graphics Rendering Engines: Widely used in 2D and 3D rendering engines to ensure fluid animations and transitions. +* GUI Frameworks: Enhances the responsiveness and smoothness of user interfaces. +* Simulation and Modeling: Ensures real-time updates in simulations without interrupting ongoing processes. +* Video Playback Software: Provides seamless video playback by preloading the next frame during the display of the current one. + +## Benefits and Trade-offs of Double Buffer Pattern + +Benefits: + +* Smooth User Experience: Pre-renders frames to deliver smooth animations and transitions. +* Performance Optimization: Allows background rendering, optimizing overall application performance. +* Minimized Flickering: Reduces flickering and visual artifacts in graphical applications. + +Trade-offs: + +* Memory Overhead: Requires additional memory for the secondary buffer, potentially increasing memory usage. +* Implementation Complexity: Adds complexity to the architecture, necessitating careful buffer management. +* Latency: May introduce slight delays as data must be fully rendered in the back buffer before display. + +## Related Java Design Patterns + +* Triple Buffering: An extension of the Double Buffer pattern, where three buffers are used to further optimize rendering and reduce latency. +* [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): The Double Buffer pattern can be seen as a variant of the Producer-Consumer pattern, with one buffer being "produced" while the other is "consumed". +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Often used in conjunction with the Strategy pattern to dynamically choose the buffering strategy based on runtime conditions. + +## References and Credits + +* [Game Programming Patterns](https://amzn.to/4ayDNkS) +* [Real-Time Design Patterns: Robust Scalable Architecture for Real-Time Systems](https://amzn.to/3xFfNxA) +* [Double Buffer (Game Programming Patterns)](https://gameprogrammingpatterns.com/double-buffer.html) diff --git a/double-buffer/etc/double-buffer-sequence-diagram.png b/double-buffer/etc/double-buffer-sequence-diagram.png new file mode 100644 index 000000000000..365dff15a718 Binary files /dev/null and b/double-buffer/etc/double-buffer-sequence-diagram.png differ diff --git a/double-buffer/etc/double-buffer.urm.png b/double-buffer/etc/double-buffer.urm.png new file mode 100644 index 000000000000..072ec4dad8be Binary files /dev/null and b/double-buffer/etc/double-buffer.urm.png differ diff --git a/double-buffer/etc/double-buffer.urm.puml b/double-buffer/etc/double-buffer.urm.puml new file mode 100644 index 000000000000..7555c972b5ed --- /dev/null +++ b/double-buffer/etc/double-buffer.urm.puml @@ -0,0 +1,45 @@ +@startuml +package com.iluwatar.doublebuffer { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + - printBlackPixelCoordinate(buffer : Buffer) {static} + } + interface Buffer { + + clear(int, int) {abstract} + + clearAll() {abstract} + + draw(int, int) {abstract} + + getPixels() : Pixel[] {abstract} + } + class FrameBuffer { + + HEIGHT : int {static} + + WIDTH : int {static} + - pixels : Pixel[] + + FrameBuffer() + + clear(x : int, y : int) + + clearAll() + + draw(x : int, y : int) + - getIndex(x : int, y : int) : int + + getPixels() : Pixel[] + } + enum Pixel { + + BLACK {static} + + WHITE {static} + - color : int + + valueOf(name : String) : Pixel {static} + + values() : Pixel[] {static} + } + class Scene { + - LOGGER : Logger {static} + - current : int + - frameBuffers : Buffer[] + - next : int + + Scene() + + draw(coordinateList : List>) + + getBuffer() : Buffer + - swap() + } +} +FrameBuffer ..|> Buffer +@enduml \ No newline at end of file diff --git a/double-buffer/pom.xml b/double-buffer/pom.xml new file mode 100644 index 000000000000..ad5bf6c3e314 --- /dev/null +++ b/double-buffer/pom.xml @@ -0,0 +1,75 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + double-buffer + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.apache.commons + commons-lang3 + 3.17.0 + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.doublebuffer.App + + + + + + + + + diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java new file mode 100644 index 000000000000..899f714667d3 --- /dev/null +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java @@ -0,0 +1,72 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.doublebuffer; + +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.tuple.MutablePair; + +/** + * Double buffering is a term used to describe a device that has two buffers. The usage of multiple + * buffers increases the overall throughput of a device and helps prevents bottlenecks. This example + * shows using double buffer pattern on graphics. It is used to show one image or frame while a + * separate frame is being buffered to be shown next. This method makes animations and games look + * more realistic than the same done in a single buffer mode. + */ +@Slf4j +public class App { + + /** + * Program main entry point. + * + * @param args runtime arguments + */ + public static void main(String[] args) { + final var scene = new Scene(); + var drawPixels1 = + List.of(new MutablePair<>(1, 1), new MutablePair<>(5, 6), new MutablePair<>(3, 2)); + scene.draw(drawPixels1); + var buffer1 = scene.getBuffer(); + printBlackPixelCoordinate(buffer1); + + var drawPixels2 = List.of(new MutablePair<>(3, 7), new MutablePair<>(6, 1)); + scene.draw(drawPixels2); + var buffer2 = scene.getBuffer(); + printBlackPixelCoordinate(buffer2); + } + + private static void printBlackPixelCoordinate(Buffer buffer) { + StringBuilder log = new StringBuilder("Black Pixels: "); + var pixels = buffer.getPixels(); + for (var i = 0; i < pixels.length; ++i) { + if (pixels[i] == Pixel.BLACK) { + var y = i / FrameBuffer.WIDTH; + var x = i % FrameBuffer.WIDTH; + log.append(" (").append(x).append(", ").append(y).append(")"); + } + } + LOGGER.info(log.toString()); + } +} diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java new file mode 100644 index 000000000000..191ad0e12225 --- /dev/null +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java @@ -0,0 +1,55 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.doublebuffer; + +/** Buffer interface. */ +public interface Buffer { + + /** + * Clear the pixel in (x, y). + * + * @param x X coordinate + * @param y Y coordinate + */ + void clear(int x, int y); + + /** + * Draw the pixel in (x, y). + * + * @param x X coordinate + * @param y Y coordinate + */ + void draw(int x, int y); + + /** Clear all the pixels. */ + void clearAll(); + + /** + * Get all the pixels. + * + * @return pixel list + */ + Pixel[] getPixels(); +} diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java new file mode 100644 index 000000000000..e015bb62e8b8 --- /dev/null +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java @@ -0,0 +1,64 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.doublebuffer; + +import java.util.Arrays; + +/** FrameBuffer implementation class. */ +public class FrameBuffer implements Buffer { + + public static final int WIDTH = 10; + public static final int HEIGHT = 8; + + private final Pixel[] pixels = new Pixel[WIDTH * HEIGHT]; + + public FrameBuffer() { + clearAll(); + } + + @Override + public void clear(int x, int y) { + pixels[getIndex(x, y)] = Pixel.WHITE; + } + + @Override + public void draw(int x, int y) { + pixels[getIndex(x, y)] = Pixel.BLACK; + } + + @Override + public void clearAll() { + Arrays.fill(pixels, Pixel.WHITE); + } + + @Override + public Pixel[] getPixels() { + return pixels; + } + + private int getIndex(int x, int y) { + return x + WIDTH * y; + } +} diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java new file mode 100644 index 000000000000..eea701e8afc6 --- /dev/null +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.doublebuffer; + +/** Pixel enum. Each pixel can be white (not drawn) or black (drawn). */ +public enum Pixel { + WHITE, + BLACK +} diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java new file mode 100644 index 000000000000..79a528fabe6b --- /dev/null +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java @@ -0,0 +1,81 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.doublebuffer; + +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.tuple.Pair; + +/** Scene class. Render the output frame. */ +@Slf4j +public class Scene { + + private final Buffer[] frameBuffers; + + private int current; + + private int next; + + /** Constructor of Scene. */ + public Scene() { + frameBuffers = new FrameBuffer[2]; + frameBuffers[0] = new FrameBuffer(); + frameBuffers[1] = new FrameBuffer(); + current = 0; + next = 1; + } + + /** + * Draw the next frame. + * + * @param coordinateList list of pixels of which the color should be black + */ + public void draw(List> coordinateList) { + LOGGER.info("Start drawing next frame"); + LOGGER.info("Current buffer: " + current + " Next buffer: " + next); + frameBuffers[next].clearAll(); + coordinateList.forEach( + coordinate -> { + var x = coordinate.getKey(); + var y = coordinate.getValue(); + frameBuffers[next].draw(x, y); + }); + LOGGER.info("Swap current and next buffer"); + swap(); + LOGGER.info("Finish swapping"); + LOGGER.info("Current buffer: " + current + " Next buffer: " + next); + } + + public Buffer getBuffer() { + LOGGER.info("Get current buffer: " + current); + return frameBuffers[current]; + } + + private void swap() { + current = current ^ next; + next = current ^ next; + current = current ^ next; + } +} diff --git a/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java b/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java new file mode 100644 index 000000000000..4c1d8674d66f --- /dev/null +++ b/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.doublebuffer; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** App unit test. */ +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/double-buffer/src/test/java/com/iluwatar/doublebuffer/FrameBufferTest.java b/double-buffer/src/test/java/com/iluwatar/doublebuffer/FrameBufferTest.java new file mode 100644 index 000000000000..2bd852a35898 --- /dev/null +++ b/double-buffer/src/test/java/com/iluwatar/doublebuffer/FrameBufferTest.java @@ -0,0 +1,92 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.doublebuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +/** FrameBuffer unit test. */ +class FrameBufferTest { + + @Test + void testClearAll() { + try { + var field = FrameBuffer.class.getDeclaredField("pixels"); + var pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH]; + Arrays.fill(pixels, Pixel.WHITE); + pixels[0] = Pixel.BLACK; + var frameBuffer = new FrameBuffer(); + field.setAccessible(true); + field.set(frameBuffer, pixels); + frameBuffer.clearAll(); + assertEquals(Pixel.WHITE, frameBuffer.getPixels()[0]); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Fail to modify field access."); + } + } + + @Test + void testClear() { + try { + var field = FrameBuffer.class.getDeclaredField("pixels"); + var pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH]; + Arrays.fill(pixels, Pixel.WHITE); + pixels[0] = Pixel.BLACK; + var frameBuffer = new FrameBuffer(); + field.setAccessible(true); + field.set(frameBuffer, pixels); + frameBuffer.clear(0, 0); + assertEquals(Pixel.WHITE, frameBuffer.getPixels()[0]); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Fail to modify field access."); + } + } + + @Test + void testDraw() { + var frameBuffer = new FrameBuffer(); + frameBuffer.draw(0, 0); + assertEquals(Pixel.BLACK, frameBuffer.getPixels()[0]); + } + + @Test + void testGetPixels() { + try { + var field = FrameBuffer.class.getDeclaredField("pixels"); + var pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH]; + Arrays.fill(pixels, Pixel.WHITE); + pixels[0] = Pixel.BLACK; + var frameBuffer = new FrameBuffer(); + field.setAccessible(true); + field.set(frameBuffer, pixels); + assertEquals(pixels, frameBuffer.getPixels()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Fail to modify field access."); + } + } +} diff --git a/double-buffer/src/test/java/com/iluwatar/doublebuffer/SceneTest.java b/double-buffer/src/test/java/com/iluwatar/doublebuffer/SceneTest.java new file mode 100644 index 000000000000..41806e566ba4 --- /dev/null +++ b/double-buffer/src/test/java/com/iluwatar/doublebuffer/SceneTest.java @@ -0,0 +1,73 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.doublebuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.ArrayList; +import org.junit.jupiter.api.Test; + +/** Scene unit tests. */ +class SceneTest { + + @Test + void testGetBuffer() { + try { + var scene = new Scene(); + var field1 = Scene.class.getDeclaredField("current"); + field1.setAccessible(true); + field1.set(scene, 0); + var frameBuffers = new FrameBuffer[2]; + var frameBuffer = new FrameBuffer(); + frameBuffer.draw(0, 0); + frameBuffers[0] = frameBuffer; + var field2 = Scene.class.getDeclaredField("frameBuffers"); + field2.setAccessible(true); + field2.set(scene, frameBuffers); + assertEquals(frameBuffer, scene.getBuffer()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Fail to access private field."); + } + } + + @Test + void testDraw() { + try { + var scene = new Scene(); + var field1 = Scene.class.getDeclaredField("current"); + var field2 = Scene.class.getDeclaredField("next"); + field1.setAccessible(true); + field1.set(scene, 0); + field2.setAccessible(true); + field2.set(scene, 1); + scene.draw(new ArrayList<>()); + assertEquals(1, field1.get(scene)); + assertEquals(0, field2.get(scene)); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Fail to access private field"); + } + } +} diff --git a/double-checked-locking/README.md b/double-checked-locking/README.md index da1fdd1a2ee7..0c4318d11f1c 100644 --- a/double-checked-locking/README.md +++ b/double-checked-locking/README.md @@ -1,25 +1,128 @@ --- -layout: pattern -title: Double Checked Locking -folder: double-checked-locking -permalink: /patterns/double-checked-locking/ -categories: Concurrency -tags: - - Java - - Difficulty-Beginner - - Idiom +title: "Double-Checked Locking Pattern in Java: Ensuring Thread Safety with Minimal Overhead" +shortTitle: Double-Checked Locking +description: "Master double-checked locking in Java with our detailed guide and practical examples. Enhance your Java design patterns knowledge today." +category: Concurrency +language: en +tag: + - Lazy initialization + - Optimization + - Performance + - Thread management --- -## Intent -Reduce the overhead of acquiring a lock by first testing the -locking criterion (the "lock hint") without actually acquiring the lock. Only -if the locking criterion check indicates that locking is required does the -actual locking logic proceed. +## Intent of Double-Checked Locking Design Pattern -![alt text](./etc/double_checked_locking_1.png "Double Checked Locking") +Reduce the overhead of acquiring a lock by first testing the locking criterion (the "lock hint") without actually acquiring the lock. Only if the locking criterion appears to be true does the actual locking logic proceed. Double-checked locking in Java helps in optimizing performance and ensuring thread safety. -## Applicability -Use the Double Checked Locking pattern when +## Detailed Explanation of Double-Checked Locking Pattern with Real-World Examples -* there is a concurrent access in object creation, e.g. singleton, where you want to create single instance of the same class and checking if it's null or not maybe not be enough when there are two or more threads that checks if instance is null or not. -* there is a concurrent access on a method where method's behaviour changes according to the some constraints and these constraint change within this method. +Real-world example + +> In a company with a high-value equipment room, employees first check a visible sign to see if the room is locked. If the sign shows it's unlocked, they enter directly; if locked, they use a security keycard for access. This two-step verification process efficiently manages security without unnecessary use of the electronic lock system, mirroring the Double-Checked Locking pattern used in software to minimize resource-intensive operations. + +In plain words + +> The Double-Checked Locking pattern in software minimizes costly locking operations by first checking the lock status in a low-cost manner before proceeding with a more resource-intensive lock, ensuring efficiency and thread safety during object initialization. + +Wikipedia says + +> In software engineering, double-checked locking (also known as "double-checked locking optimization") is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion (the "lock hint") before acquiring the lock. Locking occurs only if the locking criterion check indicates that locking is required. + +Flowchart + +![Double-Checked Locking flowchart](./etc/double-checked-locking-flowchart.png) + +## Programmatic Example of Double-Checked Locking Pattern in Java + +The Double-Checked Locking pattern is used in the `HolderThreadSafe` class to ensure that the `Heavy` object is only created once, even when accessed from multiple threads. Here's how it works: + +1. Check if the object is initialized (first check): If it is, return it immediately. + +```java +if (heavy == null) { + // ... +} +``` + +2. Synchronize the block of code where the object is created: This ensures that only one thread can create the object. + +```java +synchronized (this) { + // ... +} +``` + +3. Check again if the object is initialized. If another thread has already created the object by the time the current thread enters the synchronized block, return the created object. + +```java +if (heavy == null) { + heavy = new Heavy(); +} +``` + +4. Return the created object. + +```java +return heavy; +``` + +Here's the complete code for the `HolderThreadSafe` class: + +```java +public class HolderThreadSafe { + + private Heavy heavy; + + public HolderThreadSafe() { + LOGGER.info("Holder created"); + } + + public synchronized Heavy getHeavy() { + if (heavy == null) { + synchronized (this) { + if (heavy == null) { + heavy = new Heavy(); + } + } + } + return heavy; + } +} +``` + +In this code, the `Heavy` object is only created when the `getHeavy` method is called for the first time. This is known as lazy initialization. The double-checked locking pattern is used to ensure that the `Heavy` object is only created once, even when the `getHeavy` method is called from multiple threads simultaneously. + +## When to Use the Double-Checked Locking Pattern in Java + +Use the Double-Checked Locking pattern in Java when all the following conditions are met: + +* There is a singleton resource that is expensive to create. +* There is a need to reduce the overhead of acquiring a lock every time the resource is accessed. + +## Real-World Applications of Double-Checked Locking Pattern in Java + +* Singleton pattern implementation in multithreading environments. +* Lazy initialization of resource-intensive objects in Java applications. + +## Benefits and Trade-offs of Double-Checked Locking Pattern + +Benefits: + +* Performance gains from avoiding unnecessary locking after the object is initialized. +* Thread safety is maintained for critical initialization sections. + +Trade-offs: + +* Complex implementation can lead to mistakes, such as incorrect publishing of objects due to memory visibility issues. +* In Java, it can be redundant or broken in some versions unless volatile variables are used with care. + +## Related Java Design Patterns + +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Double-Checked Locking is often used in implementing thread-safe Singletons. +* [Lazy Loading](https://java-design-patterns.com/patterns/lazy-loading/): Shares the concept of delaying object creation until necessary. + +## References and Credits + +* [Java Concurrency in Practice](https://amzn.to/4aIAPKa) +* [Effective Java](https://amzn.to/3xx7KDh) diff --git a/double-checked-locking/etc/double-checked-locking-flowchart.png b/double-checked-locking/etc/double-checked-locking-flowchart.png new file mode 100644 index 000000000000..89d08529238b Binary files /dev/null and b/double-checked-locking/etc/double-checked-locking-flowchart.png differ diff --git a/double-checked-locking/etc/double-checked-locking.urm.puml b/double-checked-locking/etc/double-checked-locking.urm.puml new file mode 100644 index 000000000000..242519fce77c --- /dev/null +++ b/double-checked-locking/etc/double-checked-locking.urm.puml @@ -0,0 +1,22 @@ +@startuml +package com.iluwatar.doublechecked.locking { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Inventory { + - LOGGER : Logger {static} + - inventorySize : int + - items : List + - lock : Lock + + Inventory(inventorySize : int) + + addItem(item : Item) : boolean + + getItems() : List + } + class Item { + + Item() + } +} +Inventory --> "-items" Item +@enduml \ No newline at end of file diff --git a/double-checked-locking/pom.xml b/double-checked-locking/pom.xml index 7efd3c31ecd9..650c76700498 100644 --- a/double-checked-locking/pom.xml +++ b/double-checked-locking/pom.xml @@ -1,7 +1,9 @@ - - double-checked-locking.log - - double-checked-locking-%d.log - 5 - - - %-5p [%d{ISO8601,UTC}] %c: %m%n - - - - - - %-5p [%d{ISO8601,UTC}] %c: %m%n - - - - - - - - - - - - + + double-checked-locking.log + + double-checked-locking-%d.log + 5 + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + + + + diff --git a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java index 649afa58f4d6..9d9ae3496f7c 100644 --- a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java +++ b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,19 @@ */ package com.iluwatar.doublechecked.locking; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java index 2929afc5efa7..d79f6b660a00 100644 --- a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java +++ b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,42 +24,37 @@ */ package com.iluwatar.doublechecked.locking; +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTimeout; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.slf4j.LoggerFactory; - import java.util.LinkedList; import java.util.List; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; -import static java.time.Duration.ofMillis; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTimeout; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Date: 12/10/15 - 9:34 PM - * - * @author Jeroen Meulemeester - */ -public class InventoryTest { +/** InventoryTest */ +class InventoryTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(Inventory.class); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } @@ -67,9 +64,7 @@ public void tearDown() { */ private static final int THREAD_COUNT = 8; - /** - * The maximum number of {@link Item}s allowed in the {@link Inventory} - */ + /** The maximum number of {@link Item}s allowed in the {@link Inventory} */ private static final int INVENTORY_SIZE = 1000; /** @@ -79,39 +74,45 @@ public void tearDown() { * item limit. */ @Test - public void testAddItem() throws Exception { - assertTimeout(ofMillis(10000), () -> { - // Create a new inventory with a limit of 1000 items and put some load on the add method - final Inventory inventory = new Inventory(INVENTORY_SIZE); - final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); - for (int i = 0; i < THREAD_COUNT; i++) { - executorService.execute(() -> { - while (inventory.addItem(new Item())) {}; + void testAddItem() { + assertTimeout( + ofMillis(10000), + () -> { + // Create a new inventory with a limit of 1000 items and put some load on the add method + final var inventory = new Inventory(INVENTORY_SIZE); + final var executorService = Executors.newFixedThreadPool(THREAD_COUNT); + IntStream.range(0, THREAD_COUNT) + .mapToObj( + i -> + () -> { + while (inventory.addItem(new Item())) + ; + }) + .forEach(executorService::execute); + + // Wait until all threads have finished + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.SECONDS); + + // Check the number of items in the inventory. It should not have exceeded the allowed + // maximum + final var items = inventory.getItems(); + assertNotNull(items); + assertEquals(INVENTORY_SIZE, items.size()); + + assertEquals(INVENTORY_SIZE, appender.getLogSize()); + + // ... and check if the inventory size is increasing continuously + IntStream.range(0, items.size()) + .mapToObj( + i -> + appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1))) + .forEach(Assertions::assertTrue); }); - } - - // Wait until all threads have finished - executorService.shutdown(); - executorService.awaitTermination(5, TimeUnit.SECONDS); - - // Check the number of items in the inventory. It should not have exceeded the allowed maximum - final List items = inventory.getItems(); - assertNotNull(items); - assertEquals(INVENTORY_SIZE, items.size()); - - assertEquals(INVENTORY_SIZE, appender.getLogSize()); - - // ... and check if the inventory size is increasing continuously - for (int i = 0; i < items.size(); i++) { - assertTrue(appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1))); - } - }); } - - - private class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); + private static class InMemoryAppender extends AppenderBase { + private final List log = new LinkedList<>(); public InMemoryAppender(Class clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); @@ -127,5 +128,4 @@ public int getLogSize() { return log.size(); } } - } diff --git a/double-dispatch/README.md b/double-dispatch/README.md index ae87208a2639..05c0cdea4581 100644 --- a/double-dispatch/README.md +++ b/double-dispatch/README.md @@ -1,26 +1,152 @@ --- -layout: pattern -title: Double Dispatch -folder: double-dispatch -permalink: /patterns/double-dispatch/ -categories: Other -tags: - - Java - - Difficulty-Intermediate - - Idiom +title: "Double Dispatch Pattern in Java: Enhancing Polymorphic Behavior" +shortTitle: Double Dispatch +description: "Learn the Double Dispatch Pattern in Java with detailed implementation examples. Understand how to use this design pattern to enhance your Java applications. Read our comprehensive guide." +category: Behavioral +language: en +tag: + - Decoupling + - Dynamic typing + - Polymorphism + - Runtime --- -## Intent -Double Dispatch pattern is a way to create maintainable dynamic -behavior based on receiver and parameter types. +## Also known as -![alt text](./etc/double-dispatch.png "Double Dispatch") +* Multi-methods -## Applicability -Use the Double Dispatch pattern when +## Intent of Double Dispatch Design Pattern -* the dynamic behavior is not defined only based on receiving object's type but also on the receiving method's parameter type. +The Double Dispatch pattern is used to achieve dynamic polymorphism based on the types of two objects involved in a method call. It allows method behavior to be different based on the combination of the runtime types of both the object on which the method is called and the object being passed as a parameter. -## Real world examples +## Detailed Explanation of Double Dispatch Pattern with Real-World Examples -* [ObjectOutputStream](https://docs.oracle.com/javase/8/docs/api/java/io/ObjectOutputStream.html) +Real-world example + +> In a logistics company, different types of delivery vehicles like trucks, drones, and bikes interact with various types of packages (fragile, oversized, standard). The Double Dispatch design pattern is used to determine the optimal delivery method: trucks might handle oversized items, drones for quick deliveries of light packages, and bikes for urban areas. Each vehicle-package combination results in a different handling and delivery strategy, dynamically determined at runtime based on the types of both the vehicle and the package. + +In plain words + +> The Double Dispatch design pattern in Java allows a program to select a different function to execute based on the types of two objects involved in a call, enhancing flexibility in handling interactions between them. + +Wikipedia says + +> In software engineering, double dispatch is a special form of multiple dispatch, and a mechanism that dispatches a function call to different concrete functions depending on the runtime types of two objects involved in the call. In most object-oriented systems, the concrete function that is called from a function call in the code depends on the dynamic type of a single object and therefore they are known as single dispatch calls, or simply virtual function calls. + +Sequence diagram + +![Double Dispatch sequence diagram](./etc/double-dispatch-sequence-diagram.png) + +## Programmatic Example of Double Dispatch Pattern in Java + +The Double Dispatch pattern in Java is used to handle collisions between different types of game objects. Each game object is an instance of a class that extends the `GameObject` abstract class. The `GameObject` class has a `collision(GameObject)` method, which is overridden in each subclass to define the behavior when a collision occurs with another game object. Here is a simplified version of the `GameObject` class and its subclasses: + +```java +public abstract class GameObject { + // Other properties and methods... + + public abstract void collision(GameObject gameObject); +} + +public class FlamingAsteroid extends GameObject { + // Other properties and methods... + + @Override + public void collision(GameObject gameObject) { + gameObject.collisionWithFlamingAsteroid(this); + } +} + +public class SpaceStationMir extends GameObject { + // Other properties and methods... + + @Override + public void collision(GameObject gameObject) { + gameObject.collisionWithSpaceStationMir(this); + } +} +``` + +In the App class, the Double Dispatch pattern is used to check for collisions between all pairs of game objects: + +```java +public static void main(String[] args) { + // initialize game objects and print their status + LOGGER.info("Init objects and print their status"); + var objects = List.of( + new FlamingAsteroid(0, 0, 5, 5), + new SpaceStationMir(1, 1, 2, 2), + new Meteoroid(10, 10, 15, 15), + new SpaceStationIss(12, 12, 14, 14) + ); + objects.forEach(o -> LOGGER.info(o.toString())); + + // collision check + LOGGER.info("Collision check"); + objects.forEach(o1 -> objects.forEach(o2 -> { + if (o1 != o2 && o1.intersectsWith(o2)) { + o1.collision(o2); + } + })); + + // output eventual object statuses + LOGGER.info("Print object status after collision checks"); + objects.forEach(o -> LOGGER.info(o.toString())); +} +``` + +When a collision is detected between two objects, the `collision(GameObject)` method is called on the first object (o1) with the second object (o2) as the argument. This method call is dispatched at runtime to the appropriate `collision(GameObject)` method in the class of o1. Inside this method, another method call `gameObject.collisionWithX(this)` is made on o2 (where X is the type of o1), which is dispatched at runtime to the appropriate `collisionWithX(GameObject)` method in the class of o2. This is the "double dispatch" in Java - two method calls are dispatched at runtime based on the types of two objects. + +Here is the program output: + +``` +15:47:23.763 [main] INFO com.iluwatar.doubledispatch.App -- Init objects and print their status +15:47:23.772 [main] INFO com.iluwatar.doubledispatch.App -- FlamingAsteroid at [0,0,5,5] damaged=false onFire=true +15:47:23.772 [main] INFO com.iluwatar.doubledispatch.App -- SpaceStationMir at [1,1,2,2] damaged=false onFire=false +15:47:23.772 [main] INFO com.iluwatar.doubledispatch.App -- Meteoroid at [10,10,15,15] damaged=false onFire=false +15:47:23.772 [main] INFO com.iluwatar.doubledispatch.App -- SpaceStationIss at [12,12,14,14] damaged=false onFire=false +15:47:23.772 [main] INFO com.iluwatar.doubledispatch.App -- Collision check +15:47:23.772 [main] INFO com.iluwatar.doubledispatch.SpaceStationMir -- FlamingAsteroid hits SpaceStationMir. SpaceStationMir is damaged! SpaceStationMir is set on fire! +15:47:23.773 [main] INFO com.iluwatar.doubledispatch.Meteoroid -- SpaceStationMir hits FlamingAsteroid. +15:47:23.773 [main] INFO com.iluwatar.doubledispatch.SpaceStationMir -- {} is damaged! hits Meteoroid. +15:47:23.773 [main] INFO com.iluwatar.doubledispatch.Meteoroid -- SpaceStationIss hits Meteoroid. +15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- Print object status after collision checks +15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- FlamingAsteroid at [0,0,5,5] damaged=false onFire=true +15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- SpaceStationMir at [1,1,2,2] damaged=true onFire=true +15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- Meteoroid at [10,10,15,15] damaged=false onFire=false +15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- SpaceStationIss at [12,12,14,14] damaged=true onFire=false +``` + +## When to Use the Double Dispatch Pattern in Java + +* When the behavior of a method needs to vary not just based on the object it is called on, but also based on the type of the argument. +* In scenarios where if-else or switch-case type checks against the type of objects are cumbersome and not scalable. +* When implementing operations in domain classes without contaminating their code with complex decision-making logic about other domain classes. + +## Real-World Applications of Double Dispatch Pattern in Java + +* Graphical user interfaces where different actions are taken based on different types of mouse events interacting with different types of elements. +* Simulation systems where interactions between different types of objects need to trigger distinct behaviors. + +## Benefits and Trade-offs of Double Dispatch Pattern + +Benefits: + +* Increases the flexibility of code by handling interaction between objects in a manner that is easy to understand and maintain. +* Helps in adhering to the [Open/Closed Principle](https://java-design-patterns.com/principles/#open-closed-principle) by allowing new classes to be introduced without modifying existing classes. + +Trade-offs: + +* Can lead to more complex code structures, especially in languages like Java that do not support this pattern natively. +* May require additional effort in maintaining and extending as new classes are added. + +## Related Java Design Patterns + +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Similar in intent where it's used to choose an algorithm at runtime, though Strategy focuses on single object context rather than interactions between multiple objects. +* [Visitor](https://java-design-patterns.com/patterns/visitor/): Often used together with Double Dispatch to encapsulate operations performed on a set of element objects. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/4awj7cV) +* [Java Design Pattern Essentials](https://amzn.to/3Jg8ZZV) +* [Refactoring to Patterns](https://amzn.to/3vRBJ8k) diff --git a/double-dispatch/etc/double-dispatch-sequence-diagram.png b/double-dispatch/etc/double-dispatch-sequence-diagram.png new file mode 100644 index 000000000000..71302caf6d04 Binary files /dev/null and b/double-dispatch/etc/double-dispatch-sequence-diagram.png differ diff --git a/double-dispatch/etc/double-dispatch.urm.puml b/double-dispatch/etc/double-dispatch.urm.puml new file mode 100644 index 000000000000..17bcb1431bd6 --- /dev/null +++ b/double-dispatch/etc/double-dispatch.urm.puml @@ -0,0 +1,74 @@ +@startuml +package com.iluwatar.doubledispatch.constants { + class AppConstants { + + HITS : String {static} + + AppConstants() + } +} +package com.iluwatar.doubledispatch { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class FlamingAsteroid { + + FlamingAsteroid(left : int, top : int, right : int, bottom : int) + + collision(gameObject : GameObject) + } + abstract class GameObject { + - damaged : boolean + - onFire : boolean + + GameObject(left : int, top : int, right : int, bottom : int) + + collision(GameObject) {abstract} + + collisionResolve(FlamingAsteroid) {abstract} + + collisionResolve(Meteoroid) {abstract} + + collisionResolve(SpaceStationIss) {abstract} + + collisionResolve(SpaceStationMir) {abstract} + + isDamaged() : boolean + + isOnFire() : boolean + + setDamaged(damaged : boolean) + + setOnFire(onFire : boolean) + + toString() : String + } + class Meteoroid { + - LOGGER : Logger {static} + + Meteoroid(left : int, top : int, right : int, bottom : int) + + collision(gameObject : GameObject) + + collisionResolve(asteroid : FlamingAsteroid) + + collisionResolve(iss : SpaceStationIss) + + collisionResolve(meteoroid : Meteoroid) + + collisionResolve(mir : SpaceStationMir) + } + class Rectangle { + - bottom : int + - left : int + - right : int + - top : int + + Rectangle(left : int, top : int, right : int, bottom : int) + + getBottom() : int + + getLeft() : int + + getRight() : int + + getTop() : int + ~ intersectsWith(r : Rectangle) : boolean + + toString() : String + } + class SpaceStationIss { + + SpaceStationIss(left : int, top : int, right : int, bottom : int) + + collision(gameObject : GameObject) + } + class SpaceStationMir { + - LOGGER : Logger {static} + + SpaceStationMir(left : int, top : int, right : int, bottom : int) + + collision(gameObject : GameObject) + + collisionResolve(asteroid : FlamingAsteroid) + + collisionResolve(iss : SpaceStationIss) + + collisionResolve(meteoroid : Meteoroid) + + collisionResolve(mir : SpaceStationMir) + } +} +FlamingAsteroid --|> Meteoroid +GameObject --|> Rectangle +Meteoroid --|> GameObject +SpaceStationIss --|> SpaceStationMir +SpaceStationMir --|> GameObject +@enduml \ No newline at end of file diff --git a/double-dispatch/pom.xml b/double-dispatch/pom.xml index c64ab4ce91ba..035732318ee0 100644 --- a/double-dispatch/pom.xml +++ b/double-dispatch/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT double-dispatch - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.doubledispatch.App + + + + + + + + diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java index acb57d457167..bc38d0ee689d 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,60 +24,60 @@ */ package com.iluwatar.doubledispatch; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; import java.util.List; +import lombok.extern.slf4j.Slf4j; /** - * - * When a message with a parameter is sent to an object, the resultant behaviour is defined by the implementation of - * that method in the receiver. Sometimes the behaviour must also be determined by the type of the parameter. - *

    - * One way to implement this would be to create multiple instanceof-checks for the methods parameter. However, this - * creates a maintenance issue. When new types are added we would also need to change the method's implementation and - * add a new instanceof-check. This violates the single responsibility principle - a class should have only one reason - * to change. - *

    - * Instead of the instanceof-checks a better way is to make another virtual call on the parameter object. This way new - * functionality can be easily added without the need to modify existing implementation (open-closed principle). - *

    - * In this example we have hierarchy of objects ({@link GameObject}) that can collide to each other. Each object has its - * own coordinates which are checked against the other objects' coordinates. If there is an overlap, then the objects - * collide utilizing the Double Dispatch pattern. + * When a message with a parameter is sent to an object, the resultant behaviour is defined by the + * implementation of that method in the receiver. Sometimes the behaviour must also be determined by + * the type of the parameter. * + *

    One way to implement this would be to create multiple instanceof-checks for the methods + * parameter. However, this creates a maintenance issue. When new types are added we would also need + * to change the method's implementation and add a new instanceof-check. This violates the single + * responsibility principle - a class should have only one reason to change. + * + *

    Instead of the instanceof-checks a better way is to make another virtual call on the parameter + * object. This way new functionality can be easily added without the need to modify existing + * implementation (open-closed principle). + * + *

    In this example we have hierarchy of objects ({@link GameObject}) that can collide to each + * other. Each object has its own coordinates which are checked against the other objects' + * coordinates. If there is an overlap, then the objects collide utilizing the Double Dispatch + * pattern. */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * Program entry point - * - * @param args - * command line args + * Program entry point. + * + * @param args command line args */ public static void main(String[] args) { // initialize game objects and print their status - List objects = new ArrayList<>(); - objects.add(new FlamingAsteroid(0, 0, 5, 5)); - objects.add(new SpaceStationMir(1, 1, 2, 2)); - objects.add(new Meteoroid(10, 10, 15, 15)); - objects.add(new SpaceStationIss(12, 12, 14, 14)); - objects.stream().forEach(o -> LOGGER.info(o.toString())); - LOGGER.info(""); + LOGGER.info("Init objects and print their status"); + var objects = + List.of( + new FlamingAsteroid(0, 0, 5, 5), + new SpaceStationMir(1, 1, 2, 2), + new Meteoroid(10, 10, 15, 15), + new SpaceStationIss(12, 12, 14, 14)); + objects.forEach(o -> LOGGER.info(o.toString())); // collision check - objects.stream().forEach(o1 -> objects.stream().forEach(o2 -> { - if (o1 != o2 && o1.intersectsWith(o2)) { - o1.collision(o2); - } - })); - LOGGER.info(""); + LOGGER.info("Collision check"); + objects.forEach( + o1 -> + objects.forEach( + o2 -> { + if (o1 != o2 && o1.intersectsWith(o2)) { + o1.collision(o2); + } + })); // output eventual object statuses - objects.stream().forEach(o -> LOGGER.info(o.toString())); - LOGGER.info(""); + LOGGER.info("Print object status after collision checks"); + objects.forEach(o -> LOGGER.info(o.toString())); } } diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java index 6ca8a8f08f07..98b4c6c7a932 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.doubledispatch; -/** - * - * Flaming asteroid game object - * - */ +/** Flaming asteroid game object. */ public class FlamingAsteroid extends Meteoroid { public FlamingAsteroid(int left, int top, int right, int bottom) { diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java index 42c0c9a5eaf5..85ef3aa85241 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,12 @@ */ package com.iluwatar.doubledispatch; -/** - * - * Game objects have coordinates and some other status information. - * - */ +import lombok.Getter; +import lombok.Setter; + +/** Game objects have coordinates and some other status information. */ +@Getter +@Setter public abstract class GameObject extends Rectangle { private boolean damaged; @@ -38,24 +41,9 @@ public GameObject(int left, int top, int right, int bottom) { @Override public String toString() { - return String.format("%s at %s damaged=%b onFire=%b", this.getClass().getSimpleName(), - super.toString(), isDamaged(), isOnFire()); - } - - public boolean isOnFire() { - return onFire; - } - - public void setOnFire(boolean onFire) { - this.onFire = onFire; - } - - public boolean isDamaged() { - return damaged; - } - - public void setDamaged(boolean damaged) { - this.damaged = damaged; + return String.format( + "%s at %s damaged=%b onFire=%b", + this.getClass().getSimpleName(), super.toString(), isDamaged(), isOnFire()); } public abstract void collision(GameObject gameObject); diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java index 311ffa0e11f8..f2e0587590cb 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,13 @@ */ package com.iluwatar.doubledispatch; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import com.iluwatar.doubledispatch.constants.AppConstants; +import lombok.extern.slf4j.Slf4j; -/** - * - * Meteoroid game object - * - */ +/** Meteoroid game object. */ +@Slf4j public class Meteoroid extends GameObject { - private static final Logger LOGGER = LoggerFactory.getLogger(Meteoroid.class); - public Meteoroid(int left, int top, int right, int bottom) { super(left, top, right, bottom); } @@ -45,21 +42,23 @@ public void collision(GameObject gameObject) { @Override public void collisionResolve(FlamingAsteroid asteroid) { - LOGGER.info("{} hits {}.", asteroid.getClass().getSimpleName(), this.getClass().getSimpleName()); + LOGGER.info( + AppConstants.HITS, asteroid.getClass().getSimpleName(), this.getClass().getSimpleName()); } @Override public void collisionResolve(Meteoroid meteoroid) { - LOGGER.info("{} hits {}.", meteoroid.getClass().getSimpleName(), this.getClass().getSimpleName()); + LOGGER.info( + AppConstants.HITS, meteoroid.getClass().getSimpleName(), this.getClass().getSimpleName()); } @Override public void collisionResolve(SpaceStationMir mir) { - LOGGER.info("{} hits {}.", mir.getClass().getSimpleName(), this.getClass().getSimpleName()); + LOGGER.info(AppConstants.HITS, mir.getClass().getSimpleName(), this.getClass().getSimpleName()); } @Override public void collisionResolve(SpaceStationIss iss) { - LOGGER.info("{} hits {}.", iss.getClass().getSimpleName(), this.getClass().getSimpleName()); + LOGGER.info(AppConstants.HITS, iss.getClass().getSimpleName(), this.getClass().getSimpleName()); } } diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java index 5e668f4baf53..4dfe8f22a7f1 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,47 +24,24 @@ */ package com.iluwatar.doubledispatch; -/** - * - * Rectangle has coordinates and can be checked for overlap against other Rectangles. - * - */ -public class Rectangle { - - private int left; - private int top; - private int right; - private int bottom; - - /** - * Constructor - */ - public Rectangle(int left, int top, int right, int bottom) { - this.left = left; - this.top = top; - this.right = right; - this.bottom = bottom; - } - - public int getLeft() { - return left; - } - - public int getTop() { - return top; - } +import lombok.Getter; +import lombok.RequiredArgsConstructor; - public int getRight() { - return right; - } +/** Rectangle has coordinates and can be checked for overlap against other Rectangles. */ +@Getter +@RequiredArgsConstructor +public class Rectangle { - public int getBottom() { - return bottom; - } + private final int left; + private final int top; + private final int right; + private final int bottom; boolean intersectsWith(Rectangle r) { - return !(r.getLeft() > getRight() || r.getRight() < getLeft() || r.getTop() > getBottom() || r - .getBottom() < getTop()); + return !(r.getLeft() > getRight() + || r.getRight() < getLeft() + || r.getTop() > getBottom() + || r.getBottom() < getTop()); } @Override diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java index 868e8ae813ca..14c44c59602a 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.doubledispatch; -/** - * - * Space station ISS game object - * - */ +/** Space station ISS game object. */ public class SpaceStationIss extends SpaceStationMir { public SpaceStationIss(int left, int top, int right, int bottom) { diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java index 419be2e30c78..045698256a2e 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,13 @@ */ package com.iluwatar.doubledispatch; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import com.iluwatar.doubledispatch.constants.AppConstants; +import lombok.extern.slf4j.Slf4j; -/** - * - * Space station Mir game object - * - */ +/** Space station Mir game object. */ +@Slf4j public class SpaceStationMir extends GameObject { - private static final Logger LOGGER = LoggerFactory.getLogger(SpaceStationMir.class); - public SpaceStationMir(int left, int top, int right, int bottom) { super(left, top, right, bottom); } @@ -45,30 +42,40 @@ public void collision(GameObject gameObject) { @Override public void collisionResolve(FlamingAsteroid asteroid) { - LOGGER.info("{} hits {}. {} is damaged! {} is set on fire!", asteroid.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); + LOGGER.info( + AppConstants.HITS + " {} is damaged! {} is set on fire!", + asteroid.getClass().getSimpleName(), + this.getClass().getSimpleName(), + this.getClass().getSimpleName(), + this.getClass().getSimpleName()); setDamaged(true); setOnFire(true); } @Override public void collisionResolve(Meteoroid meteoroid) { - LOGGER.info("{} hits {}. {} is damaged!", meteoroid.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName()); + logHits(meteoroid); setDamaged(true); } @Override public void collisionResolve(SpaceStationMir mir) { - LOGGER.info("{} hits {}. {} is damaged!", mir.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName()); + logHits(mir); setDamaged(true); } @Override public void collisionResolve(SpaceStationIss iss) { - LOGGER.info("{} hits {}. {} is damaged!", iss.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName()); + logHits(iss); setDamaged(true); } + + private void logHits(GameObject gameObject) { + LOGGER.info( + AppConstants.HITS, + " {} is damaged!", + gameObject.getClass().getSimpleName(), + this.getClass().getSimpleName(), + this.getClass().getSimpleName()); + } } diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java new file mode 100644 index 000000000000..f664092fa944 --- /dev/null +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.doubledispatch.constants; + +/** Constants class to define all constants. */ +public class AppConstants { + + public static final String HITS = "{} hits {}."; +} diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java index ce39b2cce991..1abff6a45c73 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,19 @@ */ package com.iluwatar.doubledispatch; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java index 683fcd5b05f1..7d11fa8502fc 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,15 +24,14 @@ */ package com.iluwatar.doubledispatch; -import java.util.Objects; - import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.Objects; + /** - * Date: 12/10/15 - 8:37 PM - * Test for Collision + * CollisionTest + * * @param Type of GameObject - * @author Jeroen Meulemeester */ public abstract class CollisionTest { @@ -45,20 +46,23 @@ public abstract class CollisionTest { * Collide the tested item with the other given item and verify if the damage and fire state is as * expected * - * @param other The other object we have to collide with + * @param other The other object we have to collide with * @param otherDamaged Indicates if the other object should be damaged after the collision - * @param otherOnFire Indicates if the other object should be burning after the collision - * @param thisDamaged Indicates if the test object should be damaged after the collision - * @param thisOnFire Indicates if the other object should be burning after the collision - * @param description The expected description of the collision + * @param otherOnFire Indicates if the other object should be burning after the collision + * @param thisDamaged Indicates if the test object should be damaged after the collision + * @param thisOnFire Indicates if the other object should be burning after the collision */ - void testCollision(final GameObject other, final boolean otherDamaged, final boolean otherOnFire, - final boolean thisDamaged, final boolean thisOnFire, final String description) { + void testCollision( + final GameObject other, + final boolean otherDamaged, + final boolean otherOnFire, + final boolean thisDamaged, + final boolean thisOnFire) { Objects.requireNonNull(other); Objects.requireNonNull(getTestedObject()); - final O tested = getTestedObject(); + final var tested = getTestedObject(); tested.collision(other); @@ -67,24 +71,33 @@ void testCollision(final GameObject other, final boolean otherDamaged, final boo testOnFire(tested, other, thisOnFire); testDamaged(tested, other, thisDamaged); - } /** * Test if the fire state of the target matches the expected state after colliding with the given * object * - * @param target The target object - * @param other The other object + * @param target The target object + * @param other The other object * @param expectTargetOnFire The expected state of fire on the target object */ - private void testOnFire(final GameObject target, final GameObject other, final boolean expectTargetOnFire) { - final String targetName = target.getClass().getSimpleName(); - final String otherName = other.getClass().getSimpleName(); - - final String errorMessage = expectTargetOnFire - ? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!" - : "Expected [" + targetName + "] not to be on fire after colliding with [" + otherName + "] but it was!"; + private void testOnFire( + final GameObject target, final GameObject other, final boolean expectTargetOnFire) { + final var targetName = target.getClass().getSimpleName(); + final var otherName = other.getClass().getSimpleName(); + + final var errorMessage = + expectTargetOnFire + ? "Expected [" + + targetName + + "] to be on fire after colliding with [" + + otherName + + "] but it was not!" + : "Expected [" + + targetName + + "] not to be on fire after colliding with [" + + otherName + + "] but it was!"; assertEquals(expectTargetOnFire, target.isOnFire(), errorMessage); } @@ -93,19 +106,28 @@ private void testOnFire(final GameObject target, final GameObject other, final b * Test if the damage state of the target matches the expected state after colliding with the * given object * - * @param target The target object - * @param other The other object + * @param target The target object + * @param other The other object * @param expectedDamage The expected state of damage on the target object */ - private void testDamaged(final GameObject target, final GameObject other, final boolean expectedDamage) { - final String targetName = target.getClass().getSimpleName(); - final String otherName = other.getClass().getSimpleName(); - - final String errorMessage = expectedDamage - ? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!" - : "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!"; + private void testDamaged( + final GameObject target, final GameObject other, final boolean expectedDamage) { + final var targetName = target.getClass().getSimpleName(); + final var otherName = other.getClass().getSimpleName(); + + final var errorMessage = + expectedDamage + ? "Expected [" + + targetName + + "] to be damaged after colliding with [" + + otherName + + "] but it was not!" + : "Expected [" + + targetName + + "] not to be damaged after colliding with [" + + otherName + + "] but it was!"; assertEquals(expectedDamage, target.isDamaged(), errorMessage); } - } diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java index 7c5edb5c9711..65cd7cbd16b9 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,30 +24,24 @@ */ package com.iluwatar.doubledispatch; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Date: 12/10/15 - 11:31 PM - * - * @author Jeroen Meulemeester - */ -public class FlamingAsteroidTest extends CollisionTest { +import org.junit.jupiter.api.Test; + +/** FlamingAsteroidTest */ +class FlamingAsteroidTest extends CollisionTest { @Override final FlamingAsteroid getTestedObject() { return new FlamingAsteroid(1, 2, 3, 4); } - /** - * Test the constructor parameters - */ + /** Test the constructor parameters */ @Test - public void testConstructor() { - final FlamingAsteroid asteroid = new FlamingAsteroid(1, 2, 3, 4); + void testConstructor() { + final var asteroid = new FlamingAsteroid(1, 2, 3, 4); assertEquals(1, asteroid.getLeft()); assertEquals(2, asteroid.getTop()); assertEquals(3, asteroid.getRight()); @@ -55,56 +51,27 @@ public void testConstructor() { assertEquals("FlamingAsteroid at [1,2,3,4] damaged=false onFire=true", asteroid.toString()); } - /** - * Test what happens we collide with an asteroid - */ + /** Test what happens we collide with an asteroid */ @Test - public void testCollideFlamingAsteroid() { - testCollision( - new FlamingAsteroid(1, 2, 3, 4), - false, true, - false, true, - "FlamingAsteroid hits FlamingAsteroid." - ); + void testCollideFlamingAsteroid() { + testCollision(new FlamingAsteroid(1, 2, 3, 4), false, true, false, true); } - /** - * Test what happens we collide with an meteoroid - */ + /** Test what happens we collide with an meteoroid */ @Test - public void testCollideMeteoroid() { - testCollision( - new Meteoroid(1, 1, 3, 4), - false, false, - false, true, - "FlamingAsteroid hits Meteoroid." - ); + void testCollideMeteoroid() { + testCollision(new Meteoroid(1, 1, 3, 4), false, false, false, true); } - /** - * Test what happens we collide with ISS - */ + /** Test what happens we collide with ISS */ @Test - public void testCollideSpaceStationIss() { - testCollision( - new SpaceStationIss(1, 1, 3, 4), - true, true, - false, true, - "FlamingAsteroid hits SpaceStationIss. SpaceStationIss is damaged! SpaceStationIss is set on fire!" - ); + void testCollideSpaceStationIss() { + testCollision(new SpaceStationIss(1, 1, 3, 4), true, true, false, true); } - /** - * Test what happens we collide with MIR - */ + /** Test what happens we collide with MIR */ @Test - public void testCollideSpaceStationMir() { - testCollision( - new SpaceStationMir(1, 1, 3, 4), - true, true, - false, true, - "FlamingAsteroid hits SpaceStationMir. SpaceStationMir is damaged! SpaceStationMir is set on fire!" - ); + void testCollideSpaceStationMir() { + testCollision(new SpaceStationMir(1, 1, 3, 4), true, true, false, true); } - -} \ No newline at end of file +} diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java index 40ba0f60d16c..17d529523dfa 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,29 +24,23 @@ */ package com.iluwatar.doubledispatch; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -/** - * Date: 12/10/15 - 11:31 PM - * - * @author Jeroen Meulemeester - */ -public class MeteoroidTest extends CollisionTest { +import org.junit.jupiter.api.Test; + +/** MeteoroidTest */ +class MeteoroidTest extends CollisionTest { @Override final Meteoroid getTestedObject() { return new Meteoroid(1, 2, 3, 4); } - /** - * Test the constructor parameters - */ + /** Test the constructor parameters */ @Test - public void testConstructor() { - final Meteoroid meteoroid = new Meteoroid(1, 2, 3, 4); + void testConstructor() { + final var meteoroid = new Meteoroid(1, 2, 3, 4); assertEquals(1, meteoroid.getLeft()); assertEquals(2, meteoroid.getTop()); assertEquals(3, meteoroid.getRight()); @@ -54,56 +50,27 @@ public void testConstructor() { assertEquals("Meteoroid at [1,2,3,4] damaged=false onFire=false", meteoroid.toString()); } - /** - * Test what happens we collide with an asteroid - */ + /** Test what happens we collide with an asteroid */ @Test - public void testCollideFlamingAsteroid() { - testCollision( - new FlamingAsteroid(1, 1, 3, 4), - false, true, - false, false, - "Meteoroid hits FlamingAsteroid." - ); + void testCollideFlamingAsteroid() { + testCollision(new FlamingAsteroid(1, 1, 3, 4), false, true, false, false); } - /** - * Test what happens we collide with an meteoroid - */ + /** Test what happens we collide with an meteoroid */ @Test - public void testCollideMeteoroid() { - testCollision( - new Meteoroid(1, 1, 3, 4), - false, false, - false, false, - "Meteoroid hits Meteoroid." - ); + void testCollideMeteoroid() { + testCollision(new Meteoroid(1, 1, 3, 4), false, false, false, false); } - /** - * Test what happens we collide with ISS - */ + /** Test what happens we collide with ISS */ @Test - public void testCollideSpaceStationIss() { - testCollision( - new SpaceStationIss(1, 1, 3, 4), - true, false, - false, false, - "Meteoroid hits SpaceStationIss. SpaceStationIss is damaged!" - ); + void testCollideSpaceStationIss() { + testCollision(new SpaceStationIss(1, 1, 3, 4), true, false, false, false); } - /** - * Test what happens we collide with MIR - */ + /** Test what happens we collide with MIR */ @Test - public void testCollideSpaceStationMir() { - testCollision( - new SpaceStationMir(1, 1, 3, 4), - true, false, - false, false, - "Meteoroid hits SpaceStationMir. SpaceStationMir is damaged!" - ); + void testCollideSpaceStationMir() { + testCollision(new SpaceStationMir(1, 1, 3, 4), true, false, false, false); } - -} \ No newline at end of file +} diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java index 8f547c11f860..6b143643a805 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,23 +24,21 @@ */ package com.iluwatar.doubledispatch; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Unit test for Rectangle - */ -public class RectangleTest { +import org.junit.jupiter.api.Test; + +/** Unit test for Rectangle */ +class RectangleTest { /** * Test if the values passed through the constructor matches the values fetched from the getters */ @Test - public void testConstructor() { - final Rectangle rectangle = new Rectangle(1, 2, 3, 4); + void testConstructor() { + final var rectangle = new Rectangle(1, 2, 3, 4); assertEquals(1, rectangle.getLeft()); assertEquals(2, rectangle.getTop()); assertEquals(3, rectangle.getRight()); @@ -46,24 +46,20 @@ public void testConstructor() { } /** - * Test if the values passed through the constructor matches the values in the {@link - * #toString()} + * Test if the values passed through the constructor matches the values in the {@link #toString()} */ @Test - public void testToString() throws Exception { - final Rectangle rectangle = new Rectangle(1, 2, 3, 4); + void testToString() { + final var rectangle = new Rectangle(1, 2, 3, 4); assertEquals("[1,2,3,4]", rectangle.toString()); } - /** - * Test if the {@link Rectangle} class can detect if it intersects with another rectangle. - */ + /** Test if the {@link Rectangle} class can detect if it intersects with another rectangle. */ @Test - public void testIntersection() { + void testIntersection() { assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(0, 0, 1, 1))); assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-1, -5, 7, 8))); assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(2, 2, 3, 3))); assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-2, -2, -1, -1))); } - } diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java index f99f6bdf5ea2..593caf3d64fb 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,29 +24,23 @@ */ package com.iluwatar.doubledispatch; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -/** - * Date: 12/10/15 - 11:31 PM - * - * @author Jeroen Meulemeester - */ -public class SpaceStationIssTest extends CollisionTest { +import org.junit.jupiter.api.Test; + +/** SpaceStationIssTest */ +class SpaceStationIssTest extends CollisionTest { @Override final SpaceStationIss getTestedObject() { return new SpaceStationIss(1, 2, 3, 4); } - /** - * Test the constructor parameters - */ + /** Test the constructor parameters */ @Test - public void testConstructor() { - final SpaceStationIss iss = new SpaceStationIss(1, 2, 3, 4); + void testConstructor() { + final var iss = new SpaceStationIss(1, 2, 3, 4); assertEquals(1, iss.getLeft()); assertEquals(2, iss.getTop()); assertEquals(3, iss.getRight()); @@ -54,56 +50,27 @@ public void testConstructor() { assertEquals("SpaceStationIss at [1,2,3,4] damaged=false onFire=false", iss.toString()); } - /** - * Test what happens we collide with an asteroid - */ + /** Test what happens we collide with an asteroid */ @Test - public void testCollideFlamingAsteroid() { - testCollision( - new FlamingAsteroid(1, 1, 3, 4), - false, true, - false, false, - "SpaceStationIss hits FlamingAsteroid." - ); + void testCollideFlamingAsteroid() { + testCollision(new FlamingAsteroid(1, 1, 3, 4), false, true, false, false); } - /** - * Test what happens we collide with an meteoroid - */ + /** Test what happens we collide with an meteoroid */ @Test - public void testCollideMeteoroid() { - testCollision( - new Meteoroid(1, 1, 3, 4), - false, false, - false, false, - "SpaceStationIss hits Meteoroid." - ); + void testCollideMeteoroid() { + testCollision(new Meteoroid(1, 1, 3, 4), false, false, false, false); } - /** - * Test what happens we collide with ISS - */ + /** Test what happens we collide with ISS */ @Test - public void testCollideSpaceStationIss() { - testCollision( - new SpaceStationIss(1, 1, 3, 4), - true, false, - false, false, - "SpaceStationIss hits SpaceStationIss. SpaceStationIss is damaged!" - ); + void testCollideSpaceStationIss() { + testCollision(new SpaceStationIss(1, 1, 3, 4), true, false, false, false); } - /** - * Test what happens we collide with MIR - */ + /** Test what happens we collide with MIR */ @Test - public void testCollideSpaceStationMir() { - testCollision( - new SpaceStationMir(1, 1, 3, 4), - true, false, - false, false, - "SpaceStationIss hits SpaceStationMir. SpaceStationMir is damaged!" - ); + void testCollideSpaceStationMir() { + testCollision(new SpaceStationMir(1, 1, 3, 4), true, false, false, false); } - -} \ No newline at end of file +} diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java index f0cbd3668506..155595253ebc 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,29 +24,23 @@ */ package com.iluwatar.doubledispatch; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -/** - * Date: 12/10/15 - 11:31 PM - * - * @author Jeroen Meulemeester - */ -public class SpaceStationMirTest extends CollisionTest { +import org.junit.jupiter.api.Test; + +/** SpaceStationMirTest */ +class SpaceStationMirTest extends CollisionTest { @Override final SpaceStationMir getTestedObject() { return new SpaceStationMir(1, 2, 3, 4); } - /** - * Test the constructor parameters - */ + /** Test the constructor parameters */ @Test - public void testConstructor() { - final SpaceStationMir mir = new SpaceStationMir(1, 2, 3, 4); + void testConstructor() { + final var mir = new SpaceStationMir(1, 2, 3, 4); assertEquals(1, mir.getLeft()); assertEquals(2, mir.getTop()); assertEquals(3, mir.getRight()); @@ -54,56 +50,27 @@ public void testConstructor() { assertEquals("SpaceStationMir at [1,2,3,4] damaged=false onFire=false", mir.toString()); } - /** - * Test what happens we collide with an asteroid - */ + /** Test what happens we collide with an asteroid */ @Test - public void testCollideFlamingAsteroid() { - testCollision( - new FlamingAsteroid(1, 1, 3, 4), - false, true, - false, false, - "SpaceStationMir hits FlamingAsteroid." - ); + void testCollideFlamingAsteroid() { + testCollision(new FlamingAsteroid(1, 1, 3, 4), false, true, false, false); } - /** - * Test what happens we collide with an meteoroid - */ + /** Test what happens we collide with an meteoroid */ @Test - public void testCollideMeteoroid() { - testCollision( - new Meteoroid(1, 1, 3, 4), - false, false, - false, false, - "SpaceStationMir hits Meteoroid." - ); + void testCollideMeteoroid() { + testCollision(new Meteoroid(1, 1, 3, 4), false, false, false, false); } - /** - * Test what happens we collide with ISS - */ + /** Test what happens we collide with ISS */ @Test - public void testCollideSpaceStationIss() { - testCollision( - new SpaceStationIss(1, 1, 3, 4), - true, false, - false, false, - "SpaceStationMir hits SpaceStationIss. SpaceStationIss is damaged!" - ); + void testCollideSpaceStationIss() { + testCollision(new SpaceStationIss(1, 1, 3, 4), true, false, false, false); } - /** - * Test what happens we collide with MIR - */ + /** Test what happens we collide with MIR */ @Test - public void testCollideSpaceStationMir() { - testCollision( - new SpaceStationMir(1, 1, 3, 4), - true, false, - false, false, - "SpaceStationMir hits SpaceStationMir. SpaceStationMir is damaged!" - ); + void testCollideSpaceStationMir() { + testCollision(new SpaceStationMir(1, 1, 3, 4), true, false, false, false); } - -} \ No newline at end of file +} diff --git a/dynamic-proxy/README.md b/dynamic-proxy/README.md new file mode 100644 index 000000000000..ec0821260b1c --- /dev/null +++ b/dynamic-proxy/README.md @@ -0,0 +1,345 @@ +--- +title: "Dynamic Proxy Pattern in Java: Facilitating Seamless Object Interception" +shortTitle: Dynamic Proxy +description: "Explore the Dynamic Proxy Pattern in Java, a flexible runtime mechanism for creating proxies that enhance functionality and control access to objects. Learn through real-world examples and detailed explanations." +category: Structural +language: en +tag: + - Decoupling + - Dynamic typing + - Enhancement + - Extensibility + - Proxy + - Runtime +--- + +## Also known as + +* Runtime Proxy + +## Intent of Dynamic Proxy Design Pattern + +To provide a flexible proxy mechanism capable of dynamically creating proxies for various interfaces at runtime, allowing for controlled access or functionality enhancement of objects. + +## Detailed Explanation of Dynamic Proxy Pattern with Real-World Examples + +Real-world example + +> Mockito, a popular Java mocking framework, employs dynamic proxy to create mock objects for testing. Mock objects mimic the behavior of real objects, allowing developers to isolate components and verify interactions in unit tests. Consider a scenario where a service class depends on an external component, such as a database access object (DAO). Instead of interacting with a real DAO in a test, Mockito can dynamically generate a proxy, intercepting method invocations and returning predefined values. This enables focused unit testing without the need for a real database connection. + +In plain words + +> The Dynamic Proxy Pattern in Java is a specialized form of proxy, serving as a flexible and dynamic method to intercept and manipulate method calls. By utilizing dynamic proxies, developers can implement additional functionalities without modifying the original class code. This is particularly useful in scenarios requiring enhancement of existing functionalities. + +Wikipedia says + +> A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools. Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a _java.lang.reflect.Method_ object identifying the method that was invoked and an array of type _Object_ containing the arguments. + +Sequence diagram + +![Dynamic Proxy sequence diagram](./etc/dynamic-proxy-sequence-diagram.png) + +## Programmatic Example of Dynamic Proxy Pattern in Java + +This example demonstrates using the Dynamic Proxy pattern in Java to hit the public fake API [JSONPlaceholder](https://jsonplaceholder.typicode.com) for the resource `Album` through an interface. + +In this demo, the Dynamic Proxy pattern helps us run business logic through an interface without explicitly implementing that interface, leveraging Java Reflection. + +The `App` class sets up the dynamic proxy for the `AlbumService` interface and demonstrates how to use the proxy to make API calls. + +```java +@Slf4j +public class App { + + static final String REST_API_URL = "https://jsonplaceholder.typicode.com"; + private AlbumService albumServiceProxy; + + public static void main(String[] args) { + App app = new App(); + app.createDynamicProxy(); + app.callMethods(); + } + + public void createDynamicProxy() { + AlbumInvocationHandler handler = new AlbumInvocationHandler(REST_API_URL, HttpClient.newHttpClient()); + albumServiceProxy = (AlbumService) Proxy.newProxyInstance( + App.class.getClassLoader(), new Class[]{AlbumService.class}, handler); + } + + public void callMethods() { + var albums = albumServiceProxy.readAlbums(); + albums.forEach(album -> LOGGER.info("{}", album)); + + var album = albumServiceProxy.readAlbum(17); + LOGGER.info("{}", album); + + var newAlbum = albumServiceProxy.createAlbum(Album.builder().title("Big World").userId(3).build()); + LOGGER.info("{}", newAlbum); + + var editAlbum = albumServiceProxy.updateAlbum(17, Album.builder().title("Green Valley").userId(3).build()); + LOGGER.info("{}", editAlbum); + + var removedAlbum = albumServiceProxy.deleteAlbum(17); + LOGGER.info("{}", removedAlbum); + } +} +``` + +* The `createDynamicProxy` method uses `Proxy.newProxyInstance` to create a new dynamic proxy for the `AlbumService` interface. +* The `callMethods` method demonstrates using the dynamic proxy to make various API calls. + +The `AlbumService` interface defines the API operations that can be dynamically proxied. It uses custom annotations to specify HTTP methods and paths. + +```java +public interface AlbumService { + @Get("/albums") + List readAlbums(); + + @Get("/albums/{albumId}") + Album readAlbum(@Path("albumId") Integer albumId); + + @Post("/albums") + Album createAlbum(@Body Album album); + + @Put("/albums/{albumId}") + Album updateAlbum(@Path("albumId") Integer albumId, @Body Album album); + + @Delete("/albums/{albumId}") + Album deleteAlbum(@Path("albumId") Integer albumId); +} +``` + +* Annotations like `@Get` and `@Post` indicate the HTTP method and the path for each method. +* These annotations are used by the `TinyRestClient` to construct appropriate HTTP requests. + +The `AlbumInvocationHandler` class is where method calls on the proxy are intercepted and delegated to the `TinyRestClient`. + +```java +@Slf4j +public class AlbumInvocationHandler implements InvocationHandler { + + private TinyRestClient restClient; + + public AlbumInvocationHandler(String baseUrl, HttpClient httpClient) { + this.restClient = new TinyRestClient(baseUrl, httpClient); + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + LOGGER.info("===== Calling the method {}.{}()", + method.getDeclaringClass().getSimpleName(), method.getName()); + return restClient.send(method, args); + } +} +``` + +* Implements `InvocationHandler`, which requires defining the `invoke` method. +* The `invoke` method is called every time a method on the proxy is invoked. It delegates the call to the `TinyRestClient`, passing along the method and its arguments. + +The `TinyRestClient` handles the construction and sending of HTTP requests based on the annotations and method details. + +```java +@Slf4j +public class TinyRestClient { + private String baseUrl; + private HttpClient httpClient; + + public TinyRestClient(String baseUrl, HttpClient httpClient) { + this.baseUrl = baseUrl; + this.httpClient = httpClient; + } + + public Object send(Method method, Object[] args) throws IOException, InterruptedException { + var url = baseUrl + buildUrl(method, args); + var httpRequest = HttpRequest.newBuilder().uri(URI.create(url)).build(); + var httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); + return getResponse(method, httpResponse); + } + + private String buildUrl(Method method, Object[] args) { + // Simplified URL building logic + return "/albums"; + } + + private Object getResponse(Method method, HttpResponse httpResponse) { + // Simplified response handling logic + return httpResponse.body(); + } +} +``` + +* This class uses Java's `HttpClient` to send HTTP requests. +* The `send` method constructs a `HttpRequest` using details from the method's annotations, although simplified here to focus on the dynamic proxy mechanism. +* The response is returned as a simple string, demonstrating basic interaction with an API. + +Running the example produces the following console output showcasing the API calls and responses. See the `App` class and `main` method above. + +``` +16:05:41.964 [main] INFO com.iluwatar.dynamicproxy.AlbumInvocationHandler -- ===== Calling the method AlbumService.readAlbums() +16:05:42.409 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=1, title=quidem molestiae enim, userId=1) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=2, title=sunt qui excepturi placeat culpa, userId=1) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=3, title=omnis laborum odio, userId=1) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=4, title=non esse culpa molestiae omnis sed optio, userId=1) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=5, title=eaque aut omnis a, userId=1) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=6, title=natus impedit quibusdam illo est, userId=1) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=7, title=quibusdam autem aliquid et et quia, userId=1) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=8, title=qui fuga est a eum, userId=1) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=9, title=saepe unde necessitatibus rem, userId=1) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=10, title=distinctio laborum qui, userId=1) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=11, title=quam nostrum impedit mollitia quod et dolor, userId=2) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=12, title=consequatur autem doloribus natus consectetur, userId=2) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=13, title=ab rerum non rerum consequatur ut ea unde, userId=2) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=14, title=ducimus molestias eos animi atque nihil, userId=2) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=15, title=ut pariatur rerum ipsum natus repellendus praesentium, userId=2) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=16, title=voluptatem aut maxime inventore autem magnam atque repellat, userId=2) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=17, title=aut minima voluptatem ut velit, userId=2) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=18, title=nesciunt quia et doloremque, userId=2) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=19, title=velit pariatur quaerat similique libero omnis quia, userId=2) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=20, title=voluptas rerum iure ut enim, userId=2) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=21, title=repudiandae voluptatem optio est consequatur rem in temporibus et, userId=3) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=22, title=et rem non provident vel ut, userId=3) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=23, title=incidunt quisquam hic adipisci sequi, userId=3) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=24, title=dolores ut et facere placeat, userId=3) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=25, title=vero maxime id possimus sunt neque et consequatur, userId=3) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=26, title=quibusdam saepe ipsa vel harum, userId=3) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=27, title=id non nostrum expedita, userId=3) +16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=28, title=omnis neque exercitationem sed dolor atque maxime aut cum, userId=3) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=29, title=inventore ut quasi magnam itaque est fugit, userId=3) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=30, title=tempora assumenda et similique odit distinctio error, userId=3) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=31, title=adipisci laborum fuga laboriosam, userId=4) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=32, title=reiciendis dolores a ut qui debitis non quo labore, userId=4) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=33, title=iste eos nostrum, userId=4) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=34, title=cumque voluptatibus rerum architecto blanditiis, userId=4) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=35, title=et impedit nisi quae magni necessitatibus sed aut pariatur, userId=4) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=36, title=nihil cupiditate voluptate neque, userId=4) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=37, title=est placeat dicta ut nisi rerum iste, userId=4) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=38, title=unde a sequi id, userId=4) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=39, title=ratione porro illum labore eum aperiam sed, userId=4) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=40, title=voluptas neque et sint aut quo odit, userId=4) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=41, title=ea voluptates maiores eos accusantium officiis tempore mollitia consequatur, userId=5) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=42, title=tenetur explicabo ea, userId=5) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=43, title=aperiam doloremque nihil, userId=5) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=44, title=sapiente cum numquam officia consequatur vel natus quos suscipit, userId=5) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=45, title=tenetur quos ea unde est enim corrupti qui, userId=5) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=46, title=molestiae voluptate non, userId=5) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=47, title=temporibus molestiae aut, userId=5) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=48, title=modi consequatur culpa aut quam soluta alias perspiciatis laudantium, userId=5) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=49, title=ut aut vero repudiandae voluptas ullam voluptas at consequatur, userId=5) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=50, title=sed qui sed quas sit ducimus dolor, userId=5) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=51, title=odit laboriosam sint quia cupiditate animi quis, userId=6) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=52, title=necessitatibus quas et sunt at voluptatem, userId=6) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=53, title=est vel sequi voluptatem nemo quam molestiae modi enim, userId=6) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=54, title=aut non illo amet perferendis, userId=6) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=55, title=qui culpa itaque omnis in nesciunt architecto error, userId=6) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=56, title=omnis qui maiores tempora officiis omnis rerum sed repellat, userId=6) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=57, title=libero excepturi voluptatem est architecto quae voluptatum officia tempora, userId=6) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=58, title=nulla illo consequatur aspernatur veritatis aut error delectus et, userId=6) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=59, title=eligendi similique provident nihil, userId=6) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=60, title=omnis mollitia sunt aliquid eum consequatur fugit minus laudantium, userId=6) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=61, title=delectus iusto et, userId=7) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=62, title=eos ea non recusandae iste ut quasi, userId=7) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=63, title=velit est quam, userId=7) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=64, title=autem voluptatem amet iure quae, userId=7) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=65, title=voluptates delectus iure iste qui, userId=7) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=66, title=velit sed quia dolor dolores delectus, userId=7) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=67, title=ad voluptas nostrum et nihil, userId=7) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=68, title=qui quasi nihil aut voluptatum sit dolore minima, userId=7) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=69, title=qui aut est, userId=7) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=70, title=et deleniti unde, userId=7) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=71, title=et vel corporis, userId=8) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=72, title=unde exercitationem ut, userId=8) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=73, title=quos omnis officia, userId=8) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=74, title=quia est eius vitae dolor, userId=8) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=75, title=aut quia expedita non, userId=8) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=76, title=dolorem magnam facere itaque ut reprehenderit tenetur corrupti, userId=8) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=77, title=cupiditate sapiente maiores iusto ducimus cum excepturi veritatis quia, userId=8) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=78, title=est minima eius possimus ea ratione velit et, userId=8) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=79, title=ipsa quae voluptas natus ut suscipit soluta quia quidem, userId=8) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=80, title=id nihil reprehenderit, userId=8) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=81, title=quibusdam sapiente et, userId=9) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=82, title=recusandae consequatur vel amet unde, userId=9) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=83, title=aperiam odio fugiat, userId=9) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=84, title=est et at eos expedita, userId=9) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=85, title=qui voluptatem consequatur aut ab quis temporibus praesentium, userId=9) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=86, title=eligendi mollitia alias aspernatur vel ut iusto, userId=9) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=87, title=aut aut architecto, userId=9) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=88, title=quas perspiciatis optio, userId=9) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=89, title=sit optio id voluptatem est eum et, userId=9) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=90, title=est vel dignissimos, userId=9) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=91, title=repellendus praesentium debitis officiis, userId=10) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=92, title=incidunt et et eligendi assumenda soluta quia recusandae, userId=10) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=93, title=nisi qui dolores perspiciatis, userId=10) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=94, title=quisquam a dolores et earum vitae, userId=10) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=95, title=consectetur vel rerum qui aperiam modi eos aspernatur ipsa, userId=10) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=96, title=unde et ut molestiae est molestias voluptatem sint, userId=10) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=97, title=est quod aut, userId=10) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=98, title=omnis quia possimus nesciunt deleniti assumenda sed autem, userId=10) +16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=99, title=consectetur ut id impedit dolores sit ad ex aut, userId=10) +16:05:42.412 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=100, title=enim repellat iste, userId=10) +16:05:42.412 [main] INFO com.iluwatar.dynamicproxy.AlbumInvocationHandler -- ===== Calling the method AlbumService.readAlbum() +16:05:42.741 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=17, title=aut minima voluptatem ut velit, userId=2) +16:05:42.741 [main] INFO com.iluwatar.dynamicproxy.AlbumInvocationHandler -- ===== Calling the method AlbumService.createAlbum() +16:05:43.073 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=101, title=Big World, userId=3) +16:05:43.073 [main] INFO com.iluwatar.dynamicproxy.AlbumInvocationHandler -- ===== Calling the method AlbumService.updateAlbum() +16:05:43.220 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=17, title=Green Valley, userId=3) +16:05:43.220 [main] INFO com.iluwatar.dynamicproxy.AlbumInvocationHandler -- ===== Calling the method AlbumService.deleteAlbum() +16:05:43.357 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=null, title=null, userId=null) +``` + +## When to Use the Dynamic Proxy Pattern in Java + +Dynamic proxy should be used when you need to augment or enhance your current functionality without modifying your current code. Some examples of that usage could be: + +* You want to intercept calls to methods of an object at runtime for handling purposes such as logging, transaction management, or security checks. +* You need to create a proxy object for one or more interfaces dynamically at runtime without coding it explicitly for each interface. +* You aim to simplify complex systems by decoupling the client and the real object through a flexible proxy mechanism. + +## Dynamic Proxy Pattern Java Tutorials + +* [Dynamic Proxies in Java (CodeGym)](https://codegym.cc/groups/posts/208-dynamic-proxies) +* [Introduction To Java Dynamic Proxy (Xperti)](https://xperti.io/blogs/java-dynamic-proxies-introduction/) +* [Dynamic Proxies in Java (Baeldung)](https://www.baeldung.com/java-dynamic-proxies) +* [Intro To Java Dynamic Proxies (KapreSoft)](https://www.kapresoft.com/java/2023/12/27/intro-to-java-proxies.html) +* [Exploring the Depths of Dynamic Proxy in Java: A Comprehensive Guide (Medium)](https://naveen-metta.medium.com/exploring-the-depths-of-dynamic-proxy-in-java-a-comprehensive-guide-f34fb45b38a3) + +## Real-World Applications of Dynamic Proxy Pattern in Java + +Many frameworks and libraries use dynamic proxy to implement their functionalities: + +* Java's `java.lang.reflect.Proxy` class is a built-in dynamic proxy mechanism. +* [Spring Framework](https://docs.spring.io/spring-framework/reference/core/aop.html), for aspect oriented programming. +* [Hibernate](https://hibernate.org/orm/), for data lazy loading. +* [Mockito](https://site.mockito.org/), for mocking objects in testing. +* [Cleverclient](https://github.com/sashirestela/cleverclient), for calling http endpoints through annotated interfaces. +* Java Reflection API: Java's built-in support for dynamic proxies with the use of java.lang.reflect.Proxy and java.lang.reflect.InvocationHandler. +* Frameworks: Extensively used in Java frameworks like Spring for AOP (Aspect-Oriented Programming) to handle transactions, security, logging, etc. +* Middleware: In middleware services for transparently adding services like load balancing and access control. + +## Benefits and Trade-offs of Dynamic Proxy Pattern + +Benefits: + +* Increased flexibility in code: Dynamic proxies in Java offer a high degree of flexibility, allowing developers to create versatile and adaptable applications. By using dynamic proxies, software engineers can modify the behavior of methods at runtime, which is particularly useful in scenarios where the behavior of classes needs to be augmented or manipulated without altering their source code. This flexibility is crucial in developing applications that require dynamic response to varying conditions or need to integrate with systems where interfaces may change over time. +* Simplifying complex operations: Dynamic proxies excel in simplifying complex operations, particularly in the areas of cross-cutting concerns such as logging, transaction management, and security. By intercepting method calls, dynamic proxies can uniformly apply certain operations across various methods and classes, thereby reducing the need for repetitive code. This capability is particularly beneficial in large-scale applications where such cross-cutting concerns are prevalent. For example, adding logging or authorization checks across multiple methods becomes a matter of implementing these features once in an invocation handler, rather than modifying each method individually. +* Enhancing code maintainability: Maintainability is a key advantage of using dynamic proxies. They promote cleaner and more organized code by separating the core business logic from cross-cutting concerns. This separation of concerns not only makes the codebase more understandable but also easier to test and debug. When the business logic is decoupled from aspects like logging or transaction handling, any changes in these areas do not impact the core functionality of the application. As a result, applications become more robust and easier to maintain and update, which is crucial in the fast-paced environment of software development where requirements and technologies are constantly evolving. +* Separation of Concerns: Promotes separation of concerns by decoupling the client code from the actual handling of method calls. + +Trade-offs: + +* Performance overhead: The use of reflection and method invocation through proxies can introduce latency, especially in performance-critical applications. This overhead might be negligible in most cases, but it becomes significant in scenarios with high-frequency method calls. +* Complexity of debugging: Since dynamic proxies introduce an additional layer of abstraction, tracing and debugging issues can be more challenging. It can be difficult to trace the flow of execution through proxies, especially when multiple proxies are involved. +* Limited to interface-based programming: They can only proxy interfaces, not classes. This limitation requires careful design considerations, particularly in situations where class-based proxies would be more appropriate. +* Higher level of expertise: Developers are normally not a fan of “magic code” — code that works in a non-transparent or overly complex manner. Those unfamiliar with the proxy pattern or reflection might find the codebase more complex to understand and maintain, potentially leading to errors or misuse of the feature. This complexity can be perceived as a form of “magic” that obscures the underlying process, making the code less intuitive and more challenging to debug or extend. Therefore, while dynamic proxies are powerful, their use should be approached with caution and a thorough understanding of their inner workings. + +## Related Java Design Patterns + +* [Proxy](https://java-design-patterns.com/patterns/proxy): Static counterpart of the Dynamic Proxy, where proxies are explicitly coded. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar in structure by providing additional functionality, but without the dynamic proxy's capability to handle any interface. +* [Facade](https://java-design-patterns.com/patterns/facade/): Simplifies the interface to complex systems, not through dynamic proxies but through a single simplified interface. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3U0d8Gm) +* [Java Reflection in Action](https://amzn.to/3TVpe3t) +* [Pro Spring 6: An In-Depth Guide to the Spring Framework](https://amzn.to/43Zs2Bx) +* [Dynamic Proxy Classes - Oracle](https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html) diff --git a/dynamic-proxy/etc/dynamic-proxy-sequence-diagram.png b/dynamic-proxy/etc/dynamic-proxy-sequence-diagram.png new file mode 100644 index 000000000000..cdffa1b36d62 Binary files /dev/null and b/dynamic-proxy/etc/dynamic-proxy-sequence-diagram.png differ diff --git a/dynamic-proxy/etc/dynamic-proxy.urm.png b/dynamic-proxy/etc/dynamic-proxy.urm.png new file mode 100644 index 000000000000..6178af2fbd20 Binary files /dev/null and b/dynamic-proxy/etc/dynamic-proxy.urm.png differ diff --git a/dynamic-proxy/etc/dynamic-proxy.urm.puml b/dynamic-proxy/etc/dynamic-proxy.urm.puml new file mode 100644 index 000000000000..5db603aae1d4 --- /dev/null +++ b/dynamic-proxy/etc/dynamic-proxy.urm.puml @@ -0,0 +1,96 @@ +@startuml +package com.iluwatar.dynamicproxy.tinyrestclient.annotation { + interface Body { + } + interface Delete { + + value() : String {abstract} + } + interface Get { + + value() : String {abstract} + } + interface HttpMethod { + } + interface Path { + + value() : String {abstract} + } + interface Post { + + value() : String {abstract} + } + interface Put { + + value() : String {abstract} + } +} +package com.iluwatar.dynamicproxy.tinyrestclient { + class JsonUtil { + - objectMapper : ObjectMapper {static} + - JsonUtil() + + jsonToList(json : String, clazz : Class) : List {static} + + jsonToObject(json : String, clazz : Class) : T {static} + + objectToJson(object : T) : String {static} + } + class TinyRestClient { + - baseUrl : String + + TinyRestClient(baseUrl : String) + - annotationValue(annotation : Annotation) : String + - buildBodyPublisher(method : Method, args : Object[]) : BodyPublisher + - buildUrl(method : Method, args : Object[], httpMethodAnnotation : Annotation) : String + - getAnnotationOf(annotations : Annotation[], clazz : Class) : Annotation + - getHttpMethodAnnotation(annotations : Annotation[]) : Annotation + - getResponse(method : Method, httpResponse : HttpResponse) : Object + + send(method : Method, args : Object[]) : Object + } +} +package com.iluwatar.dynamicproxy { + class Album { + - id : Integer + - title : String + - userId : Integer + + Album() + + Album(id : Integer, title : String, userId : Integer) + + builder() : AlbumBuilder {static} + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getId() : Integer + + getTitle() : String + + getUserId() : Integer + + hashCode() : int + + setId(id : Integer) + + setTitle(title : String) + + setUserId(userId : Integer) + + toString() : String + } + class AlbumBuilder { + - id : Integer + - title : String + - userId : Integer + ~ AlbumBuilder() + + build() : Album + + id(id : Integer) : AlbumBuilder + + title(title : String) : AlbumBuilder + + toString() : String + + userId(userId : Integer) : AlbumBuilder + } + class AlbumInvocationHandler { + - restClient : TinyRestClient + + AlbumInvocationHandler(baseUrl : String) + + invoke(proxy : Object, method : Method, args : Object[]) : Object + } + interface AlbumService { + + createAlbum(Album) : Album {abstract} + + deleteAlbum(Integer) : Album {abstract} + + readAlbum(Integer) : Album {abstract} + + readAlbums() : List {abstract} + + updateAlbum(Integer, Album) : Album {abstract} + } + class App { + ~ REST_API_URL : String {static} + - albumServiceProxy : AlbumService + + App() + + callMethods() + + createDynamicProxy() + + main(args : String[]) {static} + } +} +AlbumInvocationHandler --> "-restClient" TinyRestClient +App --> "-albumServiceProxy" AlbumService +@enduml \ No newline at end of file diff --git a/dynamic-proxy/pom.xml b/dynamic-proxy/pom.xml new file mode 100644 index 000000000000..decbb24fd02d --- /dev/null +++ b/dynamic-proxy/pom.xml @@ -0,0 +1,86 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + dynamic-proxy + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + com.fasterxml.jackson.core + jackson-core + 2.19.0 + + + com.fasterxml.jackson.core + jackson-databind + 2.18.3 + + + org.springframework + spring-web + 7.0.0-M4 + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.dynamicproxy.App + + + + + + + + + diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/Album.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/Album.java new file mode 100644 index 000000000000..c61223008e19 --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/Album.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * This class represents an endpoint resource that we are going to interchange with a Rest API + * server. + */ +@Data +@AllArgsConstructor +@NoArgsConstructor(force = true) +@Builder +public class Album { + + private Integer id; + private String title; + private Integer userId; +} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumInvocationHandler.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumInvocationHandler.java new file mode 100644 index 000000000000..84a0b22d041f --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumInvocationHandler.java @@ -0,0 +1,62 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy; + +import com.iluwatar.dynamicproxy.tinyrestclient.TinyRestClient; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.net.http.HttpClient; +import lombok.extern.slf4j.Slf4j; + +/** + * Class whose method 'invoke' will be called every time that an interface's method is called. That + * interface is linked to this class by the Proxy class. + */ +@Slf4j +public class AlbumInvocationHandler implements InvocationHandler { + + private TinyRestClient restClient; + + /** + * Class constructor. It instantiates a TinyRestClient object. + * + * @param baseUrl Root url for endpoints. + * @param httpClient Handle the http communication. + */ + public AlbumInvocationHandler(String baseUrl, HttpClient httpClient) { + this.restClient = new TinyRestClient(baseUrl, httpClient); + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + + LOGGER.info( + "===== Calling the method {}.{}()", + method.getDeclaringClass().getSimpleName(), + method.getName()); + + return restClient.send(method, args); + } +} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumService.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumService.java new file mode 100644 index 000000000000..8b4c0d02d692 --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumService.java @@ -0,0 +1,86 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy; + +import com.iluwatar.dynamicproxy.tinyrestclient.annotation.Body; +import com.iluwatar.dynamicproxy.tinyrestclient.annotation.Delete; +import com.iluwatar.dynamicproxy.tinyrestclient.annotation.Get; +import com.iluwatar.dynamicproxy.tinyrestclient.annotation.Path; +import com.iluwatar.dynamicproxy.tinyrestclient.annotation.Post; +import com.iluwatar.dynamicproxy.tinyrestclient.annotation.Put; +import java.util.List; + +/** + * Every method in this interface is annotated with the necessary metadata to represents an endpoint + * that we can call to communicate with a host server which is serving a resource by Rest API. This + * interface is focused in the resource Album. + */ +public interface AlbumService { + + /** + * Get a list of albums from an endpoint. + * + * @return List of albums' data. + */ + @Get("/albums") + List readAlbums(); + + /** + * Get a specific album from an endpoint. + * + * @param albumId Album's id to search for. + * @return Album's data. + */ + @Get("/albums/{albumId}") + Album readAlbum(@Path("albumId") Integer albumId); + + /** + * Creates a new album. + * + * @param album Album's data to be created. + * @return New album's data. + */ + @Post("/albums") + Album createAlbum(@Body Album album); + + /** + * Updates an existing album. + * + * @param albumId Album's id to be modified. + * @param album New album's data. + * @return Updated album's data. + */ + @Put("/albums/{albumId}") + Album updateAlbum(@Path("albumId") Integer albumId, @Body Album album); + + /** + * Deletes an album. + * + * @param albumId Album's id to be deleted. + * @return Empty album. + */ + @Delete("/albums/{albumId}") + Album deleteAlbum(@Path("albumId") Integer albumId); +} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/App.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/App.java new file mode 100644 index 000000000000..d5a19184bf91 --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/App.java @@ -0,0 +1,114 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy; + +import java.lang.reflect.Proxy; +import java.net.http.HttpClient; +import lombok.extern.slf4j.Slf4j; + +/** + * Application to demonstrate the Dynamic Proxy pattern. This application allow us to hit the public + * fake API https://jsonplaceholder.typicode.com for the resource Album through an interface. The + * call to Proxy.newProxyInstance creates a new dynamic proxy for the AlbumService interface and + * sets the AlbumInvocationHandler class as the handler to intercept all the interface's methods. + * Everytime that we call an AlbumService's method, the handler's method "invoke" will be call + * automatically, and it will pass all the method's metadata and arguments to other specialized + * class - TinyRestClient - to prepare the Rest API call accordingly. In this demo, the Dynamic + * Proxy pattern help us to run business logic through interfaces without an explicit implementation + * of the interfaces and supported on the Java Reflection approach. + */ +@Slf4j +public class App { + + static final String REST_API_URL = "https://jsonplaceholder.typicode.com"; + + private String baseUrl; + private HttpClient httpClient; + private AlbumService albumServiceProxy; + + /** + * Class constructor. + * + * @param baseUrl Root url for endpoints. + * @param httpClient Handle the http communication. + */ + public App(String baseUrl, HttpClient httpClient) { + this.baseUrl = baseUrl; + this.httpClient = httpClient; + } + + /** + * Application entry point. + * + * @param args External arguments to be passed. Optional. + */ + public static void main(String[] args) { + App app = new App(App.REST_API_URL, HttpClient.newHttpClient()); + app.createDynamicProxy(); + app.callMethods(); + } + + /** + * Create the Dynamic Proxy linked to the AlbumService interface and to the + * AlbumInvocationHandler. + */ + public void createDynamicProxy() { + AlbumInvocationHandler albumInvocationHandler = new AlbumInvocationHandler(baseUrl, httpClient); + + albumServiceProxy = + (AlbumService) + Proxy.newProxyInstance( + App.class.getClassLoader(), + new Class[] {AlbumService.class}, + albumInvocationHandler); + } + + /** + * Call the methods of the Dynamic Proxy, in other words, the AlbumService interface's methods and + * receive the responses from the Rest API. + */ + public void callMethods() { + int albumId = 17; + int userId = 3; + + var albums = albumServiceProxy.readAlbums(); + albums.forEach(album -> LOGGER.info("{}", album)); + + var album = albumServiceProxy.readAlbum(albumId); + LOGGER.info("{}", album); + + var newAlbum = + albumServiceProxy.createAlbum(Album.builder().title("Big World").userId(userId).build()); + LOGGER.info("{}", newAlbum); + + var editAlbum = + albumServiceProxy.updateAlbum( + albumId, Album.builder().title("Green Valley").userId(userId).build()); + LOGGER.info("{}", editAlbum); + + var removedAlbum = albumServiceProxy.deleteAlbum(albumId); + LOGGER.info("{}", removedAlbum); + } +} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/JsonUtil.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/JsonUtil.java new file mode 100644 index 000000000000..d474c59da20f --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/JsonUtil.java @@ -0,0 +1,94 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy.tinyrestclient; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.CollectionType; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import lombok.extern.slf4j.Slf4j; + +/** Utility class to handle Json operations. */ +@Slf4j +public class JsonUtil { + + private static ObjectMapper objectMapper = new ObjectMapper(); + + private JsonUtil() {} + + /** + * Convert an object to a Json string representation. + * + * @param object Object to convert. + * @param Object's class. + * @return Json string. + */ + public static String objectToJson(T object) { + try { + return objectMapper.writeValueAsString(object); + } catch (JsonProcessingException e) { + LOGGER.error("Cannot convert the object " + object + " to Json.", e); + return null; + } + } + + /** + * Convert a Json string to an object of a class. + * + * @param json Json string to convert. + * @param clazz Object's class. + * @param Object's generic class. + * @return Object. + */ + public static T jsonToObject(String json, Class clazz) { + try { + return objectMapper.readValue(json, clazz); + } catch (IOException e) { + LOGGER.error("Cannot convert the Json " + json + " to class " + clazz.getName() + ".", e); + return null; + } + } + + /** + * Convert a Json string to a List of objects of a class. + * + * @param json Json string to convert. + * @param clazz Object's class. + * @param Object's generic class. + * @return List of objects. + */ + public static List jsonToList(String json, Class clazz) { + try { + CollectionType listType = + objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz); + return objectMapper.reader().forType(listType).readValue(json); + } catch (JsonProcessingException e) { + LOGGER.error("Cannot convert the Json " + json + " to List of " + clazz.getName() + ".", e); + return List.of(); + } + } +} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/TinyRestClient.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/TinyRestClient.java new file mode 100644 index 000000000000..dd952f479fa0 --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/TinyRestClient.java @@ -0,0 +1,194 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy.tinyrestclient; + +import com.iluwatar.dynamicproxy.tinyrestclient.annotation.Body; +import com.iluwatar.dynamicproxy.tinyrestclient.annotation.Http; +import com.iluwatar.dynamicproxy.tinyrestclient.annotation.Path; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.util.UriUtils; + +/** + * Class to handle all the http communication with a Rest API. It is supported by the HttpClient + * Java library. + */ +@Slf4j +public class TinyRestClient { + + private static Map httpAnnotationByMethod = new HashMap<>(); + + private String baseUrl; + private HttpClient httpClient; + + /** + * Class constructor. + * + * @param baseUrl Root url for endpoints. + * @param httpClient Handle the http communication. + */ + public TinyRestClient(String baseUrl, HttpClient httpClient) { + this.baseUrl = baseUrl; + this.httpClient = httpClient; + } + + /** + * Creates a http communication to request and receive data from an endpoint. + * + * @param method Interface's method which is annotated with a http method. + * @param args Method's arguments passed in the call. + * @return Response from the endpoint. + * @throws IOException Exception thrown when any fail happens in the call. + * @throws InterruptedException Exception thrown when call is interrupted. + */ + public Object send(Method method, Object[] args) throws IOException, InterruptedException { + var httpAnnotation = getHttpAnnotation(method); + if (httpAnnotation == null) { + return null; + } + var httpAnnotationName = httpAnnotation.annotationType().getSimpleName().toUpperCase(); + var url = baseUrl + buildUrl(method, args, httpAnnotation); + var bodyPublisher = buildBodyPublisher(method, args); + var httpRequest = + HttpRequest.newBuilder() + .uri(URI.create(url)) + .header("Content-Type", "application/json") + .method(httpAnnotationName, bodyPublisher) + .build(); + var httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); + var statusCode = httpResponse.statusCode(); + if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { + var errorDetail = httpResponse.body(); + LOGGER.error("Error from server: " + errorDetail); + return null; + } + return getResponse(method, httpResponse); + } + + private String buildUrl(Method method, Object[] args, Annotation httpMethodAnnotation) { + var url = annotationValue(httpMethodAnnotation); + if (url == null) { + return ""; + } + var index = 0; + for (var parameter : method.getParameters()) { + var pathAnnotation = getAnnotationOf(parameter.getDeclaredAnnotations(), Path.class); + if (pathAnnotation != null) { + var pathParam = "{" + annotationValue(pathAnnotation) + "}"; + var pathValue = UriUtils.encodePath(args[index].toString(), StandardCharsets.UTF_8); + url = url.replace(pathParam, pathValue); + } + index++; + } + return url; + } + + private HttpRequest.BodyPublisher buildBodyPublisher(Method method, Object[] args) { + var index = 0; + for (var parameter : method.getParameters()) { + var bodyAnnotation = getAnnotationOf(parameter.getDeclaredAnnotations(), Body.class); + if (bodyAnnotation != null) { + var body = JsonUtil.objectToJson(args[index]); + return HttpRequest.BodyPublishers.ofString(body); + } + index++; + } + return HttpRequest.BodyPublishers.noBody(); + } + + private Object getResponse(Method method, HttpResponse httpResponse) { + var rawData = httpResponse.body(); + Type returnType; + try { + returnType = method.getGenericReturnType(); + } catch (Exception e) { + LOGGER.error("Cannot get the generic return type of the method " + method.getName() + "()"); + return null; + } + if (returnType instanceof ParameterizedType) { + Class responseClass = + (Class) (((ParameterizedType) returnType).getActualTypeArguments()[0]); + return JsonUtil.jsonToList(rawData, responseClass); + } else { + Class responseClass = method.getReturnType(); + return JsonUtil.jsonToObject(rawData, responseClass); + } + } + + private Annotation getHttpAnnotation(Method method) { + return httpAnnotationByMethod.computeIfAbsent( + method, + m -> + Arrays.stream(m.getDeclaredAnnotations()) + .filter(annot -> annot.annotationType().isAnnotationPresent(Http.class)) + .findFirst() + .orElse(null)); + } + + private Annotation getAnnotationOf(Annotation[] annotations, Class clazz) { + return Arrays.stream(annotations) + .filter(annot -> annot.annotationType().equals(clazz)) + .findFirst() + .orElse(null); + } + + private String annotationValue(Annotation annotation) { + var valueMethod = + Arrays.stream(annotation.annotationType().getDeclaredMethods()) + .filter(methodAnnot -> methodAnnot.getName().equals("value")) + .findFirst() + .orElse(null); + if (valueMethod == null) { + return null; + } + Object result; + try { + result = valueMethod.invoke(annotation, (Object[]) null); + } catch (Exception e) { + LOGGER.error( + "Cannot read the value " + + annotation.annotationType().getSimpleName() + + "." + + valueMethod.getName() + + "()", + e); + result = null; + } + return (result instanceof String strResult ? strResult : null); + } +} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Body.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Body.java new file mode 100644 index 000000000000..df89731936ba --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Body.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy.tinyrestclient.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotation to mark a method's parameter as a Body parameter. It is typically used on Post and Put + * http methods. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface Body {} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Delete.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Delete.java new file mode 100644 index 000000000000..a43df905798f --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Delete.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy.tinyrestclient.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** Annotation to mark an interface's method as a DELETE http method. */ +@Http +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Delete { + /** + * Set the url for this http method. + * + * @return Url address. + */ + String value() default ""; +} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Get.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Get.java new file mode 100644 index 000000000000..74f96ac062ec --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Get.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy.tinyrestclient.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** Annotation to mark an interface's method as a GET http method. */ +@Http +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Get { + /** + * Set the url for this http method. + * + * @return Url address. + */ + String value() default ""; +} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Http.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Http.java new file mode 100644 index 000000000000..f12878de2d90 --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Http.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy.tinyrestclient.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** Annotation to mark other annotations to be recognized as http methods. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.ANNOTATION_TYPE) +public @interface Http {} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Path.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Path.java new file mode 100644 index 000000000000..4ff1faea4844 --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Path.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy.tinyrestclient.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** Annotation to mark a method's parameter as a Path parameter. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface Path { + /** + * Path parameter to be replaced in the url. + * + * @return Path parameter. + */ + String value(); +} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Post.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Post.java new file mode 100644 index 000000000000..f10f38c83984 --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Post.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy.tinyrestclient.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** Annotation to mark an interface's method as a POST http method. */ +@Http +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Post { + /** + * Set the url for this http method. + * + * @return Url address. + */ + String value() default ""; +} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Put.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Put.java new file mode 100644 index 000000000000..9af9b27c4dde --- /dev/null +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Put.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy.tinyrestclient.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** Annotation to mark an interface's method as a PUT http method. */ +@Http +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Put { + /** + * Set the url for this http method. + * + * @return Url address. + */ + String value() default ""; +} diff --git a/dynamic-proxy/src/test/java/com/iluwatar/dynamicproxy/AppTest.java b/dynamic-proxy/src/test/java/com/iluwatar/dynamicproxy/AppTest.java new file mode 100644 index 000000000000..107255695344 --- /dev/null +++ b/dynamic-proxy/src/test/java/com/iluwatar/dynamicproxy/AppTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.dynamicproxy; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void shouldRunAppWithoutExceptions() { + assertDoesNotThrow(() -> App.main(null)); + } +} diff --git a/eip-aggregator/README.md b/eip-aggregator/README.md deleted file mode 100644 index a1dc18ea8fb8..000000000000 --- a/eip-aggregator/README.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -layout: pattern -title: EIP Aggregator -folder: eip-aggregator -permalink: /patterns/eip-aggregator/ -categories: Integration -tags: - - Java - - Difficulty-Intermittent - - EIP ---- - -## Intent -Sometimes in enterprise systems there is a need to group incoming data in order to process it as a whole. For example -you may need to gather offers and after defined number of offers has been received you would like to choose the one with -the best parameters. - -Aggregator allows you to merge messages based on defined criteria and parameters. It gathers original messages, -applies aggregation strategy and upon fulfilling given criteria, releasing merged messages. - -![alt text](./etc/aggregator.gif "Splitter") - -## Applicability -Use the Aggregator pattern when - -* You need to combine multiple incoming messages -* You want to process grouped data - -## Credits - -* [Gregor Hohpe, Bobby Woolf - Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/Aggregator.html) -* [Apache Camel - Documentation](http://camel.apache.org/aggregator2.html) - diff --git a/eip-aggregator/etc/aggregator.gif b/eip-aggregator/etc/aggregator.gif deleted file mode 100644 index b06cdfb0c920..000000000000 Binary files a/eip-aggregator/etc/aggregator.gif and /dev/null differ diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml deleted file mode 100644 index 3b043ad7ec32..000000000000 --- a/eip-aggregator/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - 4.0.0 - eip-aggregator - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.apache.camel - camel-core - ${camel.version} - - - - org.apache.camel - camel-spring-boot - ${camel.version} - - - - - com.github.sbrannen - spring-test-junit5 - test - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.springframework.boot - spring-boot-starter-test - - - - org.apache.camel - camel-test-spring - ${camel.version} - - - - \ No newline at end of file diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java deleted file mode 100644 index d55f24e3ddad..000000000000 --- a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/App.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * 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.eip.aggregator; - -import org.apache.camel.CamelContext; -import org.apache.camel.builder.RouteBuilder; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * Sometimes in enterprise systems there is a need to group incoming data in order to process it as a whole. For example - * you may need to gather offers and after defined number of offers has been received you would like to choose the one - * with the best parameters. - * - *

    - * Aggregator allows you to merge messages based on defined criteria and parameters. It gathers original messages, - * applies aggregation strategy and upon fulfilling given criteria, releasing merged messages. - *

    - * - */ -@SpringBootApplication -public class App { - - /** - * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes. - * - * @param args command line args - */ - public static void main(String[] args) throws Exception { - // Run Spring Boot application and obtain ApplicationContext - ConfigurableApplicationContext context = SpringApplication.run(App.class, args); - - // Get CamelContext from ApplicationContext - CamelContext camelContext = (CamelContext) context.getBean("camelContext"); - - // Add a new routes that will handle endpoints form SplitterRoute class. - camelContext.addRoutes(new RouteBuilder() { - - @Override - public void configure() throws Exception { - from("{{endpoint}}").log("ENDPOINT: ${body}"); - } - - }); - - // Add producer that will send test message to an entry point in WireTapRoute - String[] stringArray = {"Test item #1", "Test item #2", "Test item #3"}; - camelContext.createProducerTemplate().sendBody("{{entry}}", stringArray); - - SpringApplication.exit(context); - } -} diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java deleted file mode 100644 index 536565339f1a..000000000000 --- a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/AggregatorRoute.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 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.eip.aggregator.routes; - -import org.apache.camel.builder.RouteBuilder; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -/** - * Sample aggregator route definition. - * - *

    - * It consumes messages out of the direct:entry entry point and forwards them to direct:endpoint. - * Route accepts messages containing String as a body, it aggregates the messages based on the settings and forwards - * them as CSV to the output chanel. - * - * Settings for the aggregation are: aggregate until 3 messages are bundled or wait 2000ms before sending bundled - * messages further. - *

    - * - * In this example input/output endpoints names are stored in application.properties file. - */ -@Component -public class AggregatorRoute extends RouteBuilder { - - @Autowired - private MessageAggregationStrategy aggregator; - - /** - * Configures the route - * @throws Exception in case of exception during configuration - */ - @Override - public void configure() throws Exception { - // Main route - from("{{entry}}").aggregate(constant(true), aggregator) - .completionSize(3).completionInterval(2000) - .to("{{endpoint}}"); - } -} diff --git a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java b/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java deleted file mode 100644 index 4b5e4cb2f501..000000000000 --- a/eip-aggregator/src/main/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategy.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 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.eip.aggregator.routes; - -import org.apache.camel.Exchange; -import org.apache.camel.processor.aggregate.AggregationStrategy; -import org.springframework.stereotype.Component; - -/** - * Aggregation strategy joining bodies of messages. If message is first one oldMessage is null. All changes are - * made on IN messages. - */ -@Component -public class MessageAggregationStrategy implements AggregationStrategy { - - @Override - public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { - if (oldExchange == null) { - return newExchange; - } - - String in1 = (String) oldExchange.getIn().getBody(); - String in2 = (String) newExchange.getIn().getBody(); - - oldExchange.getIn().setBody(in1 + ";" + in2); - - return oldExchange; - } -} diff --git a/eip-aggregator/src/main/resources/application.properties b/eip-aggregator/src/main/resources/application.properties deleted file mode 100644 index 044833fc1be1..000000000000 --- a/eip-aggregator/src/main/resources/application.properties +++ /dev/null @@ -1,25 +0,0 @@ -# -# 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. -# - -entry=direct:entry -endpoint=direct:endpoint diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java deleted file mode 100644 index 40a33678670f..000000000000 --- a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 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.eip.aggregator; - -import org.junit.jupiter.api.Test; - -/** - * Test for App class - */ -public class AppTest { - - @Test - public void testMain() throws Exception { - String[] args = {}; - App.main(args); - } -} diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java deleted file mode 100644 index 2c7d207d6f53..000000000000 --- a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * 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.eip.aggregator.routes; - -import org.apache.camel.EndpointInject; -import org.apache.camel.ProducerTemplate; -import org.apache.camel.component.mock.MockEndpoint; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Test class for AggregatorRoute. - *

    - * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute - * original endpoint names to mocks. - *

    - */ -@ExtendWith(SpringExtension.class) -@SpringApplicationConfiguration(classes = AggregatorRouteTest.class) -@ActiveProfiles("test") -@EnableAutoConfiguration -@ComponentScan -public class AggregatorRouteTest { - - @EndpointInject(uri = "{{entry}}") - private ProducerTemplate entry; - - @EndpointInject(uri = "{{endpoint}}") - private MockEndpoint endpoint; - - /** - * Test if endpoint receives three separate messages. - * @throws Exception in case of en exception during the test - */ - @Test - @DirtiesContext - public void testSplitter() throws Exception { - - // Three items in one entry message - entry.sendBody("TEST1"); - entry.sendBody("TEST2"); - entry.sendBody("TEST3"); - entry.sendBody("TEST4"); - entry.sendBody("TEST5"); - - // Endpoint should have three different messages in the end order of the messages is not important - endpoint.expectedMessageCount(2); - endpoint.assertIsSatisfied(); - - String body = (String) endpoint.getReceivedExchanges().get(0).getIn().getBody(); - assertEquals(3, body.split(";").length); - - String body2 = (String) endpoint.getReceivedExchanges().get(1).getIn().getBody(); - assertEquals(2, body2.split(";").length); - } -} diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java deleted file mode 100644 index 7a7a15154677..000000000000 --- a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 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.eip.aggregator.routes; - -import org.apache.camel.CamelContext; -import org.apache.camel.Exchange; -import org.apache.camel.impl.DefaultExchange; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Tests MessageAggregationStrategy - */ -public class MessageAggregationStrategyTest { - - @Test - public void testAggregate() { - MessageAggregationStrategy mas = new MessageAggregationStrategy(); - Exchange oldExchange = new DefaultExchange((CamelContext) null); - oldExchange.getIn().setBody("TEST1"); - - Exchange newExchange = new DefaultExchange((CamelContext) null); - newExchange.getIn().setBody("TEST2"); - - Exchange output = mas.aggregate(oldExchange, newExchange); - String outputBody = (String) output.getIn().getBody(); - assertEquals("TEST1;TEST2", outputBody); - } - - @Test - public void testAggregateOldNull() { - MessageAggregationStrategy mas = new MessageAggregationStrategy(); - - Exchange newExchange = new DefaultExchange((CamelContext) null); - newExchange.getIn().setBody("TEST2"); - - Exchange output = mas.aggregate(null, newExchange); - String outputBody = (String) output.getIn().getBody(); - - assertEquals(newExchange, output); - assertEquals("TEST2", outputBody); - } -} diff --git a/eip-aggregator/src/test/resources/application-test.properties b/eip-aggregator/src/test/resources/application-test.properties deleted file mode 100644 index 8d6ecbbd3bf2..000000000000 --- a/eip-aggregator/src/test/resources/application-test.properties +++ /dev/null @@ -1,25 +0,0 @@ -# -# 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. -# - -entry=direct:entry -endpoint=mock:endpoint diff --git a/eip-message-channel/README.md b/eip-message-channel/README.md deleted file mode 100644 index 606619619e8f..000000000000 --- a/eip-message-channel/README.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -layout: pattern -title: EIP Message Channel -folder: eip-message-channel -permalink: /patterns/eip-message-channel/ -categories: Integration -tags: - - Java - - EIP - - Apache Camel™ ---- - -## Intent -When two applications communicate using a messaging system they do it by using logical addresses -of the system, so called Message Channels. - -![alt text](./etc/message-channel.png "Message Channel") - -## Applicability -Use the Message Channel pattern when - -* two or more applications need to communicate using a messaging system - -## Real world examples - -* [akka-camel](http://doc.akka.io/docs/akka/snapshot/scala/camel.html) diff --git a/eip-message-channel/etc/message-channel.png b/eip-message-channel/etc/message-channel.png deleted file mode 100644 index 7db473281aff..000000000000 Binary files a/eip-message-channel/etc/message-channel.png and /dev/null differ diff --git a/eip-message-channel/etc/message-channel.ucls b/eip-message-channel/etc/message-channel.ucls deleted file mode 100644 index 3ef0ed4bc8fd..000000000000 --- a/eip-message-channel/etc/message-channel.ucls +++ /dev/null @@ -1,320 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/eip-message-channel/pom.xml b/eip-message-channel/pom.xml deleted file mode 100644 index 84cde7e2ef96..000000000000 --- a/eip-message-channel/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - eip-message-channel - - - org.apache.camel - camel-core - - - org.apache.camel - camel-stream - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - diff --git a/eip-message-channel/src/main/java/com/iluwatar/eip/message/channel/App.java b/eip-message-channel/src/main/java/com/iluwatar/eip/message/channel/App.java deleted file mode 100644 index d5929d0db3aa..000000000000 --- a/eip-message-channel/src/main/java/com/iluwatar/eip/message/channel/App.java +++ /dev/null @@ -1,76 +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.eip.message.channel; - -import org.apache.camel.CamelContext; -import org.apache.camel.builder.RouteBuilder; -import org.apache.camel.impl.DefaultCamelContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * When two applications communicate with each other using a messaging system they first need to - * establish a communication channel that will carry the data. Message Channel decouples Message - * producers and consumers. - *

    - * The sending application doesn't necessarily know what particular application will end up - * retrieving it, but it can be assured that the application that retrieves the information is - * interested in that information. This is because the messaging system has different Message - * Channels for different types of information the applications want to communicate. When an - * application sends information, it doesn't randomly add the information to any channel available; - * it adds it to a channel whose specific purpose is to communicate that sort of information. - * Likewise, an application that wants to receive particular information doesn't pull info off some - * random channel; it selects what channel to get information from based on what type of information - * it wants. - *

    - * In this example we use Apache Camel to establish two different Message Channels. The first one - * reads from standard input and delivers messages to Direct endpoint. The second Message Channel is - * established from the Direct component to console output. No actual messages are sent, only the - * established routes are printed to standard output. - * - */ -public class App { - - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * Program entry point - */ - public static void main(String[] args) throws Exception { - CamelContext context = new DefaultCamelContext(); - - context.addRoutes(new RouteBuilder() { - - @Override - public void configure() throws Exception { - from("stream:in").to("direct:greetings"); - from("direct:greetings").to("stream:out"); - } - }); - - context.start(); - context.getRoutes().stream().forEach(r -> LOGGER.info(r.toString())); - context.stop(); - } -} diff --git a/eip-message-channel/src/test/java/com/iluwatar/eip/message/channel/AppTest.java b/eip-message-channel/src/test/java/com/iluwatar/eip/message/channel/AppTest.java deleted file mode 100644 index 127f427b8548..000000000000 --- a/eip-message-channel/src/test/java/com/iluwatar/eip/message/channel/AppTest.java +++ /dev/null @@ -1,39 +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.eip.message.channel; - -import org.junit.jupiter.api.Test; - -/** - * - * Application test - * - */ -public class AppTest { - - @Test - public void test() throws Exception { - String[] args = {}; - App.main(args); - } -} diff --git a/eip-publish-subscribe/.gitignore b/eip-publish-subscribe/.gitignore deleted file mode 100644 index b83d22266ac8..000000000000 --- a/eip-publish-subscribe/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/eip-publish-subscribe/README.md b/eip-publish-subscribe/README.md deleted file mode 100644 index 90ac02c9b462..000000000000 --- a/eip-publish-subscribe/README.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -layout: pattern -title: EIP Publish Subscribe -folder: eip-publish-subscribe -permalink: /patterns/eip-publish-subscribe/ -categories: Integration -tags: - - Java - - EIP - - Apache Camel™ ---- - -## Intent -Broadcast messages from sender to all the interested receivers. - -![alt text](./etc/publish-subscribe.png "Publish Subscribe Channel") - -## Applicability -Use the Publish Subscribe Channel pattern when - -* two or more applications need to communicate using a messaging system for broadcasts. - -## Credits - -* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2) diff --git a/eip-publish-subscribe/etc/publish-subscribe.png b/eip-publish-subscribe/etc/publish-subscribe.png deleted file mode 100644 index 99867da66b54..000000000000 Binary files a/eip-publish-subscribe/etc/publish-subscribe.png and /dev/null differ diff --git a/eip-publish-subscribe/etc/publish-subscribe.ucls b/eip-publish-subscribe/etc/publish-subscribe.ucls deleted file mode 100644 index 1b121506eed8..000000000000 --- a/eip-publish-subscribe/etc/publish-subscribe.ucls +++ /dev/null @@ -1,218 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/eip-publish-subscribe/pom.xml b/eip-publish-subscribe/pom.xml deleted file mode 100644 index 82763b22bfd5..000000000000 --- a/eip-publish-subscribe/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - eip-publish-subscribe - - - org.apache.camel - camel-core - - - org.apache.camel - camel-stream - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - diff --git a/eip-publish-subscribe/src/main/java/com/iluwatar/eip/publish/subscribe/App.java b/eip-publish-subscribe/src/main/java/com/iluwatar/eip/publish/subscribe/App.java deleted file mode 100644 index 7c7e77a1848a..000000000000 --- a/eip-publish-subscribe/src/main/java/com/iluwatar/eip/publish/subscribe/App.java +++ /dev/null @@ -1,72 +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.eip.publish.subscribe; - -import org.apache.camel.CamelContext; -import org.apache.camel.ProducerTemplate; -import org.apache.camel.builder.RouteBuilder; -import org.apache.camel.impl.DefaultCamelContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * There are well-established patterns for implementing broadcasting. The Observer pattern describes - * the need to decouple observers from their subject (that is, the originator of the event) so that - * the subject can easily provide event notification to all interested observers no matter how many - * observers there are (even none). The Publish-Subscribe pattern expands upon Observer by adding - * the notion of an event channel for communicating event notifications. - *

    - * A Publish-Subscribe Channel works like this: It has one input channel that splits into multiple - * output channels, one for each subscriber. When an event is published into the channel, the - * Publish-Subscribe Channel delivers a copy of the message to each of the output channels. Each - * output end of the channel has only one subscriber, which is allowed to consume a message only - * once. In this way, each subscriber gets the message only once, and consumed copies disappear from - * their channels. - *

    - * In this example we use Apache Camel to establish a Publish-Subscribe Channel from "direct-origin" - * to "mock:foo", "mock:bar" and "stream:out". - * - */ -public class App { - - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * Program entry point - */ - public static void main(String[] args) throws Exception { - CamelContext context = new DefaultCamelContext(); - context.addRoutes(new RouteBuilder() { - @Override - public void configure() throws Exception { - from("direct:origin").multicast().to("mock:foo", "mock:bar", "stream:out"); - } - }); - ProducerTemplate template = context.createProducerTemplate(); - context.start(); - context.getRoutes().stream().forEach(r -> LOGGER.info(r.toString())); - template.sendBody("direct:origin", "Hello from origin"); - context.stop(); - } -} diff --git a/eip-publish-subscribe/src/main/resources/logback.xml b/eip-publish-subscribe/src/main/resources/logback.xml deleted file mode 100644 index 582af26bde36..000000000000 --- a/eip-publish-subscribe/src/main/resources/logback.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - publish-subscribe.log - - publish-subscribe-%d.log - 5 - - - %-5p [%d{ISO8601,UTC}] %c: %m%n - - - - - - %-5p [%d{ISO8601,UTC}] %c: %m%n - - - - - - - - - - - - - diff --git a/eip-publish-subscribe/src/test/java/com/iluwatar/eip/publish/subscribe/AppTest.java b/eip-publish-subscribe/src/test/java/com/iluwatar/eip/publish/subscribe/AppTest.java deleted file mode 100644 index 783c796ac549..000000000000 --- a/eip-publish-subscribe/src/test/java/com/iluwatar/eip/publish/subscribe/AppTest.java +++ /dev/null @@ -1,39 +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.eip.publish.subscribe; - -import org.junit.jupiter.api.Test; - -/** - * - * Application test - * - */ -public class AppTest { - - @Test - public void test() throws Exception { - String[] args = {}; - App.main(args); - } -} diff --git a/eip-splitter/README.md b/eip-splitter/README.md deleted file mode 100644 index 51a917badd4b..000000000000 --- a/eip-splitter/README.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -layout: pattern -title: EIP Splitter -folder: eip-splitter -permalink: /patterns/eip-splitter/ -categories: Integration -tags: - - Java - - Difficulty-Intermittent - - EIP ---- - -## Intent -It is very common in integration systems that incoming messages consists of many items bundled together. For example -an invoice document contains multiple invoice lines describing transaction (quantity, name of provided -service/sold goods, price etc.). Such bundled messages may not be accepted by other systems. This is where splitter -pattern comes in handy. It will take the whole document, split it based on given criteria and send individual -items to the endpoint. - -![alt text](./etc/sequencer.gif "Splitter") - -## Applicability -Use the Splitter pattern when - -* You need to split received data into smaller pieces to process them individually -* You need to control the size of data batches you are able to process - -## Credits - -* [Gregor Hohpe, Bobby Woolf - Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/Sequencer.html) -* [Apache Camel - Documentation](http://camel.apache.org/splitter.html) - diff --git a/eip-splitter/etc/sequencer.gif b/eip-splitter/etc/sequencer.gif deleted file mode 100644 index a925fa209877..000000000000 Binary files a/eip-splitter/etc/sequencer.gif and /dev/null differ diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml deleted file mode 100644 index ed16337da8d7..000000000000 --- a/eip-splitter/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - 4.0.0 - eip-splitter - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.apache.camel - camel-core - ${camel.version} - - - - org.apache.camel - camel-spring-boot - ${camel.version} - - - - - com.github.sbrannen - spring-test-junit5 - test - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.springframework.boot - spring-boot-starter-test - - - - org.apache.camel - camel-test-spring - ${camel.version} - - - - \ No newline at end of file diff --git a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java deleted file mode 100644 index ceadb5f8dc0e..000000000000 --- a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/App.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * 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.eip.splitter; - -import org.apache.camel.CamelContext; -import org.apache.camel.builder.RouteBuilder; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * It is very common in integration systems that incoming messages consists of many items bundled together. For example - * an invoice document contains multiple invoice lines describing transaction (quantity, name of provided - * service/sold goods, price etc.). Such bundled messages may not be accepted by other systems. This is where splitter - * pattern comes in handy. It will take the whole document, split it based on given criteria and send individual - * items to the endpoint. - * - *

    - * Splitter allows you to split messages based on defined criteria. It takes original message, process it and send - * multiple parts to the output channel. It is not defined if it should keep the order of items though. - *

    - * - */ -@SpringBootApplication -public class App { - - /** - * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes. - * - * @param args command line args - */ - public static void main(String[] args) throws Exception { - // Run Spring Boot application and obtain ApplicationContext - ConfigurableApplicationContext context = SpringApplication.run(App.class, args); - - // Get CamelContext from ApplicationContext - CamelContext camelContext = (CamelContext) context.getBean("camelContext"); - - // Add a new routes that will handle endpoints form SplitterRoute class. - camelContext.addRoutes(new RouteBuilder() { - - @Override - public void configure() throws Exception { - from("{{endpoint}}").log("ENDPOINT: ${body}"); - } - - }); - - // Add producer that will send test message to an entry point in WireTapRoute - String[] stringArray = {"Test item #1", "Test item #2", "Test item #3"}; - camelContext.createProducerTemplate().sendBody("{{entry}}", stringArray); - - SpringApplication.exit(context); - } -} diff --git a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java b/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java deleted file mode 100644 index f7eb28deaf11..000000000000 --- a/eip-splitter/src/main/java/com/iluwatar/eip/splitter/routes/SplitterRoute.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 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.eip.splitter.routes; - -import org.apache.camel.builder.RouteBuilder; -import org.springframework.stereotype.Component; - -/** - * Sample splitter route definition. - * - *

    - * It consumes messages out of the direct:entry entry point and forwards them to direct:endpoint. - * Route accepts messages having body of array or collection of objects. Splitter component split message body and - * forwards single objects to the endpoint. - *

    - * - * In this example input/output endpoints names are stored in application.properties file. - */ -@Component -public class SplitterRoute extends RouteBuilder { - - /** - * Configures the route - * @throws Exception in case of exception during configuration - */ - @Override - public void configure() throws Exception { - // Main route - from("{{entry}}").split().body().to("{{endpoint}}"); - } -} diff --git a/eip-splitter/src/main/resources/application.properties b/eip-splitter/src/main/resources/application.properties deleted file mode 100644 index 044833fc1be1..000000000000 --- a/eip-splitter/src/main/resources/application.properties +++ /dev/null @@ -1,25 +0,0 @@ -# -# 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. -# - -entry=direct:entry -endpoint=direct:endpoint diff --git a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java deleted file mode 100644 index fe3eca01e2db..000000000000 --- a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 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.eip.splitter; - -import org.junit.jupiter.api.Test; - -/** - * Test for App class - */ -public class AppTest { - - @Test - public void testMain() throws Exception { - String[] args = {}; - App.main(args); - } -} diff --git a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java deleted file mode 100644 index 9257a4410186..000000000000 --- a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 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.eip.splitter.routes; - -import org.apache.camel.EndpointInject; -import org.apache.camel.ProducerTemplate; -import org.apache.camel.component.mock.MockEndpoint; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -/** - * Test class for SplitterRoute. - *

    - * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute - * original endpoint names to mocks. - *

    - */ -@ExtendWith(SpringExtension.class) -@SpringApplicationConfiguration(classes = SplitterRouteTest.class) -@ActiveProfiles("test") -@EnableAutoConfiguration -@ComponentScan -public class SplitterRouteTest { - - @EndpointInject(uri = "{{entry}}") - private ProducerTemplate entry; - - @EndpointInject(uri = "{{endpoint}}") - private MockEndpoint endpoint; - - /** - * Test if endpoint receives three separate messages. - * @throws Exception in case of en exception during the test - */ - @Test - @DirtiesContext - public void testSplitter() throws Exception { - - // Three items in one entry message - entry.sendBody(new String[] {"TEST1", "TEST2", "TEST3"}); - - // Endpoint should have three different messages in the end order of the messages is not important - endpoint.expectedMessageCount(3); - endpoint.assertIsSatisfied(); - } -} diff --git a/eip-splitter/src/test/resources/application-test.properties b/eip-splitter/src/test/resources/application-test.properties deleted file mode 100644 index 8d6ecbbd3bf2..000000000000 --- a/eip-splitter/src/test/resources/application-test.properties +++ /dev/null @@ -1,25 +0,0 @@ -# -# 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. -# - -entry=direct:entry -endpoint=mock:endpoint diff --git a/eip-wire-tap/README.md b/eip-wire-tap/README.md deleted file mode 100644 index 31cbd9123603..000000000000 --- a/eip-wire-tap/README.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -layout: pattern -title: EIP Wire Tap -folder: eip-wire-tap -permalink: /patterns/eip-wire-tap/ -categories: Integration -tags: - - Java - - Difficulty-Intermittent - - EIP ---- - -## Intent -In most integration cases there is a need to monitor the messages flowing through the system. It is usually achieved -by intercepting the message and redirecting it to a different location like console, filesystem or the database. -It is important that such functionality should not modify the original message and influence the processing path. - -![alt text](./etc/wiretap.gif "Wire Tap") - -## Applicability -Use the Wire Tap pattern when - -* You need to monitor messages flowing through the system -* You need to redirect the same, unchanged message to two different endpoints/paths - -## Credits - -* [Gregor Hohpe, Bobby Woolf - Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/WireTap.html) -* [Apache Camel - Documentation](http://camel.apache.org/wire-tap.html) diff --git a/eip-wire-tap/etc/wiretap.gif b/eip-wire-tap/etc/wiretap.gif deleted file mode 100644 index 4141737167ca..000000000000 Binary files a/eip-wire-tap/etc/wiretap.gif and /dev/null differ diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml deleted file mode 100644 index 752d43077e57..000000000000 --- a/eip-wire-tap/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - 4.0.0 - eip-wire-tap - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.apache.camel - camel-core - ${camel.version} - - - - org.apache.camel - camel-spring-boot - ${camel.version} - - - - - com.github.sbrannen - spring-test-junit5 - test - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.springframework.boot - spring-boot-starter-test - - - - org.apache.camel - camel-test-spring - ${camel.version} - - - - \ No newline at end of file diff --git a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java deleted file mode 100644 index ca605cb78171..000000000000 --- a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * 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.eip.wiretap; - -import org.apache.camel.CamelContext; -import org.apache.camel.builder.RouteBuilder; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * In most integration cases there is a need to monitor the messages flowing through the system. It is usually achieved - * by intercepting the message and redirecting it to a different location like console, filesystem or the database. - * It is important that such functionality should not modify the original message and influence the processing path. - * - *

    - * Wire Tap allows you to route messages to a separate location while they are being forwarded to the ultimate - * destination. It basically consumes messages of the input channel and publishes the unmodified message to both - * output channels. - *

    - */ -@SpringBootApplication -public class App { - - /** - * Program entry point. It starts Spring Boot application and using Apache Camel it auto-configures routes. - * - * @param args command line args - */ - public static void main(String[] args) throws Exception { - // Run Spring Boot application and obtain ApplicationContext - ConfigurableApplicationContext context = SpringApplication.run(App.class, args); - - // Get CamelContext from ApplicationContext - CamelContext camelContext = (CamelContext) context.getBean("camelContext"); - - // Add a new routes that will handle endpoints form WireTapRoute class. - camelContext.addRoutes(new RouteBuilder() { - - @Override - public void configure() throws Exception { - from("{{endpoint}}").log("ENDPOINT: ${body}"); - from("{{wireTapEndpoint}}").log("WIRETAPPED ENDPOINT: ${body}"); - } - - }); - - // Add producer that will send test message to an entry point in WireTapRoute - camelContext.createProducerTemplate().sendBody("{{entry}}", "Test message"); - - SpringApplication.exit(context); - } -} diff --git a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java b/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java deleted file mode 100644 index 994ceacdb6bc..000000000000 --- a/eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/routes/WireTapRoute.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 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.eip.wiretap.routes; - -import org.apache.camel.builder.RouteBuilder; -import org.springframework.stereotype.Component; - -/** - * Sample wire tap route definition. - * - *

    - * It consumes messages out of the direct:entry entry point and forwards them to direct:endpoint. - * Wire Tap intercepts the message and sends it to direct:wireTap, which in turn forwards it to - * direct:wireTapEndpoint. - *

    - * - * In this example input/output endpoints names are stored in application.properties file. - */ -@Component -public class WireTapRoute extends RouteBuilder { - - /** - * Configures the route - * @throws Exception in case of exception during configuration - */ - @Override - public void configure() throws Exception { - // Main route - from("{{entry}}").wireTap("direct:wireTap").to("{{endpoint}}"); - - // Wire tap route - from("direct:wireTap").log("Message: ${body}").to("{{wireTapEndpoint}}"); - } -} diff --git a/eip-wire-tap/src/main/resources/application.properties b/eip-wire-tap/src/main/resources/application.properties deleted file mode 100644 index 90a152425a4e..000000000000 --- a/eip-wire-tap/src/main/resources/application.properties +++ /dev/null @@ -1,26 +0,0 @@ -# -# 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. -# - -entry=direct:entry -endpoint=direct:endpoint -wireTapEndpoint=direct:wireTapEndpoint \ No newline at end of file diff --git a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java deleted file mode 100644 index 673803df706b..000000000000 --- a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 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.eip.wiretap; - -import org.junit.jupiter.api.Test; - -/** - * Test for App class - */ -public class AppTest { - - @Test - public void testMain() throws Exception { - String[] args = {}; - App.main(args); - } -} diff --git a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java deleted file mode 100644 index 449f86208258..000000000000 --- a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * 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.eip.wiretap.routes; - -import org.apache.camel.EndpointInject; -import org.apache.camel.Message; -import org.apache.camel.ProducerTemplate; -import org.apache.camel.component.mock.MockEndpoint; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Test class for WireTapRoute. - *

    - * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute - * original endpoint names to mocks. - *

    - */ -@ExtendWith(SpringExtension.class) -@SpringApplicationConfiguration(classes = WireTapRouteTest.class) -@ActiveProfiles("test") -@EnableAutoConfiguration -@ComponentScan -public class WireTapRouteTest { - - @EndpointInject(uri = "{{entry}}") - private ProducerTemplate entry; - - @EndpointInject(uri = "{{endpoint}}") - private MockEndpoint endpoint; - - @EndpointInject(uri = "{{wireTapEndpoint}}") - private MockEndpoint wireTapEndpoint; - - /** - * Test if both endpoints receive exactly one message containing the same, unchanged body. - * @throws Exception in case of en exception during the test - */ - @Test - @DirtiesContext - public void testWireTap() throws Exception { - entry.sendBody("TEST"); - - endpoint.expectedMessageCount(1); - wireTapEndpoint.expectedMessageCount(1); - - endpoint.assertIsSatisfied(); - wireTapEndpoint.assertIsSatisfied(); - - Message endpointIn = endpoint.getExchanges().get(0).getIn(); - Message wireTapEndpointIn = wireTapEndpoint.getExchanges().get(0).getIn(); - - assertEquals("TEST", endpointIn.getBody()); - assertEquals("TEST", wireTapEndpointIn.getBody()); - } -} diff --git a/eip-wire-tap/src/test/resources/application-test.properties b/eip-wire-tap/src/test/resources/application-test.properties deleted file mode 100644 index e76faa1fc864..000000000000 --- a/eip-wire-tap/src/test/resources/application-test.properties +++ /dev/null @@ -1,26 +0,0 @@ -# -# 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. -# - -entry=direct:entry -endpoint=mock:endpoint -wireTapEndpoint=mock:wireTapEndpoint \ No newline at end of file diff --git a/event-aggregator/README.md b/event-aggregator/README.md index ac07869e7a89..063aac502640 100644 --- a/event-aggregator/README.md +++ b/event-aggregator/README.md @@ -1,34 +1,206 @@ --- -layout: pattern -title: Event Aggregator -folder: event-aggregator -permalink: /patterns/event-aggregator/ -categories: Structural -tags: - - Java - - Difficulty-Beginner - - Reactive +title: "Event Aggregator Pattern in Java: Centralizing Event Management in Large Applications" +shortTitle: Event Aggregator +description: "Explore the Event Aggregator design pattern with our in-depth guide. Learn how to implement it effectively with examples and improve your Java applications. Perfect for developers seeking to enhance their design pattern knowledge." +category: Messaging +language: en +tag: + - Decoupling + - Event-driven + - Messaging + - Publish/subscribe + - Reactive +head: + - - meta + - name: keywords + content: --- -## Intent -A system with lots of objects can lead to complexities when a -client wants to subscribe to events. The client has to find and register for -each object individually, if each object has multiple events then each event -requires a separate subscription. An Event Aggregator acts as a single source -of events for many objects. It registers for all the events of the many objects -allowing clients to register with just the aggregator. +## Also known as -![alt text](./etc/classes.png "Event Aggregator") +* Event Channel +* Event Central +* Message Hub + +## Intent of Event Aggregator Design Pattern + +An Event Aggregator is a design pattern used for handling events in a system. It centralizes the event handling logic, making it easier to manage and maintain. The Event Aggregator design pattern aims to decouple event generation from event handling. This design pattern collects events from multiple sources and routes them to the appropriate handlers. + +## Detailed Explanation of Event Aggregator Pattern with Real-World Examples + +Real-world example + +> The Event Aggregator pattern is often compared to a hub in a wheel. In this analogy, the Event Aggregator is the hub, and the spokes are the event sources. The hub collects events from all the spokes and then distributes them to the appropriate handlers. + +In Plain Words + +> Event Aggregator is a design pattern that allows multiple event sources to communicate with event handlers through a central point, rather than having each event source communicate directly with each handler. + +Sequence diagram + +![Event Aggregator sequence diagram](./etc/event-aggregator-sequence-diagram.png) + +## Programmatic Example of Event Aggregator Pattern in Java + +Consider the following example where we use the Event Aggregator to handle multiple events. + +King Joffrey sits on the iron throne and rules the seven kingdoms of Westeros. He receives most of his critical information from King's Hand, the second in command. King's hand has many close advisors himself, feeding him with relevant information about events occurring in the kingdom. + +In our programmatic example, we demonstrate the implementation of an event aggregator pattern. Some of the objects are event listeners, some are event emitters, and the event aggregator does both. + +```java +public interface EventObserver { + void onEvent(Event e); +} +``` + +```java +public abstract class EventEmitter { + + private final Map> observerLists; + + public EventEmitter() { + observerLists = new HashMap<>(); + } + + public final void registerObserver(EventObserver obs, Event e) { + // implementation omitted + } + + protected void notifyObservers(Event e) { + // implementation omitted + } +} +``` + +`KingJoffrey` is listening to events from `KingsHand`. + +```java + +@Slf4j +public class KingJoffrey implements EventObserver { + @Override + public void onEvent(Event e) { + LOGGER.info("Received event from the King's Hand: {}", e.toString()); + } +} +``` + +`KingsHand` is listening to events from his subordinates `LordBaelish`, `LordVarys`, and `Scout`. Whatever he hears from them, he delivers to `KingJoffrey`. + +```java +public class KingsHand extends EventEmitter implements EventObserver { + + public KingsHand() { + } + + public KingsHand(EventObserver obs, Event e) { + super(obs, e); + } + + @Override + public void onEvent(Event e) { + notifyObservers(e); + } +} +``` + +For example, `LordVarys` finds a traitor every Sunday and notifies the `KingsHand`. + +```java + +@Slf4j +public class LordVarys extends EventEmitter implements EventObserver { + @Override + public void timePasses(Weekday day) { + if (day == Weekday.SATURDAY) { + notifyObservers(Event.TRAITOR_DETECTED); + } + } +} +``` + +The following snippet demonstrates how the objects are constructed and wired together. + +```java +public static void main(String[] args) { + + var kingJoffrey = new KingJoffrey(); + + var kingsHand = new KingsHand(); + kingsHand.registerObserver(kingJoffrey, Event.TRAITOR_DETECTED); + kingsHand.registerObserver(kingJoffrey, Event.STARK_SIGHTED); + kingsHand.registerObserver(kingJoffrey, Event.WARSHIPS_APPROACHING); + kingsHand.registerObserver(kingJoffrey, Event.WHITE_WALKERS_SIGHTED); + + var varys = new LordVarys(); + varys.registerObserver(kingsHand, Event.TRAITOR_DETECTED); + varys.registerObserver(kingsHand, Event.WHITE_WALKERS_SIGHTED); + + var scout = new Scout(); + scout.registerObserver(kingsHand, Event.WARSHIPS_APPROACHING); + scout.registerObserver(varys, Event.WHITE_WALKERS_SIGHTED); + + var baelish = new LordBaelish(kingsHand, Event.STARK_SIGHTED); + + var emitters = List.of( + kingsHand, + baelish, + varys, + scout + ); + + Arrays.stream(Weekday.values()) + .>map(day -> emitter -> emitter.timePasses(day)) + .forEachOrdered(emitters::forEach); +} +``` + +The console output after running the example. + +``` +21:37:38.737 [main] INFO com.iluwatar.event.aggregator.KingJoffrey -- Received event from the King's Hand: Warships approaching +21:37:38.739 [main] INFO com.iluwatar.event.aggregator.KingJoffrey -- Received event from the King's Hand: White walkers sighted +21:37:38.739 [main] INFO com.iluwatar.event.aggregator.KingJoffrey -- Received event from the King's Hand: Stark sighted +21:37:38.739 [main] INFO com.iluwatar.event.aggregator.KingJoffrey -- Received event from the King's Hand: Traitor detected +``` + +## When to Use the Event Aggregator Pattern in Java -## Applicability Use the Event Aggregator pattern when -* Event Aggregator is a good choice when you have lots of objects that are - potential event sources. Rather than have the observer deal with registering - with them all, you can centralize the registration logic to the Event - Aggregator. As well as simplifying registration, a Event Aggregator also - simplifies the memory management issues in using observers. +* You have multiple event sources and handlers. +* You want to decouple the event generation and handling logic. +* You need a centralized event management system. + +## Real-World Applications of Event Aggregator Pattern in Java + +* Enterprise application integrations where systems need a central point to handle events generated by various subsystems. +* Complex GUI applications where user actions in one part of the interface need to affect other parts without tight coupling between the components. + +## Benefits and Trade-offs of Event Aggregator Pattern + +Benefits: + +* Decoupling: By centralizing event handling, the Event Aggregator minimizes direct interaction between components, leading to a more modular and easier-to-manage system. +* Improves Flexibility and Scalability: Adding new publishers or subscribers involves less effort since the central aggregator handles all routing. +* Simplifies Component Interface: Components need to know only about the Event Aggregator, not about other components. +* Centralizes event management: Makes the system easier to maintain. + +Trade-offs: + +* Complexity of the Aggregator: The Event Aggregator itself can become a complex and high-maintenance component if not properly designed. +* Potential Performance Bottleneck: If not scaled properly, the central event handling mechanism can become a bottleneck in the system. + +## Related Java Design Patterns + +* [Mediator](https://java-design-patterns.com/patterns/mediator/): Similar to Mediator in that it abstracts direct communications between components, but focused specifically on event messages. +* [Observer](https://java-design-patterns.com/patterns/observer/): The Event Aggregator pattern is often implemented using the Observer pattern, where the aggregator observes events and notifies subscribers. +* Publish-Subscribe: The Event Aggregator can be seen as a special case of the Publish-Subscribe pattern, with the aggregator acting as the broker. -## Credits +## References and Credits -* [Martin Fowler - Event Aggregator](http://martinfowler.com/eaaDev/EventAggregator.html) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/44eWKXv) +* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/440b0CZ) +* [Java Design Pattern Essentials](https://amzn.to/43XHCgM) +* [Event Aggregator (Martin Fowler)](http://martinfowler.com/eaaDev/EventAggregator.html) diff --git a/event-aggregator/etc/event-aggregator-sequence-diagram.png b/event-aggregator/etc/event-aggregator-sequence-diagram.png new file mode 100644 index 000000000000..f96fbc427a86 Binary files /dev/null and b/event-aggregator/etc/event-aggregator-sequence-diagram.png differ diff --git a/event-aggregator/etc/event-aggregator.urm.puml b/event-aggregator/etc/event-aggregator.urm.puml new file mode 100644 index 000000000000..341d7d65e02c --- /dev/null +++ b/event-aggregator/etc/event-aggregator.urm.puml @@ -0,0 +1,74 @@ +@startuml +package com.iluwatar.event.aggregator { + class App { + + App() + + main(args : String[]) {static} + } + enum Event { + + STARK_SIGHTED {static} + + TRAITOR_DETECTED {static} + + WARSHIPS_APPROACHING {static} + - description : String + + toString() : String + + valueOf(name : String) : Event {static} + + values() : Event[] {static} + } + abstract class EventEmitter { + - observers : List + + EventEmitter() + + EventEmitter(obs : EventObserver) + # notifyObservers(e : Event) + + registerObserver(obs : EventObserver) + + timePasses(Weekday) {abstract} + } + interface EventObserver { + + onEvent(Event) {abstract} + } + class KingJoffrey { + - LOGGER : Logger {static} + + KingJoffrey() + + onEvent(e : Event) + } + class KingsHand { + + KingsHand() + + KingsHand(obs : EventObserver) + + onEvent(e : Event) + + timePasses(day : Weekday) + } + class LordBaelish { + + LordBaelish() + + LordBaelish(obs : EventObserver) + + timePasses(day : Weekday) + } + class LordVarys { + + LordVarys() + + LordVarys(obs : EventObserver) + + timePasses(day : Weekday) + } + class Scout { + + Scout() + + Scout(obs : EventObserver) + + timePasses(day : Weekday) + } + enum Weekday { + + FRIDAY {static} + + MONDAY {static} + + SATURDAY {static} + + SUNDAY {static} + + THURSDAY {static} + + TUESDAY {static} + + WEDNESDAY {static} + - description : String + + toString() : String + + valueOf(name : String) : Weekday {static} + + values() : Weekday[] {static} + } +} +EventEmitter --> "-observers" EventObserver +KingJoffrey ..|> EventObserver +KingsHand ..|> EventObserver +KingsHand --|> EventEmitter +LordBaelish --|> EventEmitter +LordVarys --|> EventEmitter +Scout --|> EventEmitter +@enduml \ No newline at end of file diff --git a/event-aggregator/pom.xml b/event-aggregator/pom.xml index a39738bf809a..3e7e58120155 100644 --- a/event-aggregator/pom.xml +++ b/event-aggregator/pom.xml @@ -1,7 +1,10 @@ + - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - event-aggregator - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.mockito - mockito-core - test - - + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + event-aggregator + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.event.aggregator.App + + + + + + + + diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java index 2c489ff5b002..4b5e9a615cbf 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,45 +24,53 @@ */ package com.iluwatar.event.aggregator; -import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.function.Consumer; /** - * * A system with lots of objects can lead to complexities when a client wants to subscribe to * events. The client has to find and register for each object individually, if each object has * multiple events then each event requires a separate subscription. - *

    - * An Event Aggregator acts as a single source of events for many objects. It registers for all the - * events of the many objects allowing clients to register with just the aggregator. - *

    - * In the example {@link LordBaelish}, {@link LordVarys} and {@link Scout} deliver events to - * {@link KingsHand}. {@link KingsHand}, the event aggregator, then delivers the events to - * {@link KingJoffrey}. * + *

    An Event Aggregator acts as a single source of events for many objects. It registers for all + * the events of the many objects allowing clients to register with just the aggregator. + * + *

    In the example {@link LordBaelish}, {@link LordVarys} and {@link Scout} deliver events to + * {@link KingsHand}. {@link KingsHand}, the event aggregator, then delivers the events to {@link + * KingJoffrey}. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - KingJoffrey kingJoffrey = new KingJoffrey(); - KingsHand kingsHand = new KingsHand(kingJoffrey); + var kingJoffrey = new KingJoffrey(); + + var kingsHand = new KingsHand(); + kingsHand.registerObserver(kingJoffrey, Event.TRAITOR_DETECTED); + kingsHand.registerObserver(kingJoffrey, Event.STARK_SIGHTED); + kingsHand.registerObserver(kingJoffrey, Event.WARSHIPS_APPROACHING); + kingsHand.registerObserver(kingJoffrey, Event.WHITE_WALKERS_SIGHTED); + + var varys = new LordVarys(); + varys.registerObserver(kingsHand, Event.TRAITOR_DETECTED); + varys.registerObserver(kingsHand, Event.WHITE_WALKERS_SIGHTED); + + var scout = new Scout(); + scout.registerObserver(kingsHand, Event.WARSHIPS_APPROACHING); + scout.registerObserver(varys, Event.WHITE_WALKERS_SIGHTED); + + var baelish = new LordBaelish(kingsHand, Event.STARK_SIGHTED); - List emitters = new ArrayList<>(); - emitters.add(kingsHand); - emitters.add(new LordBaelish(kingsHand)); - emitters.add(new LordVarys(kingsHand)); - emitters.add(new Scout(kingsHand)); + var emitters = List.of(kingsHand, baelish, varys, scout); - for (Weekday day : Weekday.values()) { - for (EventEmitter emitter : emitters) { - emitter.timePasses(day); - } - } + Arrays.stream(Weekday.values()) + .>map(day -> emitter -> emitter.timePasses(day)) + .forEachOrdered(emitters::forEach); } } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java index daa3a9674031..87b1f5eafa22 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,22 +24,19 @@ */ package com.iluwatar.event.aggregator; -/** - * - * Event enumeration. - * - */ -public enum Event { +import lombok.RequiredArgsConstructor; - STARK_SIGHTED("Stark sighted"), WARSHIPS_APPROACHING("Warships approaching"), TRAITOR_DETECTED( - "Traitor detected"); - - private String description; +/** Event enumeration. */ +@RequiredArgsConstructor +public enum Event { + WHITE_WALKERS_SIGHTED("White walkers sighted"), + STARK_SIGHTED("Stark sighted"), + WARSHIPS_APPROACHING("Warships approaching"), + TRAITOR_DETECTED("Traitor detected"); - Event(String description) { - this.description = description; - } + private final String description; + @Override public String toString() { return description; } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java index af19727b2959..ccff62740db7 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,34 +24,43 @@ */ package com.iluwatar.event.aggregator; +import java.util.HashMap; import java.util.LinkedList; import java.util.List; +import java.util.Map; -/** - * - * EventEmitter is the base class for event producers that can be observed. - * - */ +/** EventEmitter is the base class for event producers that can be observed. */ public abstract class EventEmitter { - private List observers; + private final Map> observerLists; public EventEmitter() { - observers = new LinkedList<>(); + observerLists = new HashMap<>(); } - public EventEmitter(EventObserver obs) { + public EventEmitter(EventObserver obs, Event e) { this(); - registerObserver(obs); + registerObserver(obs, e); } - public final void registerObserver(EventObserver obs) { - observers.add(obs); + /** + * Registers observer for specific event in the related list. + * + * @param obs the observer that observers this emitter + * @param e the specific event for that observation occurs + */ + public final void registerObserver(EventObserver obs, Event e) { + if (!observerLists.containsKey(e)) { + observerLists.put(e, new LinkedList<>()); + } + if (!observerLists.get(e).contains(obs)) { + observerLists.get(e).add(obs); + } } protected void notifyObservers(Event e) { - for (EventObserver obs : observers) { - obs.onEvent(e); + if (observerLists.containsKey(e)) { + observerLists.get(e).forEach(observer -> observer.onEvent(e)); } } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java index e88d571fbf70..2db98f93982b 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,13 +24,8 @@ */ package com.iluwatar.event.aggregator; -/** - * - * Observers of events implement this interface. - * - */ +/** Observers of events implement this interface. */ public interface EventObserver { void onEvent(Event e); - } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java index 9e341f1c78fd..90036f664ab7 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.event.aggregator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * KingJoffrey observes events from {@link KingsHand}. - * - */ +/** KingJoffrey observes events from {@link KingsHand}. */ +@Slf4j public class KingJoffrey implements EventObserver { - private static final Logger LOGGER = LoggerFactory.getLogger(KingJoffrey.class); - @Override public void onEvent(Event e) { LOGGER.info("Received event from the King's Hand: {}", e.toString()); diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java index 0d4f6af2da30..c9089a68fdda 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,13 @@ */ package com.iluwatar.event.aggregator; -/** - * - * KingsHand observes events from multiple sources and delivers them to listeners. - * - */ +/** KingsHand observes events from multiple sources and delivers them to listeners. */ public class KingsHand extends EventEmitter implements EventObserver { - public KingsHand() { - } + public KingsHand() {} - public KingsHand(EventObserver obs) { - super(obs); + public KingsHand(EventObserver obs, Event e) { + super(obs, e); } @Override @@ -43,6 +40,8 @@ public void onEvent(Event e) { @Override public void timePasses(Weekday day) { - // NOP + // This method is intentionally left empty because KingsHand does not handle time-based events + // directly. + // It serves as a placeholder to fulfill the EventObserver interface contract. } } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java index 50b7d501a799..f133a774d89a 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,23 +24,18 @@ */ package com.iluwatar.event.aggregator; -/** - * - * LordBaelish produces events. - * - */ +/** LordBaelish produces events. */ public class LordBaelish extends EventEmitter { - public LordBaelish() { - } + public LordBaelish() {} - public LordBaelish(EventObserver obs) { - super(obs); + public LordBaelish(EventObserver obs, Event e) { + super(obs, e); } @Override public void timePasses(Weekday day) { - if (day.equals(Weekday.FRIDAY)) { + if (day == Weekday.FRIDAY) { notifyObservers(Event.STARK_SIGHTED); } } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java index 6248c44469d3..5472e2288496 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,24 +24,27 @@ */ package com.iluwatar.event.aggregator; -/** - * - * LordVarys produces events. - * - */ -public class LordVarys extends EventEmitter { +import lombok.extern.slf4j.Slf4j; - public LordVarys() { - } +/** LordVarys produces events. */ +@Slf4j +public class LordVarys extends EventEmitter implements EventObserver { - public LordVarys(EventObserver obs) { - super(obs); + public LordVarys() {} + + public LordVarys(EventObserver obs, Event e) { + super(obs, e); } @Override public void timePasses(Weekday day) { - if (day.equals(Weekday.SATURDAY)) { + if (day == Weekday.SATURDAY) { notifyObservers(Event.TRAITOR_DETECTED); } } + + @Override + public void onEvent(Event e) { + notifyObservers(e); + } } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java index a1095640a4bf..d1566571a465 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,24 +24,22 @@ */ package com.iluwatar.event.aggregator; -/** - * - * Scout produces events. - * - */ +/** Scout produces events. */ public class Scout extends EventEmitter { - public Scout() { - } + public Scout() {} - public Scout(EventObserver obs) { - super(obs); + public Scout(EventObserver obs, Event e) { + super(obs, e); } @Override public void timePasses(Weekday day) { - if (day.equals(Weekday.TUESDAY)) { + if (day == Weekday.TUESDAY) { notifyObservers(Event.WARSHIPS_APPROACHING); } + if (day == Weekday.WEDNESDAY) { + notifyObservers(Event.WHITE_WALKERS_SIGHTED); + } } } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java index 2072e227c838..b232ad54b563 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,22 +24,22 @@ */ package com.iluwatar.event.aggregator; -/** - * - * Weekday enumeration - * - */ -public enum Weekday { +import lombok.RequiredArgsConstructor; - MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY( - "Friday"), SATURDAY("Saturday"), SUNDAY("Sunday"); - - private String description; +/** Weekday enumeration. */ +@RequiredArgsConstructor +public enum Weekday { + MONDAY("Monday"), + TUESDAY("Tuesday"), + WEDNESDAY("Wednesday"), + THURSDAY("Thursday"), + FRIDAY("Friday"), + SATURDAY("Saturday"), + SUNDAY("Sunday"); - Weekday(String description) { - this.description = description; - } + private final String description; + @Override public String toString() { return description; } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java index 09548e38433d..2ccd559a832e 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,19 @@ */ package com.iluwatar.event.aggregator; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java index c2f457e28ff2..bfc00e6cd88a 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,53 +24,44 @@ */ package com.iluwatar.event.aggregator; -import org.junit.jupiter.api.Test; - -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; import java.util.Objects; -import java.util.function.Function; +import java.util.function.BiFunction; import java.util.function.Supplier; +import org.junit.jupiter.api.Test; /** - * Date: 12/12/15 - 10:58 PM * Tests for Event Emitter + * * @param Type of Event Emitter - * @author Jeroen Meulemeester */ -public abstract class EventEmitterTest { +abstract class EventEmitterTest { - /** - * Factory used to create a new instance of the test object with a default observer - */ - private final Function factoryWithDefaultObserver; + /** Factory used to create a new instance of the test object with a default observer */ + private final BiFunction factoryWithDefaultObserver; - /** - * Factory used to create a new instance of the test object without passing a default observer - */ + /** Factory used to create a new instance of the test object without passing a default observer */ private final Supplier factoryWithoutDefaultObserver; - /** - * The day of the week an event is expected - */ + /** The day of the week an event is expected */ private final Weekday specialDay; - /** - * The expected event, emitted on the special day - */ + /** The expected event, emitted on the special day */ private final Event event; /** * Create a new event emitter test, using the given test object factories, special day and event */ - EventEmitterTest(final Weekday specialDay, final Event event, - final Function factoryWithDefaultObserver, - final Supplier factoryWithoutDefaultObserver) { + EventEmitterTest( + final Weekday specialDay, + final Event event, + final BiFunction factoryWithDefaultObserver, + final Supplier factoryWithoutDefaultObserver) { this.specialDay = specialDay; this.event = event; @@ -81,7 +74,7 @@ public abstract class EventEmitterTest { * is executed twice, once without a default emitter and once with */ @Test - public void testAllDays() { + void testAllDays() { testAllDaysWithoutDefaultObserver(specialDay, event); testAllDaysWithDefaultObserver(specialDay, event); } @@ -91,25 +84,28 @@ public void testAllDays() { * received the correct event on the special day. * * @param specialDay The special day on which an event is emitted - * @param event The expected event emitted by the test object - * @param emitter The event emitter - * @param observers The registered observer mocks + * @param event The expected event emitted by the test object + * @param emitter The event emitter + * @param observers The registered observer mocks */ - private void testAllDays(final Weekday specialDay, final Event event, final E emitter, - final EventObserver... observers) { + private void testAllDays( + final Weekday specialDay, + final Event event, + final E emitter, + final EventObserver... observers) { - for (final Weekday weekday : Weekday.values()) { + for (final var weekday : Weekday.values()) { // Pass each week of the day, day by day to the event emitter emitter.timePasses(weekday); if (weekday == specialDay) { // On a special day, every observer should have received the event - for (final EventObserver observer : observers) { + for (final var observer : observers) { verify(observer, times(1)).onEvent(eq(event)); } } else { // On any other normal day, the observers should have received nothing at all - verifyZeroInteractions(observers); + verifyNoMoreInteractions(observers); } } @@ -122,15 +118,15 @@ private void testAllDays(final Weekday specialDay, final Event event, final E em * event emitter without a default observer * * @param specialDay The special day on which an event is emitted - * @param event The expected event emitted by the test object + * @param event The expected event emitted by the test object */ private void testAllDaysWithoutDefaultObserver(final Weekday specialDay, final Event event) { - final EventObserver observer1 = mock(EventObserver.class); - final EventObserver observer2 = mock(EventObserver.class); + final var observer1 = mock(EventObserver.class); + final var observer2 = mock(EventObserver.class); - final E emitter = this.factoryWithoutDefaultObserver.get(); - emitter.registerObserver(observer1); - emitter.registerObserver(observer2); + final var emitter = this.factoryWithoutDefaultObserver.get(); + emitter.registerObserver(observer1, event); + emitter.registerObserver(observer2, event); testAllDays(specialDay, event, emitter, observer1, observer2); } @@ -139,18 +135,17 @@ private void testAllDaysWithoutDefaultObserver(final Weekday specialDay, final E * Go over every day of the month, and check if the event is emitted on the given day. * * @param specialDay The special day on which an event is emitted - * @param event The expected event emitted by the test object + * @param event The expected event emitted by the test object */ private void testAllDaysWithDefaultObserver(final Weekday specialDay, final Event event) { - final EventObserver defaultObserver = mock(EventObserver.class); - final EventObserver observer1 = mock(EventObserver.class); - final EventObserver observer2 = mock(EventObserver.class); + final var defaultObserver = mock(EventObserver.class); + final var observer1 = mock(EventObserver.class); + final var observer2 = mock(EventObserver.class); - final E emitter = this.factoryWithDefaultObserver.apply(defaultObserver); - emitter.registerObserver(observer1); - emitter.registerObserver(observer2); + final var emitter = this.factoryWithDefaultObserver.apply(defaultObserver, event); + emitter.registerObserver(observer1, event); + emitter.registerObserver(observer2, event); testAllDays(specialDay, event, emitter, defaultObserver, observer1, observer2); } - } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java index 28062c613ed1..20c3c489925f 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,28 +24,24 @@ */ package com.iluwatar.event.aggregator; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; -/** - * Date: 12/12/15 - 2:52 PM - * - * @author Jeroen Meulemeester - */ -public class EventTest { +import java.util.Arrays; +import org.junit.jupiter.api.Test; - /** - * Verify if every event has a non-null, non-empty description - */ +/** EventTest */ +class EventTest { + + /** Verify if every event has a non-null, non-empty description */ @Test - public void testToString() { - for (final Event event : Event.values()) { - final String toString = event.toString(); - assertNotNull(toString); - assertFalse(toString.trim().isEmpty()); - } + void testToString() { + Arrays.stream(Event.values()) + .map(Event::toString) + .forEach( + toString -> { + assertNotNull(toString); + assertFalse(toString.trim().isEmpty()); + }); } - -} \ No newline at end of file +} diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java index 3f3296c575e3..aa689a34e9c5 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,61 +24,55 @@ */ package com.iluwatar.event.aggregator; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.IntStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Date: 12/12/15 - 3:04 PM - * - * @author Jeroen Meulemeester - */ -public class KingJoffreyTest { +/** KingJoffreyTest */ +class KingJoffreyTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(KingJoffrey.class); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } - /** - * Test if {@link KingJoffrey} tells us what event he received - */ + /** Test if {@link KingJoffrey} tells us what event he received */ @Test - public void testOnEvent() { - final KingJoffrey kingJoffrey = new KingJoffrey(); - - for (int i = 0; i < Event.values().length; ++i) { - assertEquals(i, appender.getLogSize()); - Event event = Event.values()[i]; - kingJoffrey.onEvent(event); - - final String expectedMessage = "Received event from the King's Hand: " + event.toString(); - assertEquals(expectedMessage, appender.getLastMessage()); - assertEquals(i + 1, appender.getLogSize()); - } - + void testOnEvent() { + final var kingJoffrey = new KingJoffrey(); + + IntStream.range(0, Event.values().length) + .forEach( + i -> { + assertEquals(i, appender.getLogSize()); + var event = Event.values()[i]; + kingJoffrey.onEvent(event); + final var expectedMessage = "Received event from the King's Hand: " + event; + assertEquals(expectedMessage, appender.getLastMessage()); + assertEquals(i + 1, appender.getLogSize()); + }); } - private class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); + private static class InMemoryAppender extends AppenderBase { + private final List log = new LinkedList<>(); - public InMemoryAppender(Class clazz) { + public InMemoryAppender(Class clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } @@ -94,5 +90,4 @@ public int getLogSize() { return log.size(); } } - } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java index 3a5ae8f68f22..e06a50fc80b9 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,49 +24,47 @@ */ package com.iluwatar.event.aggregator; -import org.junit.jupiter.api.Test; - -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -/** - * Date: 12/12/15 - 10:57 AM - * - * @author Jeroen Meulemeester - */ -public class KingsHandTest extends EventEmitterTest { +import java.util.Arrays; +import org.junit.jupiter.api.Test; - /** - * Create a new test instance, using the correct object factory - */ +/** KingsHandTest */ +class KingsHandTest extends EventEmitterTest { + + /** Create a new test instance, using the correct object factory */ public KingsHandTest() { super(null, null, KingsHand::new, KingsHand::new); } /** - * The {@link KingsHand} is both an {@link EventEmitter} as an {@link EventObserver} so verify if every - * event received is passed up to it's superior, in most cases {@link KingJoffrey} but now just a - * mocked observer. + * The {@link KingsHand} is both an {@link EventEmitter} as an {@link EventObserver} so verify if + * every event received is passed up to its superior, in most cases {@link KingJoffrey} but now + * just a mocked observer. */ @Test - public void testPassThrough() throws Exception { - final EventObserver observer = mock(EventObserver.class); - final KingsHand kingsHand = new KingsHand(observer); + void testPassThrough() { + final var observer = mock(EventObserver.class); + final var kingsHand = new KingsHand(); + kingsHand.registerObserver(observer, Event.STARK_SIGHTED); + kingsHand.registerObserver(observer, Event.WARSHIPS_APPROACHING); + kingsHand.registerObserver(observer, Event.TRAITOR_DETECTED); + kingsHand.registerObserver(observer, Event.WHITE_WALKERS_SIGHTED); // The kings hand should not pass any events before he received one - verifyZeroInteractions(observer); + verifyNoMoreInteractions(observer); // Verify if each event is passed on to the observer, nothing less, nothing more. - for (final Event event : Event.values()) { - kingsHand.onEvent(event); - verify(observer, times(1)).onEvent(eq(event)); - verifyNoMoreInteractions(observer); - } - + Arrays.stream(Event.values()) + .forEach( + event -> { + kingsHand.onEvent(event); + verify(observer, times(1)).onEvent(eq(event)); + verifyNoMoreInteractions(observer); + }); } - -} \ No newline at end of file +} diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordBaelishTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordBaelishTest.java index 5042c8f8d00b..c90ccd993317 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordBaelishTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordBaelishTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,11 @@ */ package com.iluwatar.event.aggregator; -/** - * Date: 12/12/15 - 10:57 AM - * - * @author Jeroen Meulemeester - */ -public class LordBaelishTest extends EventEmitterTest { +/** LordBaelishTest */ +class LordBaelishTest extends EventEmitterTest { - /** - * Create a new test instance, using the correct object factory - */ + /** Create a new test instance, using the correct object factory */ public LordBaelishTest() { super(Weekday.FRIDAY, Event.STARK_SIGHTED, LordBaelish::new, LordBaelish::new); } - -} \ No newline at end of file +} diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordVarysTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordVarysTest.java index 7af5d9be8f19..5ddd0a65e26f 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordVarysTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordVarysTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,11 @@ */ package com.iluwatar.event.aggregator; -/** - * Date: 12/12/15 - 10:57 AM - * - * @author Jeroen Meulemeester - */ -public class LordVarysTest extends EventEmitterTest { +/** LordVarysTest */ +class LordVarysTest extends EventEmitterTest { - /** - * Create a new test instance, using the correct object factory - */ + /** Create a new test instance, using the correct object factory */ public LordVarysTest() { super(Weekday.SATURDAY, Event.TRAITOR_DETECTED, LordVarys::new, LordVarys::new); } - -} \ No newline at end of file +} diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java index 87ed209d472a..b6f86123e45c 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.event.aggregator; -/** - * Date: 12/12/15 - 10:57 AM - * - * @author Jeroen Meulemeester - */ -public class ScoutTest extends EventEmitterTest { +/** ScoutTest */ +class ScoutTest extends EventEmitterTest { - /** - * Create a new test instance, using the correct object factory - */ + /** Create a new test instance, using the correct object factory */ public ScoutTest() { + super(Weekday.TUESDAY, Event.WARSHIPS_APPROACHING, Scout::new, Scout::new); } - -} \ No newline at end of file +} diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java index df2d8ac79549..e078951e4eb4 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,25 +24,23 @@ */ package com.iluwatar.event.aggregator; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -/** - * Date: 12/12/15 - 2:12 PM - * - * @author Jeroen Meulemeester - */ -public class WeekdayTest { +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +/** WeekdayTest */ +class WeekdayTest { @Test - public void testToString() throws Exception { - for (final Weekday weekday : Weekday.values()) { - final String toString = weekday.toString(); - assertNotNull(toString); - assertEquals(weekday.name(), toString.toUpperCase()); - } + void testToString() { + Arrays.stream(Weekday.values()) + .forEach( + weekday -> { + final String toString = weekday.toString(); + assertNotNull(toString); + assertEquals(weekday.name(), toString.toUpperCase()); + }); } - -} \ No newline at end of file +} diff --git a/event-asynchronous/README.md b/event-asynchronous/README.md deleted file mode 100644 index 4c26e0a3caa6..000000000000 --- a/event-asynchronous/README.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -layout: pattern -title: Event-based Asynchronous -folder: event-asynchronous -permalink: /patterns/event-asynchronous/ -categories: Concurrency -tags: - - difficulty-intermediate - - performance - - Java ---- - -## Intent -The Event-based Asynchronous Pattern makes available the advantages of multithreaded applications while hiding many -of the complex issues inherent in multithreaded design. Using a class that supports this pattern can allow you to: - -1. Perform time-consuming tasks, such as downloads and database operations, "in the background," without interrupting your application. -2. Execute multiple operations simultaneously, receiving notifications when each completes. -3. Wait for resources to become available without stopping ("hanging") your application. -4. Communicate with pending asynchronous operations using the familiar events-and-delegates model. - -![alt text](./etc/event-asynchronous.png "Event-based Asynchronous") - -## Applicability -Use the Event-based Asynchronous pattern(s) when - -* Time-consuming tasks are needed to run in the background without disrupting the current application. - -## Credits - -* [Event-based Asynchronous Pattern Overview](https://msdn.microsoft.com/en-us/library/wewwczdw%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) diff --git a/event-asynchronous/pom.xml b/event-asynchronous/pom.xml deleted file mode 100644 index 9398d25ce6ab..000000000000 --- a/event-asynchronous/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - event-asynchronous - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java deleted file mode 100644 index 6e9138d3c518..000000000000 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java +++ /dev/null @@ -1,211 +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.event.asynchronous; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.Scanner; - -/** - * - * This application demonstrates the Event-based Asynchronous pattern. Essentially, users (of the pattern) may - * choose to run events in an Asynchronous or Synchronous mode. There can be multiple Asynchronous events running at - * once but only one Synchronous event can run at a time. Asynchronous events are synonymous to multi-threads. The key - * point here is that the threads run in the background and the user is free to carry on with other processes. Once an - * event is complete, the appropriate listener/callback method will be called. The listener then proceeds to carry out - * further processing depending on the needs of the user. - * - * The {@link EventManager} manages the events/threads that the user creates. Currently, the supported event operations - * are: start, stop, getStatus. For Synchronous events, the user is unable to - * start another (Synchronous) event if one is already running at the time. The running event would have to either be - * stopped or completed before a new event can be started. - * - * The Event-based Asynchronous Pattern makes available the advantages of multithreaded applications while hiding many - * of the complex issues inherent in multithreaded design. Using a class that supports this pattern can allow you to:- - * (1) Perform time-consuming tasks, such as downloads and database operations, "in the background," without - * interrupting your application. (2) Execute multiple operations simultaneously, receiving notifications when each - * completes. (3) Wait for resources to become available without stopping ("hanging") your application. (4) Communicate - * with pending asynchronous operations using the familiar events-and-delegates model. - * - * @see EventManager - * @see Event - * - */ -public class App { - - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - public static final String PROP_FILE_NAME = "config.properties"; - - boolean interactiveMode = false; - - /** - * Program entry point. - * - * @param args command line args - */ - public static void main(String[] args) { - App app = new App(); - - app.setUp(); - app.run(); - } - - /** - * App can run in interactive mode or not. Interactive mode == Allow user interaction with command line. - * Non-interactive is a quick sequential run through the available {@link EventManager} operations. - */ - public void setUp() { - Properties prop = new Properties(); - - InputStream inputStream = App.class.getClassLoader().getResourceAsStream(PROP_FILE_NAME); - - if (inputStream != null) { - try { - prop.load(inputStream); - } catch (IOException e) { - LOGGER.error("{} was not found. Defaulting to non-interactive mode.", PROP_FILE_NAME, e); - } - String property = prop.getProperty("INTERACTIVE_MODE"); - if (property.equalsIgnoreCase("YES")) { - interactiveMode = true; - } - } - } - - /** - * Run program in either interactive mode or not. - */ - public void run() { - if (interactiveMode) { - runInteractiveMode(); - } else { - quickRun(); - } - } - - /** - * Run program in non-interactive mode. - */ - public void quickRun() { - EventManager eventManager = new EventManager(); - - try { - // Create an Asynchronous event. - int aEventId = eventManager.createAsync(60); - LOGGER.info("Async Event [{}] has been created.", aEventId); - eventManager.start(aEventId); - LOGGER.info("Async Event [{}] has been started.", aEventId); - - // Create a Synchronous event. - int sEventId = eventManager.create(60); - LOGGER.info("Sync Event [{}] has been created.", sEventId); - eventManager.start(sEventId); - LOGGER.info("Sync Event [{}] has been started.", sEventId); - - eventManager.status(aEventId); - eventManager.status(sEventId); - - eventManager.cancel(aEventId); - LOGGER.info("Async Event [{}] has been stopped.", aEventId); - eventManager.cancel(sEventId); - LOGGER.info("Sync Event [{}] has been stopped.", sEventId); - - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException - | InvalidOperationException e) { - LOGGER.error(e.getMessage()); - } - } - - /** - * Run program in interactive mode. - */ - public void runInteractiveMode() { - EventManager eventManager = new EventManager(); - - Scanner s = new Scanner(System.in); - int option = -1; - while (option != 4) { - LOGGER.info("Hello. Would you like to boil some eggs?"); - LOGGER.info("(1) BOIL AN EGG \n(2) STOP BOILING THIS EGG \n(3) HOW ARE MY EGGS? \n(4) EXIT"); - LOGGER.info("Choose [1,2,3,4]: "); - option = s.nextInt(); - - if (option == 1) { - s.nextLine(); - LOGGER.info("Boil multiple eggs at once (A) or boil them one-by-one (S)?: "); - String eventType = s.nextLine(); - LOGGER.info("How long should this egg be boiled for (in seconds)?: "); - int eventTime = s.nextInt(); - if (eventType.equalsIgnoreCase("A")) { - try { - int eventId = eventManager.createAsync(eventTime); - eventManager.start(eventId); - LOGGER.info("Egg [{}] is being boiled.", eventId); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } - } else if (eventType.equalsIgnoreCase("S")) { - try { - int eventId = eventManager.create(eventTime); - eventManager.start(eventId); - LOGGER.info("Egg [{}] is being boiled.", eventId); - } catch (MaxNumOfEventsAllowedException | InvalidOperationException | LongRunningEventException - | EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } - } else { - LOGGER.info("Unknown event type."); - } - } else if (option == 2) { - LOGGER.info("Which egg?: "); - int eventId = s.nextInt(); - try { - eventManager.cancel(eventId); - LOGGER.info("Egg [{}] is removed from boiler.", eventId); - } catch (EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } - } else if (option == 3) { - s.nextLine(); - LOGGER.info("Just one egg (O) OR all of them (A) ?: "); - String eggChoice = s.nextLine(); - - if (eggChoice.equalsIgnoreCase("O")) { - LOGGER.info("Which egg?: "); - int eventId = s.nextInt(); - try { - eventManager.status(eventId); - } catch (EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } - } else if (eggChoice.equalsIgnoreCase("A")) { - eventManager.statusOfAllEvents(); - } - } else if (option == 4) { - eventManager.shutdown(); - } - } - - s.close(); - } - -} diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java deleted file mode 100644 index 5dc069bc7032..000000000000 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java +++ /dev/null @@ -1,106 +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.event.asynchronous; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Each Event runs as a separate/individual thread. - * - */ -public class Event implements IEvent, Runnable { - - private static final Logger LOGGER = LoggerFactory.getLogger(Event.class); - - private int eventId; - private int eventTime; - private boolean isSynchronous; - private Thread thread; - private boolean isComplete = false; - private ThreadCompleteListener eventListener; - - /** - * - * @param eventId event ID - * @param eventTime event time - * @param isSynchronous is of synchronous type - */ - public Event(final int eventId, final int eventTime, final boolean isSynchronous) { - this.eventId = eventId; - this.eventTime = eventTime; - this.isSynchronous = isSynchronous; - } - - public boolean isSynchronous() { - return isSynchronous; - } - - @Override - public void start() { - thread = new Thread(this); - thread.start(); - } - - @Override - public void stop() { - if (null == thread) { - return; - } - thread.interrupt(); - } - - @Override - public void status() { - if (!isComplete) { - LOGGER.info("[{}] is not done.", eventId); - } else { - LOGGER.info("[{}] is done.", eventId); - } - } - - @Override - public void run() { - long currentTime = System.currentTimeMillis(); - long endTime = currentTime + (eventTime * 1000); - while (System.currentTimeMillis() < endTime) { - try { - Thread.sleep(1000); // Sleep for 1 second. - } catch (InterruptedException e) { - return; - } - } - isComplete = true; - completed(); - } - - public final void addListener(final ThreadCompleteListener listener) { - this.eventListener = listener; - } - - public final void removeListener(final ThreadCompleteListener listener) { - this.eventListener = null; - } - - private final void completed() { - if (eventListener != null) { - eventListener.completedEventHandler(eventId); - } - } - -} diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java deleted file mode 100644 index e7a5e75b6d4b..000000000000 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java +++ /dev/null @@ -1,29 +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.event.asynchronous; - -/** - * Custom Exception Class for Non Existent Event - */ -public class EventDoesNotExistException extends Exception { - - private static final long serialVersionUID = -3398463738273811509L; - - public EventDoesNotExistException(String message) { - super(message); - } -} diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java deleted file mode 100644 index 729900620aa0..000000000000 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java +++ /dev/null @@ -1,218 +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.event.asynchronous; - -import java.util.Iterator; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.ConcurrentHashMap; - -/** - * - * EventManager handles and maintains a pool of event threads. {@link Event} threads are created upon user request. Thre - * are two types of events; Asynchronous and Synchronous. There can be multiple Asynchronous events running at once but - * only one Synchronous event running at a time. Currently supported event operations are: start, stop, and getStatus. - * Once an event is complete, it then notifies EventManager through a listener. The EventManager then takes the event - * out of the pool. - * - */ -public class EventManager implements ThreadCompleteListener { - - public static final int MAX_RUNNING_EVENTS = 1000; // Just don't wanna have too many running events. :) - public static final int MIN_ID = 1; - public static final int MAX_ID = MAX_RUNNING_EVENTS; - public static final int MAX_EVENT_TIME = 1800; // in seconds / 30 minutes. - private int currentlyRunningSyncEvent = -1; - private Random rand; - private Map eventPool; - - /** - * EventManager constructor. - * - */ - public EventManager() { - rand = new Random(1); - eventPool = new ConcurrentHashMap(MAX_RUNNING_EVENTS); - - } - - /** - * Create a Synchronous event. - * - * @param eventTime Time an event should run for. - * @return eventId - * @throws MaxNumOfEventsAllowedException When too many events are running at a time. - * @throws InvalidOperationException No new synchronous events can be created when one is already running. - * @throws LongRunningEventException Long running events are not allowed in the app. - */ - public int create(int eventTime) - throws MaxNumOfEventsAllowedException, InvalidOperationException, LongRunningEventException { - if (currentlyRunningSyncEvent != -1) { - throw new InvalidOperationException( - "Event [" + currentlyRunningSyncEvent + "] is still running. Please wait until it finishes and try again."); - } - - int eventId = createEvent(eventTime, true); - currentlyRunningSyncEvent = eventId; - - return eventId; - } - - /** - * Create an Asynchronous event. - * - * @param eventTime Time an event should run for. - * @return eventId - * @throws MaxNumOfEventsAllowedException When too many events are running at a time. - * @throws LongRunningEventException Long running events are not allowed in the app. - */ - public int createAsync(int eventTime) throws MaxNumOfEventsAllowedException, LongRunningEventException { - return createEvent(eventTime, false); - } - - private int createEvent(int eventTime, boolean isSynchronous) - throws MaxNumOfEventsAllowedException, LongRunningEventException { - if (eventPool.size() == MAX_RUNNING_EVENTS) { - throw new MaxNumOfEventsAllowedException("Too many events are running at the moment. Please try again later."); - } - - if (eventTime >= MAX_EVENT_TIME) { - throw new LongRunningEventException( - "Maximum event time allowed is " + MAX_EVENT_TIME + " seconds. Please try again."); - } - - int newEventId = generateId(); - - Event newEvent = new Event(newEventId, eventTime, isSynchronous); - newEvent.addListener(this); - eventPool.put(newEventId, newEvent); - - return newEventId; - } - - /** - * Starts event. - * - * @param eventId The event that needs to be started. - * @throws EventDoesNotExistException If event does not exist in our eventPool. - */ - public void start(int eventId) throws EventDoesNotExistException { - if (!eventPool.containsKey(eventId)) { - throw new EventDoesNotExistException(eventId + " does not exist."); - } - - eventPool.get(eventId).start(); - } - - /** - * Stops event. - * - * @param eventId The event that needs to be stopped. - * @throws EventDoesNotExistException If event does not exist in our eventPool. - */ - public void cancel(int eventId) throws EventDoesNotExistException { - if (!eventPool.containsKey(eventId)) { - throw new EventDoesNotExistException(eventId + " does not exist."); - } - - if (eventId == currentlyRunningSyncEvent) { - currentlyRunningSyncEvent = -1; - } - - eventPool.get(eventId).stop(); - eventPool.remove(eventId); - } - - /** - * Get status of a running event. - * - * @param eventId The event to inquire status of. - * @throws EventDoesNotExistException If event does not exist in our eventPool. - */ - public void status(int eventId) throws EventDoesNotExistException { - if (!eventPool.containsKey(eventId)) { - throw new EventDoesNotExistException(eventId + " does not exist."); - } - - eventPool.get(eventId).status(); - } - - /** - * Gets status of all running events. - */ - @SuppressWarnings("rawtypes") - public void statusOfAllEvents() { - Iterator it = eventPool.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry pair = (Map.Entry) it.next(); - ((Event) pair.getValue()).status(); - } - } - - /** - * Stop all running events. - */ - @SuppressWarnings("rawtypes") - public void shutdown() { - Iterator it = eventPool.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry pair = (Map.Entry) it.next(); - ((Event) pair.getValue()).stop(); - } - } - - /** - * Returns a pseudo-random number between min and max, inclusive. The difference between min and max can be at most - * Integer.MAX_VALUE - 1. - */ - private int generateId() { - // nextInt is normally exclusive of the top value, - // so add 1 to make it inclusive - int randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID; - while (eventPool.containsKey(randomNum)) { - randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID; - } - - return randomNum; - } - - /** - * Callback from an {@link Event} (once it is complete). The Event is then removed from the pool. - */ - @Override - public void completedEventHandler(int eventId) { - eventPool.get(eventId).status(); - if (eventPool.get(eventId).isSynchronous()) { - currentlyRunningSyncEvent = -1; - } - eventPool.remove(eventId); - } - - /** - * Getter method for event pool. - */ - public Map getEventPool() { - return eventPool; - } - - /** - * Get number of currently running Synchronous events. - */ - public int numOfCurrentlyRunningSyncEvent() { - return currentlyRunningSyncEvent; - } -} diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java deleted file mode 100644 index bfb5d4f0433b..000000000000 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/IEvent.java +++ /dev/null @@ -1,31 +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.event.asynchronous; - -/** - * Events that fulfill the start stop and list out current status behaviour - * follow this interface - */ -public interface IEvent { - - void start(); - - void stop(); - - void status(); - -} diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java deleted file mode 100644 index 7ca5cfc9a6a4..000000000000 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java +++ /dev/null @@ -1,30 +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.event.asynchronous; - -/** - * Type of Exception raised when the Operation being invoked is Invalid - */ -public class InvalidOperationException extends Exception { - - private static final long serialVersionUID = -6191545255213410803L; - - public InvalidOperationException(String message) { - super(message); - } - -} diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java deleted file mode 100644 index b11f1a33597f..000000000000 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java +++ /dev/null @@ -1,29 +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.event.asynchronous; - -/** - * Type of Exception raised when the Operation being invoked is Long Running - */ -public class LongRunningEventException extends Exception { - - private static final long serialVersionUID = -483423544320148809L; - - public LongRunningEventException(String message) { - super(message); - } -} diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java deleted file mode 100644 index 17b46fd882e8..000000000000 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java +++ /dev/null @@ -1,29 +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.event.asynchronous; - -/** - * Type of Exception raised when the max number of allowed events is exceeded - */ -public class MaxNumOfEventsAllowedException extends Exception { - - private static final long serialVersionUID = -8430876973516292695L; - - public MaxNumOfEventsAllowedException(String message) { - super(message); - } -} diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java deleted file mode 100644 index 7a37f7614849..000000000000 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java +++ /dev/null @@ -1,24 +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.event.asynchronous; - -/** - * Interface with listener behaviour related to Thread Completion. - */ -public interface ThreadCompleteListener { - void completedEventHandler(final int eventId); -} diff --git a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java b/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java deleted file mode 100644 index 372bc2f5825c..000000000000 --- a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java +++ /dev/null @@ -1,32 +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.event.asynchronous; - -import org.junit.jupiter.api.Test; - -import java.io.IOException; - -/** - * Tests that EventAsynchronous example runs without errors. - */ -public class AppTest { - @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); - } -} diff --git a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java b/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java deleted file mode 100644 index aa2c644cb5a9..000000000000 --- a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java +++ /dev/null @@ -1,142 +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.event.asynchronous; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * - * Application test - * - */ -public class EventAsynchronousTest { - App app; - - private static final Logger LOGGER = LoggerFactory.getLogger(EventAsynchronousTest.class); - - @BeforeEach - public void setUp() { - app = new App(); - } - - @Test - public void testAsynchronousEvent() { - EventManager eventManager = new EventManager(); - try { - int aEventId = eventManager.createAsync(60); - eventManager.start(aEventId); - assertTrue(eventManager.getEventPool().size() == 1); - assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); - assertTrue(eventManager.numOfCurrentlyRunningSyncEvent() == -1); - eventManager.cancel(aEventId); - assertTrue(eventManager.getEventPool().size() == 0); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } - } - - @Test - public void testSynchronousEvent() { - EventManager eventManager = new EventManager(); - try { - int sEventId = eventManager.create(60); - eventManager.start(sEventId); - assertTrue(eventManager.getEventPool().size() == 1); - assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); - assertTrue(eventManager.numOfCurrentlyRunningSyncEvent() != -1); - eventManager.cancel(sEventId); - assertTrue(eventManager.getEventPool().size() == 0); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException - | InvalidOperationException e) { - LOGGER.error(e.getMessage()); - } - } - - @Test - public void testUnsuccessfulSynchronousEvent() throws InvalidOperationException { - assertThrows(InvalidOperationException.class, () -> { - EventManager eventManager = new EventManager(); - try { - int sEventId = eventManager.create(60); - eventManager.start(sEventId); - sEventId = eventManager.create(60); - eventManager.start(sEventId); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } - }); - } - - @Test - public void testFullSynchronousEvent() { - EventManager eventManager = new EventManager(); - try { - int eventTime = 1; - - int sEventId = eventManager.create(eventTime); - assertTrue(eventManager.getEventPool().size() == 1); - eventManager.start(sEventId); - - long currentTime = System.currentTimeMillis(); - long endTime = currentTime + (eventTime + 2 * 1000); // +2 to give a bit of buffer time for event to - // complete - // properly. - while (System.currentTimeMillis() < endTime) { - } - - assertTrue(eventManager.getEventPool().size() == 0); - - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException - | InvalidOperationException e) { - LOGGER.error(e.getMessage()); - } - } - - @Test - public void testFullAsynchronousEvent() { - EventManager eventManager = new EventManager(); - try { - int eventTime = 1; - - int aEventId1 = eventManager.createAsync(eventTime); - int aEventId2 = eventManager.createAsync(eventTime); - int aEventId3 = eventManager.createAsync(eventTime); - assertTrue(eventManager.getEventPool().size() == 3); - - eventManager.start(aEventId1); - eventManager.start(aEventId2); - eventManager.start(aEventId3); - - long currentTime = System.currentTimeMillis(); - long endTime = currentTime + (eventTime + 2 * 1000); // +2 to give a bit of buffer time for event to complete - // properly. - while (System.currentTimeMillis() < endTime) { - } - - assertTrue(eventManager.getEventPool().size() == 0); - - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } - } -} diff --git a/event-based-asynchronous/README.md b/event-based-asynchronous/README.md new file mode 100644 index 000000000000..6eb885c715e9 --- /dev/null +++ b/event-based-asynchronous/README.md @@ -0,0 +1,187 @@ +--- +title: "Event-Based Asynchronous Pattern in Java: Mastering Non-Blocking System Design" +shortTitle: Event-Based Asynchronous +description: "Explore the best practices and implementations of event-based asynchronous patterns in Java. Enhance your programming skills with our comprehensive guide and real-world examples." +category: Concurrency +language: en +tag: + - Asynchronous + - Decoupling + - Event-driven + - Fault tolerance + - Messaging + - Reactive + - Scalability +--- + +## Also known as + +* Asynchronous Event Handling + +## Intent of Event-Based Asynchronous Design Pattern + +The Event-Based Asynchronous pattern allows a system to handle tasks that might take some time to complete without blocking the execution of the program. It enables better resource utilization by freeing up a thread that would otherwise be blocked waiting for the task to complete. + +## Detailed Explanation of Event-Based Asynchronous Pattern with Real-World Examples + +Real-world example + +> A real-world analogy of the Event-Based Asynchronous design pattern is how a restaurant operates. When a customer places an order, the waiter records the order and passes it to the kitchen. Instead of waiting at the kitchen for the food to be prepared, the waiter continues to serve other tables. Once the kitchen completes the order, they signal (event) the waiter, who then delivers the food to the customer. This allows the waiter to handle multiple tasks efficiently without idle waiting, similar to how asynchronous programming handles tasks in parallel, enhancing overall efficiency and responsiveness. + +In Plain Words + +> The Event-Based Asynchronous design pattern allows tasks to be executed in the background, notifying the main program via events when completed, thereby enhancing system efficiency and responsiveness without blocking ongoing operations. + +Sequence diagram + +![Event-Based Asynchronous sequence diagram](./etc/event-based-asynchronous-sequence-diagram.png) + +## Programmatic Example of Event-Based Asynchronous Pattern in Java + +Event-Based Asynchronous design pattern allows tasks to be executed in the background, notifying the main program via events when completed, thereby enhancing system efficiency and responsiveness without blocking ongoing operations. + +In the provided code, we have several key classes implementing this pattern: + +- `App`: The main class that runs the application. It interacts with the `EventManager` to create, start, stop, and check the status of events. +- `EventManager`: Manages the lifecycle of events, including creating, starting, stopping, and checking the status of events. It maintains a map of event IDs to `Event` objects. +- `Event`: An abstract class that represents an event. It has two concrete subclasses: `AsyncEvent` and `SyncEvent`. +- `AsyncEvent` and `SyncEvent`: Represent asynchronous and synchronous events respectively. +- Custom exceptions: Thrown by the `EventManager` when certain conditions are not met. + +Here's a simplified code example of how these classes interact: + +```java +// Create an EventManager +EventManager eventManager = new EventManager(); + +// Create an asynchronous event that runs for 60 seconds +int asyncEventId = eventManager.createAsync(Duration.ofSeconds(60)); + +// Start the asynchronous event +eventManager.start(asyncEventId); + +// Check the status of the asynchronous event +eventManager.status(asyncEventId); + +// Stop the asynchronous event +eventManager.cancel(asyncEventId); +``` + +In this example, the `App` class creates an `EventManager`, then uses it to create, start, check the status of, and stop an asynchronous event. The `EventManager` creates an `AsyncEvent` object, starts it in a separate thread, checks its status, and stops it when requested. + +The `EventManager` class is the core of the Event-Based Asynchronous pattern implementation. It manages the lifecycle of events, including creating, starting, stopping, and checking the status of events. It maintains a map of event IDs to `Event` objects. Here's a snippet of how it creates an asynchronous event: + +```java +public int createAsync(Duration runtime) throws MaxNumOfEventsAllowedException, LongRunningEventException { + int id = counter.incrementAndGet(); + events.put(id, new AsyncEvent(id, runtime)); + return id; +} +``` + +The `Event` class is an abstract class that represents an event. It has two concrete subclasses: `AsyncEvent` and `SyncEvent`. An `Event` has an ID, a runtime (how long it should run), and a status (whether it's running, completed, or ready to start). It also has methods to start and stop the event. Here's a snippet of how an `AsyncEvent` starts: + +```java +@Override +public void start() { + Thread thread = new Thread(() -> { + try { + handleRunStart(); + Thread.sleep(getRuntime().toMillis()); + handleRunComplete(); + } catch (InterruptedException e) { + handleRunFailure(e.getMessage()); + } + }); + thread.start(); +} +``` + +In this snippet, when an `AsyncEvent` is started, it runs in a separate thread without blocking the main thread. + +A synchronous event is created and managed similarly to an asynchronous event. Here's a snippet of how it creates and manages a synchronous event: + +```java +// Create an EventManager +EventManager eventManager = new EventManager(); + +// Create a synchronous event that runs for 60 seconds +int syncEventId = eventManager.create(Duration.ofSeconds(60)); + +// Start the synchronous event +eventManager.start(syncEventId); + +// Check the status of the synchronous event +eventManager.status(syncEventId); + +// Stop the synchronous event +eventManager.cancel(syncEventId); +``` + +In the `EventManager` class, a synchronous event is created using the `create` method: + +```java +public int create(Duration runtime) throws MaxNumOfEventsAllowedException, LongRunningEventException { + int id = counter.incrementAndGet(); + events.put(id, new SyncEvent(id, runtime)); + return id; +} +``` + +The `SyncEvent` class is a subclass of `Event` that represents a synchronous event. When a `SyncEvent` is started, it runs on the main thread and blocks it until the event is completed. Here's a snippet of how a `SyncEvent` starts: + +```java +@Override +public void start() { + try { + handleRunStart(); + Thread.sleep(getRuntime().toMillis()); + handleRunComplete(); + } catch (InterruptedException e) { + handleRunFailure(e.getMessage()); + } +} +``` + +In this snippet, when a `SyncEvent` is started, it runs on the main thread, blocking it until the event is completed. This is in contrast to an `AsyncEvent`, which runs in a separate thread without blocking the main thread. + +These are the key parts of the Event-Based Asynchronous design pattern as implemented in this code. The pattern allows tasks to be executed in the background, notifying the main program via events when completed, thereby enhancing system efficiency and responsiveness without blocking ongoing operations. + +## When to Use the Event-Based Asynchronous Pattern in Java + +* When multiple tasks can be processed in parallel and independently. +* Systems that require responsiveness and cannot afford to have threads blocked waiting for an operation to complete. +* In GUI applications where user interface responsiveness is critical. +* Distributed systems where long network operations are involved. + +## Real-World Applications of Event-Based Asynchronous Pattern in Java + +* GUI libraries in Java (e.g., JavaFX, Swing with SwingWorker). +* Java Message Service (JMS) for handling asynchronous messaging. +* Java’s CompletableFuture and various Event-Driven Frameworks. + +## Benefits and Trade-offs of Event-Based Asynchronous Pattern + +Benefits: + +* Improves application scalability and responsiveness. +* Reduces the resources wasted on threads that would simply wait for I/O operations. +* Enhances fault tolerance through isolation of process execution. + +Trade-offs: + +* Increases complexity of error handling as errors may occur in different threads or at different times. +* Can lead to harder-to-follow code and debugging challenges due to the non-linear nature of asynchronous code execution. + +## Related Java Design Patterns + +* [Observer](https://java-design-patterns.com/patterns/observer/): Often used in conjunction where the observer reacts to events as they occur. +* Publish/Subscribe: Related in terms of event handling mechanisms, particularly for messaging and event distribution across components. +* [Command](https://java-design-patterns.com/patterns/command/): Useful for encapsulating all information needed to perform an action or trigger an event. + +## References and Credits + +* [Java Concurrency in Practice](https://amzn.to/4cYY4kU) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3Uh7rW1) +* [Pro JavaFX 8: A Definitive Guide to Building Desktop, Mobile, and Embedded Java Clients](https://amzn.to/3vHUqLL) +* [Event-based Asynchronous Pattern Overview (Microsoft)](https://msdn.microsoft.com/en-us/library/wewwczdw%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) diff --git a/event-asynchronous/etc/event-asynchronous.png b/event-based-asynchronous/etc/event-asynchronous.png similarity index 100% rename from event-asynchronous/etc/event-asynchronous.png rename to event-based-asynchronous/etc/event-asynchronous.png diff --git a/event-asynchronous/etc/event-asynchronous.ucls b/event-based-asynchronous/etc/event-asynchronous.ucls similarity index 100% rename from event-asynchronous/etc/event-asynchronous.ucls rename to event-based-asynchronous/etc/event-asynchronous.ucls diff --git a/event-based-asynchronous/etc/event-asynchronous.urm.puml b/event-based-asynchronous/etc/event-asynchronous.urm.puml new file mode 100644 index 000000000000..3a896c32f59f --- /dev/null +++ b/event-based-asynchronous/etc/event-asynchronous.urm.puml @@ -0,0 +1,70 @@ +@startuml +package com.iluwatar.event.asynchronous { + class App { + - LOGGER : Logger {static} + + PROP_FILE_NAME : String {static} + ~ interactiveMode : boolean + + App() + + main(args : String[]) {static} + - processOption1(eventManager : EventManager, s : Scanner) + - processOption2(eventManager : EventManager, s : Scanner) + - processOption3(eventManager : EventManager, s : Scanner) + + quickRun() + + run() + + runInteractiveMode() + + setUp() + } + class Event { + - LOGGER : Logger {static} + - eventId : int + - eventListener : ThreadCompleteListener + - eventTime : int + - isComplete : boolean + - isSynchronous : boolean + - thread : Thread + + Event(eventId : int, eventTime : int, isSynchronous : boolean) + + addListener(listener : ThreadCompleteListener) + - completed() + + isSynchronous() : boolean + + removeListener(listener : ThreadCompleteListener) + + run() + + start() + + status() + + stop() + } + class EventManager { + - DOES_NOT_EXIST : String {static} + + MAX_EVENT_TIME : int {static} + + MAX_ID : int {static} + + MAX_RUNNING_EVENTS : int {static} + + MIN_ID : int {static} + - currentlyRunningSyncEvent : int + - eventPool : Map + - rand : Random + + EventManager() + + cancel(eventId : int) + + completedEventHandler(eventId : int) + + create(eventTime : int) : int + + createAsync(eventTime : int) : int + - createEvent(eventTime : int, isSynchronous : boolean) : int + - generateId() : int + + getEventPool() : Map + + numOfCurrentlyRunningSyncEvent() : int + + shutdown() + + start(eventId : int) + + status(eventId : int) + + statusOfAllEvents() + } + interface IEvent { + + start() {abstract} + + status() {abstract} + + stop() {abstract} + } + interface ThreadCompleteListener { + + completedEventHandler(int) {abstract} + } +} +Event --> "-eventListener" ThreadCompleteListener +Event ..|> IEvent +EventManager ..|> ThreadCompleteListener +@enduml \ No newline at end of file diff --git a/event-based-asynchronous/etc/event-based-asynchronous-sequence-diagram.png b/event-based-asynchronous/etc/event-based-asynchronous-sequence-diagram.png new file mode 100644 index 000000000000..882975df5c0a Binary files /dev/null and b/event-based-asynchronous/etc/event-based-asynchronous-sequence-diagram.png differ diff --git a/event-based-asynchronous/etc/event-based-asynchronous.urm.puml b/event-based-asynchronous/etc/event-based-asynchronous.urm.puml new file mode 100644 index 000000000000..518155ab44f9 --- /dev/null +++ b/event-based-asynchronous/etc/event-based-asynchronous.urm.puml @@ -0,0 +1,70 @@ +@startuml +package com.iluwatar.event.asynchronous { + class App { + - LOGGER : Logger {static} + + PROP_FILE_NAME : String {static} + ~ interactiveMode : boolean + + App() + + main(args : String[]) {static} + - processOption1(eventManager : EventManager, s : Scanner) + - processOption2(eventManager : EventManager, s : Scanner) + - processOption3(eventManager : EventManager, s : Scanner) + + quickRun() + + run() + + runInteractiveMode() + + setUp() + } + class AsyncEvent { + - LOGGER : Logger {static} + - eventId : int + - eventListener : ThreadCompleteListener + - eventTime : int + - isComplete : AtomicBoolean + - synchronous : boolean + - thread : Thread + + AsyncEvent(eventId : int, eventTime : int, synchronous : boolean) + + addListener(listener : ThreadCompleteListener) + - completed() + + isSynchronous() : boolean + + removeListener() + + run() + + start() + + status() + + stop() + } + interface Event { + + start() {abstract} + + status() {abstract} + + stop() {abstract} + } + class EventManager { + - DOES_NOT_EXIST : String {static} + + MAX_EVENT_TIME : int {static} + + MAX_ID : int {static} + + MAX_RUNNING_EVENTS : int {static} + + MIN_ID : int {static} + - currentlyRunningSyncEvent : int + - eventPool : Map + - rand : SecureRandom + + EventManager() + + cancel(eventId : int) + + completedEventHandler(eventId : int) + + create(eventTime : int) : int + + createAsync(eventTime : int) : int + - createEvent(eventTime : int, isSynchronous : boolean) : int + - generateId() : int + + getEventPool() : Map + + numOfCurrentlyRunningSyncEvent() : int + + shutdown() + + start(eventId : int) + + status(eventId : int) + + statusOfAllEvents() + } + interface ThreadCompleteListener { + + completedEventHandler(int) {abstract} + } +} +AsyncEvent --> "-eventListener" ThreadCompleteListener +AsyncEvent ..|> Event +EventManager ..|> ThreadCompleteListener +@enduml \ No newline at end of file diff --git a/event-based-asynchronous/pom.xml b/event-based-asynchronous/pom.xml new file mode 100644 index 000000000000..3a66d321c02f --- /dev/null +++ b/event-based-asynchronous/pom.xml @@ -0,0 +1,76 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + event-based-asynchronous + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.awaitility + awaitility + 4.3.0 + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.event.asynchronous.App + + + + + + + + + \ No newline at end of file diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java new file mode 100644 index 000000000000..731cd169157e --- /dev/null +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java @@ -0,0 +1,234 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +import java.io.IOException; +import java.time.Duration; +import java.util.Properties; +import java.util.Scanner; +import lombok.extern.slf4j.Slf4j; + +/** + * This application demonstrates the Event-based Asynchronous pattern. Essentially, users (of + * the pattern) may choose to run events in an Asynchronous or Synchronous mode. There can be + * multiple Asynchronous events running at once but only one Synchronous event can run at a time. + * Asynchronous events are synonymous to multi-threads. The key point here is that the threads run + * in the background and the user is free to carry on with other processes. Once an event is + * complete, the appropriate listener/callback method will be called. The listener then proceeds to + * carry out further processing depending on the needs of the user. + * + *

    The {@link EventManager} manages the events/threads that the user creates. Currently, the + * supported event operations are: start, stop, getStatus. + * For Synchronous events, the user is unable to start another (Synchronous) event if one is already + * running at the time. The running event would have to either be stopped or completed before a new + * event can be started. + * + *

    The Event-based Asynchronous Pattern makes available the advantages of multithreaded + * applications while hiding many of the complex issues inherent in multithreaded design. Using a + * class that supports this pattern can allow you to:- (1) Perform time-consuming tasks, such as + * downloads and database operations, "in the background," without interrupting your application. + * (2) Execute multiple operations simultaneously, receiving notifications when each completes. (3) + * Wait for resources to become available without stopping ("hanging") your application. (4) + * Communicate with pending asynchronous operations using the familiar events-and-delegates model. + * + * @see EventManager + * @see AsyncEvent + */ +@Slf4j +public class App { + + public static final String PROP_FILE_NAME = "config.properties"; + + boolean interactiveMode = false; + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + var app = new App(); + app.setUp(); + app.run(); + } + + /** + * App can run in interactive mode or not. Interactive mode == Allow user interaction with command + * line. Non-interactive is a quick sequential run through the available {@link EventManager} + * operations. + */ + public void setUp() { + var prop = new Properties(); + + var inputStream = App.class.getClassLoader().getResourceAsStream(PROP_FILE_NAME); + + if (inputStream != null) { + try { + prop.load(inputStream); + } catch (IOException e) { + LOGGER.error("{} was not found. Defaulting to non-interactive mode.", PROP_FILE_NAME, e); + } + var property = prop.getProperty("INTERACTIVE_MODE"); + if (property.equalsIgnoreCase("YES")) { + interactiveMode = true; + } + } + } + + /** Run program in either interactive mode or not. */ + public void run() { + if (interactiveMode) { + runInteractiveMode(); + } else { + quickRun(); + } + } + + /** Run program in non-interactive mode. */ + public void quickRun() { + var eventManager = new EventManager(); + + try { + // Create an Asynchronous event. + var asyncEventId = eventManager.createAsync(Duration.ofSeconds(60)); + LOGGER.info("Async Event [{}] has been created.", asyncEventId); + eventManager.start(asyncEventId); + LOGGER.info("Async Event [{}] has been started.", asyncEventId); + + // Create a Synchronous event. + var syncEventId = eventManager.create(Duration.ofSeconds(60)); + LOGGER.info("Sync Event [{}] has been created.", syncEventId); + eventManager.start(syncEventId); + LOGGER.info("Sync Event [{}] has been started.", syncEventId); + + eventManager.status(asyncEventId); + eventManager.status(syncEventId); + + eventManager.cancel(asyncEventId); + LOGGER.info("Async Event [{}] has been stopped.", asyncEventId); + eventManager.cancel(syncEventId); + LOGGER.info("Sync Event [{}] has been stopped.", syncEventId); + + } catch (MaxNumOfEventsAllowedException + | LongRunningEventException + | EventDoesNotExistException + | InvalidOperationException e) { + LOGGER.error(e.getMessage()); + } + } + + /** Run program in interactive mode. */ + public void runInteractiveMode() { + var eventManager = new EventManager(); + + var s = new Scanner(System.in); + var option = -1; + while (option != 4) { + LOGGER.info("Hello. Would you like to boil some eggs?"); + LOGGER.info( + """ + (1) BOIL AN EGG + (2) STOP BOILING THIS EGG + (3) HOW ARE MY EGGS? + (4) EXIT + """); + LOGGER.info("Choose [1,2,3,4]: "); + option = s.nextInt(); + + if (option == 1) { + processOption1(eventManager, s); + } else if (option == 2) { + processOption2(eventManager, s); + } else if (option == 3) { + processOption3(eventManager, s); + } else if (option == 4) { + eventManager.shutdown(); + } + } + + s.close(); + } + + private void processOption3(EventManager eventManager, Scanner s) { + s.nextLine(); + LOGGER.info("Just one egg (O) OR all of them (A) ?: "); + var eggChoice = s.nextLine(); + + if (eggChoice.equalsIgnoreCase("O")) { + LOGGER.info("Which egg?: "); + int eventId = s.nextInt(); + try { + eventManager.status(eventId); + } catch (EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + } else if (eggChoice.equalsIgnoreCase("A")) { + eventManager.statusOfAllEvents(); + } + } + + private void processOption2(EventManager eventManager, Scanner s) { + LOGGER.info("Which egg?: "); + var eventId = s.nextInt(); + try { + eventManager.cancel(eventId); + LOGGER.info("Egg [{}] is removed from boiler.", eventId); + } catch (EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + } + + private void processOption1(EventManager eventManager, Scanner s) { + s.nextLine(); + LOGGER.info("Boil multiple eggs at once (A) or boil them one-by-one (S)?: "); + var eventType = s.nextLine(); + LOGGER.info("How long should this egg be boiled for (in seconds)?: "); + var eventTime = Duration.ofSeconds(s.nextInt()); + if (eventType.equalsIgnoreCase("A")) { + try { + var eventId = eventManager.createAsync(eventTime); + eventManager.start(eventId); + LOGGER.info("Egg [{}] is being boiled.", eventId); + } catch (MaxNumOfEventsAllowedException + | LongRunningEventException + | EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + } else if (eventType.equalsIgnoreCase("S")) { + try { + var eventId = eventManager.create(eventTime); + eventManager.start(eventId); + LOGGER.info("Egg [{}] is being boiled.", eventId); + } catch (MaxNumOfEventsAllowedException + | InvalidOperationException + | LongRunningEventException + | EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + } else { + LOGGER.info("Unknown event type."); + } + } +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java new file mode 100644 index 000000000000..b58848f0a702 --- /dev/null +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java @@ -0,0 +1,97 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** Each Event runs as a separate/individual thread. */ +@Slf4j +@RequiredArgsConstructor +public class AsyncEvent implements Event, Runnable { + + private final int eventId; + private final Duration eventTime; + @Getter private final boolean synchronous; + private Thread thread; + private final AtomicBoolean isComplete = new AtomicBoolean(false); + private ThreadCompleteListener eventListener; + + @Override + public void start() { + thread = new Thread(this); + thread.start(); + } + + @Override + public void stop() { + if (null == thread) { + return; + } + thread.interrupt(); + } + + @Override + public void status() { + if (isComplete.get()) { + LOGGER.info("[{}] is not done.", eventId); + } else { + LOGGER.info("[{}] is done.", eventId); + } + } + + @Override + public void run() { + + var currentTime = Instant.now(); + var endTime = currentTime.plusSeconds(eventTime.getSeconds()); + while (Instant.now().compareTo(endTime) < 0) { + try { + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException e) { + LOGGER.error("Thread was interrupted: ", e); + Thread.currentThread().interrupt(); + return; + } + } + isComplete.set(true); + completed(); + } + + public final void addListener(final ThreadCompleteListener listener) { + this.eventListener = listener; + } + + private void completed() { + if (eventListener != null) { + eventListener.completedEventHandler(eventId); + } + } +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java new file mode 100644 index 000000000000..6c51f8584ec6 --- /dev/null +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +/** + * Events that fulfill the start stop and list out current status behaviour follow this interface. + */ +public interface Event { + + void start(); + + void stop(); + + void status(); +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java new file mode 100644 index 000000000000..ad6a649c058f --- /dev/null +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +import java.io.Serial; + +/** Custom Exception Class for Non-Existent Event. */ +public class EventDoesNotExistException extends Exception { + + @Serial private static final long serialVersionUID = -3398463738273811509L; + + public EventDoesNotExistException(String message) { + super(message); + } +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java new file mode 100644 index 000000000000..cef3697ffb55 --- /dev/null +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java @@ -0,0 +1,216 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +import java.security.SecureRandom; +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import lombok.Getter; + +/** + * EventManager handles and maintains a pool of event threads. {@link AsyncEvent} threads are + * created upon user request. Thre are two types of events; Asynchronous and Synchronous. There can + * be multiple Asynchronous events running at once but only one Synchronous event running at a time. + * Currently supported event operations are: start, stop, and getStatus. Once an event is complete, + * it then notifies EventManager through a listener. The EventManager then takes the event out of + * the pool. + */ +public class EventManager implements ThreadCompleteListener { + + public static final int MAX_RUNNING_EVENTS = 1000; + // Just don't want to have too many running events. :) + public static final int MIN_ID = 1; + public static final int MAX_ID = MAX_RUNNING_EVENTS; + public static final Duration MAX_EVENT_TIME = Duration.ofSeconds(1800); // 30 minutes. + private int currentlyRunningSyncEvent = -1; + private final SecureRandom rand; + + @Getter private final Map eventPool; + + private static final String DOES_NOT_EXIST = " does not exist."; + + /** EventManager constructor. */ + public EventManager() { + rand = new SecureRandom(); + eventPool = new ConcurrentHashMap<>(MAX_RUNNING_EVENTS); + } + + /** + * Create a Synchronous event. + * + * @param eventTime Time an event should run for. + * @return eventId + * @throws MaxNumOfEventsAllowedException When too many events are running at a time. + * @throws InvalidOperationException No new synchronous events can be created when one is already + * running. + * @throws LongRunningEventException Long-running events are not allowed in the app. + */ + public int create(Duration eventTime) + throws MaxNumOfEventsAllowedException, InvalidOperationException, LongRunningEventException { + if (currentlyRunningSyncEvent != -1) { + throw new InvalidOperationException( + "Event [" + + currentlyRunningSyncEvent + + "] is still" + + " running. Please wait until it finishes and try again."); + } + + var eventId = createEvent(eventTime, true); + currentlyRunningSyncEvent = eventId; + + return eventId; + } + + /** + * Create an Asynchronous event. + * + * @param eventTime Time an event should run for. + * @return eventId + * @throws MaxNumOfEventsAllowedException When too many events are running at a time. + * @throws LongRunningEventException Long-running events are not allowed in the app. + */ + public int createAsync(Duration eventTime) + throws MaxNumOfEventsAllowedException, LongRunningEventException { + return createEvent(eventTime, false); + } + + private int createEvent(Duration eventTime, boolean isSynchronous) + throws MaxNumOfEventsAllowedException, LongRunningEventException { + if (eventTime.isNegative()) { + throw new IllegalArgumentException("eventTime cannot be negative"); + } + + if (eventPool.size() == MAX_RUNNING_EVENTS) { + throw new MaxNumOfEventsAllowedException( + "Too many events are running at the moment." + " Please try again later."); + } + + if (eventTime.getSeconds() > MAX_EVENT_TIME.getSeconds()) { + throw new LongRunningEventException( + "Maximum event time allowed is " + MAX_EVENT_TIME + " seconds. Please try again."); + } + + var newEventId = generateId(); + + var newEvent = new AsyncEvent(newEventId, eventTime, isSynchronous); + newEvent.addListener(this); + eventPool.put(newEventId, newEvent); + + return newEventId; + } + + /** + * Starts event. + * + * @param eventId The event that needs to be started. + * @throws EventDoesNotExistException If event does not exist in our eventPool. + */ + public void start(int eventId) throws EventDoesNotExistException { + if (!eventPool.containsKey(eventId)) { + throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST); + } + + eventPool.get(eventId).start(); + } + + /** + * Stops event. + * + * @param eventId The event that needs to be stopped. + * @throws EventDoesNotExistException If event does not exist in our eventPool. + */ + public void cancel(int eventId) throws EventDoesNotExistException { + if (!eventPool.containsKey(eventId)) { + throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST); + } + + if (eventId == currentlyRunningSyncEvent) { + currentlyRunningSyncEvent = -1; + } + + eventPool.get(eventId).stop(); + eventPool.remove(eventId); + } + + /** + * Get status of a running event. + * + * @param eventId The event to inquire status of. + * @throws EventDoesNotExistException If event does not exist in our eventPool. + */ + public void status(int eventId) throws EventDoesNotExistException { + if (!eventPool.containsKey(eventId)) { + throw new EventDoesNotExistException(eventId + DOES_NOT_EXIST); + } + + eventPool.get(eventId).status(); + } + + /** Gets status of all running events. */ + @SuppressWarnings("rawtypes") + public void statusOfAllEvents() { + eventPool.entrySet().forEach(entry -> ((AsyncEvent) ((Map.Entry) entry).getValue()).status()); + } + + /** Stop all running events. */ + @SuppressWarnings("rawtypes") + public void shutdown() { + eventPool.entrySet().forEach(entry -> ((AsyncEvent) ((Map.Entry) entry).getValue()).stop()); + } + + /** + * Returns a pseudo-random number between min and max, inclusive. The difference between min and + * max can be at most Integer.MAX_VALUE - 1. + */ + private int generateId() { + // nextInt is normally exclusive of the top value, + // so add 1 to make it inclusive + var randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID; + while (eventPool.containsKey(randomNum)) { + randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID; + } + + return randomNum; + } + + /** + * Callback from an {@link AsyncEvent} (once it is complete). The Event is then removed from the + * pool. + */ + @Override + public void completedEventHandler(int eventId) { + eventPool.get(eventId).status(); + if (eventPool.get(eventId).isSynchronous()) { + currentlyRunningSyncEvent = -1; + } + eventPool.remove(eventId); + } + + /** Get number of currently running Synchronous events. */ + public int numOfCurrentlyRunningSyncEvent() { + return currentlyRunningSyncEvent; + } +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java new file mode 100644 index 000000000000..f8a5914602de --- /dev/null +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +import java.io.Serial; + +/** Type of Exception raised when the Operation being invoked is Invalid. */ +public class InvalidOperationException extends Exception { + + @Serial private static final long serialVersionUID = -6191545255213410803L; + + public InvalidOperationException(String message) { + super(message); + } +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java new file mode 100644 index 000000000000..9045b6dcf9b1 --- /dev/null +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +import java.io.Serial; + +/** Type of Exception raised when the Operation being invoked is Long Running. */ +public class LongRunningEventException extends Exception { + + @Serial private static final long serialVersionUID = -483423544320148809L; + + public LongRunningEventException(String message) { + super(message); + } +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java new file mode 100644 index 000000000000..16fa5502d1f9 --- /dev/null +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +import java.io.Serial; + +/** Type of Exception raised when the max number of allowed events is exceeded. */ +public class MaxNumOfEventsAllowedException extends Exception { + + @Serial private static final long serialVersionUID = -8430876973516292695L; + + public MaxNumOfEventsAllowedException(String message) { + super(message); + } +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java new file mode 100644 index 000000000000..f30eb51351a5 --- /dev/null +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +/** Interface with listener behaviour related to Thread Completion. */ +public interface ThreadCompleteListener { + void completedEventHandler(final int eventId); +} diff --git a/event-asynchronous/src/main/resources/config.properties b/event-based-asynchronous/src/main/resources/config.properties similarity index 96% rename from event-asynchronous/src/main/resources/config.properties rename to event-based-asynchronous/src/main/resources/config.properties index f76c07bb4dfc..9b05b1c77509 100644 --- a/event-asynchronous/src/main/resources/config.properties +++ b/event-based-asynchronous/src/main/resources/config.properties @@ -1,6 +1,6 @@ # # The MIT License -# Copyright (c) 2014-2016 Ilkka Seppälä +# Copyright © 2014-2021 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 diff --git a/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java b/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java new file mode 100644 index 000000000000..4b5094033b13 --- /dev/null +++ b/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Tests that EventAsynchronous example runs without errors. */ +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java b/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java new file mode 100644 index 000000000000..ab9dd70bbf3d --- /dev/null +++ b/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java @@ -0,0 +1,141 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.asynchronous; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import lombok.SneakyThrows; +import org.junit.jupiter.api.Test; + +/** Application test */ +class EventAsynchronousTest { + + @Test + @SneakyThrows + void testAsynchronousEvent() { + var eventManager = new EventManager(); + var aEventId = eventManager.createAsync(Duration.ofSeconds(60)); + + assertDoesNotThrow(() -> eventManager.start(aEventId)); + + assertEquals(1, eventManager.getEventPool().size()); + assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); + assertEquals(-1, eventManager.numOfCurrentlyRunningSyncEvent()); + + assertDoesNotThrow(() -> eventManager.cancel(aEventId)); + assertTrue(eventManager.getEventPool().isEmpty()); + } + + @Test + @SneakyThrows + void testSynchronousEvent() { + var eventManager = new EventManager(); + var sEventId = eventManager.create(Duration.ofSeconds(60)); + + assertDoesNotThrow(() -> eventManager.start(sEventId)); + assertEquals(1, eventManager.getEventPool().size()); + assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); + assertNotEquals(-1, eventManager.numOfCurrentlyRunningSyncEvent()); + + assertDoesNotThrow(() -> eventManager.cancel(sEventId)); + assertTrue(eventManager.getEventPool().isEmpty()); + } + + @Test + @SneakyThrows + void testFullSynchronousEvent() { + var eventManager = new EventManager(); + + var eventTime = Duration.ofSeconds(1); + + var sEventId = eventManager.create(eventTime); + assertEquals(1, eventManager.getEventPool().size()); + + eventManager.start(sEventId); + + await().until(() -> eventManager.getEventPool().isEmpty()); + } + + @Test + @SneakyThrows + void testUnsuccessfulSynchronousEvent() { + assertThrows( + InvalidOperationException.class, + () -> { + var eventManager = new EventManager(); + + var sEventId = assertDoesNotThrow(() -> eventManager.create(Duration.ofSeconds(60))); + eventManager.start(sEventId); + sEventId = eventManager.create(Duration.ofSeconds(60)); + eventManager.start(sEventId); + }); + } + + @Test + @SneakyThrows + void testFullAsynchronousEvent() { + var eventManager = new EventManager(); + var eventTime = Duration.ofSeconds(1); + + var aEventId1 = assertDoesNotThrow(() -> eventManager.createAsync(eventTime)); + var aEventId2 = assertDoesNotThrow(() -> eventManager.createAsync(eventTime)); + var aEventId3 = assertDoesNotThrow(() -> eventManager.createAsync(eventTime)); + assertEquals(3, eventManager.getEventPool().size()); + + eventManager.start(aEventId1); + eventManager.start(aEventId2); + eventManager.start(aEventId3); + + await().until(() -> eventManager.getEventPool().isEmpty()); + } + + @Test + void testLongRunningEventException() { + assertThrows( + LongRunningEventException.class, + () -> { + var eventManager = new EventManager(); + eventManager.createAsync(Duration.ofMinutes(31)); + }); + } + + @Test + void testMaxNumOfEventsAllowedException() { + assertThrows( + MaxNumOfEventsAllowedException.class, + () -> { + final var eventManager = new EventManager(); + for (int i = 0; i < 1100; i++) { + eventManager.createAsync(Duration.ofSeconds(i)); + } + }); + } +} diff --git a/event-driven-architecture/README.md b/event-driven-architecture/README.md index e2f06cf5aff5..c868c174e078 100644 --- a/event-driven-architecture/README.md +++ b/event-driven-architecture/README.md @@ -1,37 +1,202 @@ --- -layout: pattern -title: Event Driven Architecture -folder: event-driven-architecture -permalink: /patterns/event-driven-architecture/ -categories: Architectural -tags: - - Java - - Difficulty-Intermediate - - Reactive +title: "Event-Driven Architecture Pattern in Java: Building Responsive and Scalable Java Systems" +shortTitle: Event-Driven Architecture +description: "Discover comprehensive guides on Event-Driven Architecture patterns with practical Java examples. Learn to implement effective event-driven systems in your projects." +category: Architectural +language: en +tag: + - Asynchronous + - Decoupling + - Enterprise patterns + - Event-driven + - Messaging + - Publish/subscribe + - Reactive + - Scalability --- -## Intent -Send and notify state changes of your objects to other applications using an Event-driven Architecture. +## Also known as -![alt text](./etc/eda.png "Event Driven Architecture") +* Event-Driven System +* Event-Based Architecture + +## Intent of Event-Driven Architecture Design Pattern + +Event-Driven Architecture (EDA) is designed to orchestrate behavior around the production, detection, consumption of, and reaction to events. This architecture enables highly decoupled, scalable, and dynamic interconnections between event producers and consumers. + +## Detailed Explanation of Event-Driven Architecture Pattern with Real-World Examples + +Real-world example + +> A real-world example of the Event-Driven Architecture (EDA) pattern is the operation of an air traffic control system. In this system, events such as aircraft entering airspace, changes in weather conditions, and ground vehicle movements trigger specific responses like altering flight paths, scheduling gate assignments, and updating runway usage. This setup allows for highly efficient, responsive, and safe management of airport operations, reflecting EDA's core principles of asynchronous communication and dynamic event handling. + +In plain words + +> Event-Driven Architecture is a design pattern where system behavior is dictated by the occurrence of specific events, allowing for dynamic, efficient, and decoupled responses. + +Wikipedia says + +> Event-driven architecture (EDA) is a software architecture paradigm concerning the production and detection of events. + +Architecture diagram + +![EDA Architecture Diagram](./etc/eda-architecture-diagram.png) + +## Programmatic Example of Event-Driven Architecture in Java + +The Event-Driven Architecture (EDA) pattern in this module is implemented using several key classes and concepts: + +* Event: This is an abstract class that represents an event. It's the base class for all types of events that can occur in the system. +* UserCreatedEvent and UserUpdatedEvent: These are concrete classes that extend the Event class. They represent specific types of events that can occur in the system, namely the creation and updating of a user. +* EventDispatcher: This class is responsible for dispatching events to their respective handlers. It maintains a mapping of event types to handlers. +* UserCreatedEventHandler and UserUpdatedEventHandler: These are the handler classes for the UserCreatedEvent and UserUpdatedEvent respectively. They contain the logic to execute when these events occur. + +First, we'll define the `Event` abstract class and the concrete event classes `UserCreatedEvent` and `UserUpdatedEvent`. + +```java +public abstract class Event { + // Event related properties and methods +} +``` + +```java +public class UserCreatedEvent extends Event { + private User user; + + public UserCreatedEvent(User user) { + this.user = user; + } + + public User getUser() { + return user; + } +} +``` + +```java +public class UserUpdatedEvent extends Event { + private User user; + + public UserUpdatedEvent(User user) { + this.user = user; + } + + public User getUser() { + return user; + } +} +``` + +Next, we'll define the event handlers `UserCreatedEventHandler` and `UserUpdatedEventHandler`. + +```java +public class UserCreatedEventHandler { + public void onUserCreated(UserCreatedEvent event) { + // Logic to execute when a UserCreatedEvent occurs + } +} +``` + +```java +public class UserUpdatedEventHandler { + public void onUserUpdated(UserUpdatedEvent event) { + // Logic to execute when a UserUpdatedEvent occurs + } +} +``` + +Then, we'll define the `EventDispatcher` class that is responsible for dispatching events to their respective handlers. + +```java +public class EventDispatcher { + private Map, List>> handlers = new HashMap<>(); + + public void registerHandler(Class eventType, Consumer handler) { + handlers.computeIfAbsent(eventType, k -> new ArrayList<>()).add(handler::accept); + } + + public void dispatch(Event event) { + List> eventHandlers = handlers.get(event.getClass()); + if (eventHandlers != null) { + eventHandlers.forEach(handler -> handler.accept(event)); + } + } +} +``` + +Finally, we'll demonstrate how to use these classes in the main application. + +```java +public class App { + public static void main(String[] args) { + // Create an EventDispatcher + EventDispatcher dispatcher = new EventDispatcher(); + + // Register handlers for UserCreatedEvent and UserUpdatedEvent + dispatcher.registerHandler(UserCreatedEvent.class, new UserCreatedEventHandler()::onUserCreated); + dispatcher.registerHandler(UserUpdatedEvent.class, new UserUpdatedEventHandler()::onUserUpdated); + + // Create a User + User user = new User("iluwatar"); + + // Dispatch UserCreatedEvent + dispatcher.dispatch(new UserCreatedEvent(user)); + + // Dispatch UserUpdatedEvent + dispatcher.dispatch(new UserUpdatedEvent(user)); + } +} +``` + +Running the example produces the following console output: + +``` +22:15:19.997 [main] INFO com.iluwatar.eda.handler.UserCreatedEventHandler -- User 'iluwatar' has been Created! +22:15:20.000 [main] INFO com.iluwatar.eda.handler.UserUpdatedEventHandler -- User 'iluwatar' has been Updated! +``` + +This example demonstrates the Event-Driven Architecture pattern, where the occurrence of events drives the flow of the program. The system is designed to respond to events as they occur, which allows for a high degree of flexibility and decoupling between components. + +## When to Use the Event-Driven Architecture Pattern in Java -## Applicability Use an Event-driven architecture when -* you want to create a loosely coupled system -* you want to build a more responsive system -* you want a system that is easier to extend +* Systems where change detection is crucial. +* Applications that require real-time features and reactive systems. +* Systems needing to efficiently handle high throughput and sporadic loads. +* When integrating with microservices to enhance agility and scalability. -## Real world examples +## Real-World Applications of Event-Driven Architecture Pattern in Java -* SendGrid, an email API, sends events whenever an email is processed, delivered, opened etc... (https://sendgrid.com/docs/API_Reference/Webhooks/event.html) +* Real-time data processing applications. +* Complex event processing systems in finance, such as stock trading platforms. +* IoT systems for dynamic device and information management. * Chargify, a billing API, exposes payment activity through various events (https://docs.chargify.com/api-events) * Amazon's AWS Lambda, lets you execute code in response to events such as changes to Amazon S3 buckets, updates to an Amazon DynamoDB table, or custom events generated by your applications or devices. (https://aws.amazon.com/lambda) * MySQL runs triggers based on events such as inserts and update events happening on database tables. -## Credits +## Benefits and Trade-offs of Event-Driven Architecture Pattern + +Benefits: + +* Scalability: Efficiently processes fluctuating loads with asynchronous processing. +* Flexibility and Agility: New event types and event consumers can be added with minimal impact on existing components. +* Responsiveness: Improves responsiveness by decoupling event processing and state management. + +Trade-offs: + +* Complexity in Tracking: Can be challenging to debug and track due to loose coupling and asynchronous behaviors. +* Dependency on Messaging Systems: Heavily relies on robust messaging infrastructures. +* Event Consistency: Requires careful design to handle event ordering and consistency. + +## Related Java Design Patterns + +* Microservices Architecture: Often used together with EDA to enhance agility and scalability. +* Publish/Subscribe: A common pattern used within EDA for messaging between event producers and consumers. + +## References and Credits -* [Event-driven architecture - Wikipedia](https://en.wikipedia.org/wiki/Event-driven_architecture) -* [Fundamental Components of an Event-Driven Architecture](http://giocc.com/fundamental-components-of-an-event-driven-architecture.html) -* [Real World Applications/Event Driven Applications](https://wiki.haskell.org/Real_World_Applications/Event_Driven_Applications) -* [Event-driven architecture definition](http://searchsoa.techtarget.com/definition/event-driven-architecture) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3Q3vBki) +* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/49Aljz0) +* [Reactive Messaging Patterns With the Actor Model: Applications and Integration in Scala and Akka](https://amzn.to/3UeoBUa) +* [What is an Event-Driven Architecture (Amazon)](https://aws.amazon.com/event-driven-architecture/) diff --git a/event-driven-architecture/etc/eda-architecture-diagram.png b/event-driven-architecture/etc/eda-architecture-diagram.png new file mode 100644 index 000000000000..4e74bcf2e89a Binary files /dev/null and b/event-driven-architecture/etc/eda-architecture-diagram.png differ diff --git a/event-driven-architecture/etc/event-driven-architecture.urm.puml b/event-driven-architecture/etc/event-driven-architecture.urm.puml new file mode 100644 index 000000000000..6b67f0a0e569 --- /dev/null +++ b/event-driven-architecture/etc/event-driven-architecture.urm.puml @@ -0,0 +1,64 @@ +@startuml +package com.iluwatar.eda.handler { + class UserCreatedEventHandler { + - LOGGER : Logger {static} + + UserCreatedEventHandler() + + onEvent(event : UserCreatedEvent) + } + class UserUpdatedEventHandler { + - LOGGER : Logger {static} + + UserUpdatedEventHandler() + + onEvent(event : UserUpdatedEvent) + } +} +package com.iluwatar.eda.event { + abstract class AbstractEvent { + + AbstractEvent() + + getType() : Class + } + class UserCreatedEvent { + - user : User + + UserCreatedEvent(user : User) + + getUser() : User + } + class UserUpdatedEvent { + - user : User + + UserUpdatedEvent(user : User) + + getUser() : User + } +} +package com.iluwatar.eda.framework { + interface Event { + + getType() : Class {abstract} + } + class EventDispatcher { + - handlers : Map, Handler> + + EventDispatcher() + + dispatch(event : E extends Event) + + registerHandler(eventType : Class, handler : Handler) + } + interface Handler { + + onEvent(E extends Event) {abstract} + } +} +package com.iluwatar.eda.model { + class User { + - username : String + + User(username : String) + + getUsername() : String + } +} +package com.iluwatar.eda { + class App { + + App() + + main(args : String[]) {static} + } +} +UserCreatedEvent --> "-user" User +UserUpdatedEvent --> "-user" User +AbstractEvent ..|> Event +UserCreatedEvent --|> AbstractEvent +UserUpdatedEvent --|> AbstractEvent +UserCreatedEventHandler ..|> Handler +UserUpdatedEventHandler ..|> Handler +@enduml \ No newline at end of file diff --git a/event-driven-architecture/pom.xml b/event-driven-architecture/pom.xml index 87aae0070c79..8a9fc27876eb 100644 --- a/event-driven-architecture/pom.xml +++ b/event-driven-architecture/pom.xml @@ -1,8 +1,10 @@ - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - - event-driven-architecture - - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - - org.mockito - mockito-core - test - - - \ No newline at end of file + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + event-driven-architecture + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.eda.App + + + + + + + + + diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java index c41b0ed5a1b1..3b2ea6ae24b3 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -33,11 +35,11 @@ /** * An event-driven architecture (EDA) is a framework that orchestrates behavior around the * production, detection and consumption of events as well as the responses they evoke. An event is - * any identifiable occurrence that has significance for system hardware or software.

    The - * example below uses an {@link EventDispatcher} to link/register {@link Event} objects to their - * respective handlers once an {@link Event} is dispatched, it's respective handler is invoked and - * the {@link Event} is handled accordingly. + * any identifiable occurrence that has significance for system hardware or software. * + *

    The example below uses an {@link EventDispatcher} to link/register {@link Event} objects to + * their respective handlers once an {@link Event} is dispatched, it's respective handler is invoked + * and the {@link Event} is handled accordingly. */ public class App { @@ -46,19 +48,17 @@ public class App { * made known to the dispatcher by registering them. In this case the {@link UserCreatedEvent} is * bound to the UserCreatedEventHandler, whilst the {@link UserUpdatedEvent} is bound to the * {@link UserUpdatedEventHandler}. The dispatcher can now be called to dispatch specific events. - * When a user is saved, the {@link UserCreatedEvent} can be dispatched. - * On the other hand, when a user is updated, {@link UserUpdatedEvent} can be dispatched. - * + * When a user is saved, the {@link UserCreatedEvent} can be dispatched. On the other hand, when a + * user is updated, {@link UserUpdatedEvent} can be dispatched. */ public static void main(String[] args) { - EventDispatcher dispatcher = new EventDispatcher(); + var dispatcher = new EventDispatcher(); dispatcher.registerHandler(UserCreatedEvent.class, new UserCreatedEventHandler()); dispatcher.registerHandler(UserUpdatedEvent.class, new UserUpdatedEventHandler()); - User user = new User("iluwatar"); + var user = new User("iluwatar"); dispatcher.dispatch(new UserCreatedEvent(user)); dispatcher.dispatch(new UserUpdatedEvent(user)); } - } diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java index be6d70ec1f87..0add9446244e 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,28 +24,29 @@ */ package com.iluwatar.eda.event; -import com.iluwatar.eda.framework.EventDispatcher; import com.iluwatar.eda.framework.Event; +import com.iluwatar.eda.framework.EventDispatcher; /** - * The {@link AbstractEvent} class serves as a base class for defining custom events happening with your - * system. In this example we have two types of events defined. + * The {@link AbstractEvent} class serves as a base class for defining custom events happening with + * your system. In this example we have two types of events defined. + * *

      - *
    • {@link UserCreatedEvent} - used when a user is created
    • - *
    • {@link UserUpdatedEvent} - used when a user is updated
    • + *
    • {@link UserCreatedEvent} - used when a user is created + *
    • {@link UserUpdatedEvent} - used when a user is updated *
    + * * Events can be distinguished using the {@link #getType() getType} method. */ public abstract class AbstractEvent implements Event { /** - * Returns the event type as a {@link Class} object - * In this example, this method is used by the {@link EventDispatcher} to - * dispatch events depending on their type. + * Returns the event type as a {@link Class} object In this example, this method is used by the + * {@link EventDispatcher} to dispatch events depending on their type. * * @return the AbstractEvent type as a {@link Class}. */ public Class getType() { return getClass(); } -} \ No newline at end of file +} diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java index af209f4a9c6e..06cbe3122858 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,21 +25,17 @@ package com.iluwatar.eda.event; import com.iluwatar.eda.model.User; +import lombok.Getter; +import lombok.RequiredArgsConstructor; /** - * The {@link UserCreatedEvent} should should be dispatched whenever a user has been created. - * This class can be extended to contain details about the user has been created. In this example, - * the entire {@link User} object is passed on as data with the event. + * The {@link UserCreatedEvent} should be dispatched whenever a user has been created. This class + * can be extended to contain details about the user has been created. In this example, the entire + * {@link User} object is passed on as data with the event. */ +@RequiredArgsConstructor +@Getter public class UserCreatedEvent extends AbstractEvent { - private User user; - - public UserCreatedEvent(User user) { - this.user = user; - } - - public User getUser() { - return user; - } + private final User user; } diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java index e1046cdcbb72..5fd0e4a7d2ee 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,21 +25,17 @@ package com.iluwatar.eda.event; import com.iluwatar.eda.model.User; +import lombok.Getter; +import lombok.RequiredArgsConstructor; /** - * The {@link UserUpdatedEvent} should should be dispatched whenever a user has been updated. - * This class can be extended to contain details about the user has been updated. In this example, - * the entire {@link User} object is passed on as data with the event. + * The {@link UserUpdatedEvent} should be dispatched whenever a user has been updated. This class + * can be extended to contain details about the user has been updated. In this example, the entire + * {@link User} object is passed on as data with the event. */ +@RequiredArgsConstructor +@Getter public class UserUpdatedEvent extends AbstractEvent { - private User user; - - public UserUpdatedEvent(User user) { - this.user = user; - } - - public User getUser() { - return user; - } + private final User user; } diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Event.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Event.java index fdcd00584e2d..f23dcf872218 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Event.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Event.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,14 +25,15 @@ package com.iluwatar.eda.framework; /** - * A {@link Event} is an object with a specific type that is associated - * to a specific {@link Handler}. + * A {@link Event} is an object with a specific type that is associated to a specific {@link + * Handler}. */ public interface Event { /** - * Returns the message type as a {@link Class} object. In this example the message type is - * used to handle events by their type. + * Returns the message type as a {@link Class} object. In this example the message type is used to + * handle events by their type. + * * @return the message type as a {@link Class}. */ Class getType(); diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java index 427d7bd36bb9..da29f770eeea 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -26,12 +28,12 @@ import java.util.Map; /** - * Handles the routing of {@link Event} messages to associated handlers. - * A {@link HashMap} is used to store the association between events and their respective handlers. + * Handles the routing of {@link Event} messages to associated handlers. A {@link HashMap} is used + * to store the association between events and their respective handlers. */ public class EventDispatcher { - private Map, Handler> handlers; + private final Map, Handler> handlers; public EventDispatcher() { handlers = new HashMap<>(); @@ -41,24 +43,22 @@ public EventDispatcher() { * Links an {@link Event} to a specific {@link Handler}. * * @param eventType The {@link Event} to be registered - * @param handler The {@link Handler} that will be handling the {@link Event} + * @param handler The {@link Handler} that will be handling the {@link Event} */ - public void registerHandler(Class eventType, - Handler handler) { + public void registerHandler(Class eventType, Handler handler) { handlers.put(eventType, handler); } /** - * Dispatches an {@link Event} depending on it's type. + * Dispatches an {@link Event} depending on its type. * * @param event The {@link Event} to be dispatched */ @SuppressWarnings("unchecked") public void dispatch(E event) { - Handler handler = (Handler) handlers.get(event.getClass()); + var handler = (Handler) handlers.get(event.getClass()); if (handler != null) { handler.onEvent(event); } } - -} \ No newline at end of file +} diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java index 3208e1edf1eb..8eb56ca0cb0b 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,16 +25,18 @@ package com.iluwatar.eda.framework; /** - * This interface can be implemented to handle different types of messages. - * Every handler is responsible for a single of type message + * This interface can be implemented to handle different types of messages. Every handler is + * responsible for a single of type message + * * @param Handler can handle events of type E */ public interface Handler { /** - * The onEvent method should implement and handle behavior related to the event. - * This can be as simple as calling another service to handle the event on publishing the event on - * a queue to be consumed by other sub systems. + * The onEvent method should implement and handle behavior related to the event. This can be as + * simple as calling another service to handle the event on publishing the event in a queue to be + * consumed by other sub systems. + * * @param event the {@link Event} object to be handled. */ void onEvent(E event); diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserCreatedEventHandler.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserCreatedEventHandler.java index 3d8e2779fc42..25f2354b5dd2 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserCreatedEventHandler.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserCreatedEventHandler.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,19 +26,14 @@ import com.iluwatar.eda.event.UserCreatedEvent; import com.iluwatar.eda.framework.Handler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * Handles the {@link UserCreatedEvent} message. - */ +/** Handles the {@link UserCreatedEvent} message. */ +@Slf4j public class UserCreatedEventHandler implements Handler { - private static final Logger LOGGER = LoggerFactory.getLogger(UserCreatedEventHandler.class); - @Override public void onEvent(UserCreatedEvent event) { - LOGGER.info("User '{}' has been Created!", event.getUser().getUsername()); + LOGGER.info("User '{}' has been Created!", event.getUser().username()); } - } diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserUpdatedEventHandler.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserUpdatedEventHandler.java index eef5f67854e3..9947af48403c 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserUpdatedEventHandler.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserUpdatedEventHandler.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,18 +26,14 @@ import com.iluwatar.eda.event.UserUpdatedEvent; import com.iluwatar.eda.framework.Handler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * Handles the {@link UserUpdatedEvent} message. - */ +/** Handles the {@link UserUpdatedEvent} message. */ +@Slf4j public class UserUpdatedEventHandler implements Handler { - private static final Logger LOGGER = LoggerFactory.getLogger(UserUpdatedEventHandler.class); - @Override public void onEvent(UserUpdatedEvent event) { - LOGGER.info("User '{}' has been Updated!", event.getUser().getUsername()); + LOGGER.info("User '{}' has been Updated!", event.getUser().username()); } } diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java index 92ea232bcb53..2b9e17693f14 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -26,18 +28,7 @@ import com.iluwatar.eda.event.UserUpdatedEvent; /** - * This {@link User} class is a basic pojo used to demonstrate user data sent along with - * the {@link UserCreatedEvent} and {@link UserUpdatedEvent} events. + * This {@link User} class is a basic pojo used to demonstrate user data sent along with the {@link + * UserCreatedEvent} and {@link UserUpdatedEvent} events. */ -public class User { - - private String username; - - public User(String username) { - this.username = username; - } - - public String getUsername() { - return username; - } -} +public record User(String username) {} diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java index f74232ac1e60..52e08eb9a76a 100644 --- a/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java +++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,21 @@ */ package com.iluwatar.eda; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -import java.io.IOException; +/** Tests that Event Driven Architecture example runs without errors. */ +class AppTest { -/** - * Tests that Event Driven Architecture example runs without errors. - */ -public class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + *

    Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. + */ @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java index 823605e9d302..d3254255e714 100644 --- a/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java +++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,24 +24,22 @@ */ package com.iluwatar.eda.event; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.eda.model.User; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * {@link UserCreatedEventTest} tests and verifies {@link AbstractEvent} behaviour. - */ -public class UserCreatedEventTest { +/** {@link UserCreatedEventTest} tests and verifies {@link AbstractEvent} behaviour. */ +class UserCreatedEventTest { /** * This unit test should correctly return the {@link AbstractEvent} class type when calling the * {@link AbstractEvent#getType() getType} method. */ @Test - public void testGetEventType() { - User user = new User("iluwatar"); - UserCreatedEvent userCreatedEvent = new UserCreatedEvent(user); + void testGetEventType() { + var user = new User("iluwatar"); + var userCreatedEvent = new UserCreatedEvent(user); assertEquals(UserCreatedEvent.class, userCreatedEvent.getType()); } } diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java index 6f647245dce0..f92fde927109 100644 --- a/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java +++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,6 +24,9 @@ */ package com.iluwatar.eda.framework; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + import com.iluwatar.eda.event.UserCreatedEvent; import com.iluwatar.eda.event.UserUpdatedEvent; import com.iluwatar.eda.handler.UserCreatedEventHandler; @@ -29,41 +34,35 @@ import com.iluwatar.eda.model.User; import org.junit.jupiter.api.Test; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -/** - * Event Dispatcher unit tests to assert and verify correct event dispatcher behaviour - */ -public class EventDispatcherTest { +/** Event Dispatcher unit tests to assert and verify correct event dispatcher behaviour */ +class EventDispatcherTest { /** * This unit test should register events and event handlers correctly with the event dispatcher * and events should be dispatched accordingly. */ @Test - public void testEventDriverPattern() { + void testEventDriverPattern() { - EventDispatcher dispatcher = spy(new EventDispatcher()); - UserCreatedEventHandler userCreatedEventHandler = spy(new UserCreatedEventHandler()); - UserUpdatedEventHandler userUpdatedEventHandler = spy(new UserUpdatedEventHandler()); + var dispatcher = spy(new EventDispatcher()); + var userCreatedEventHandler = spy(new UserCreatedEventHandler()); + var userUpdatedEventHandler = spy(new UserUpdatedEventHandler()); dispatcher.registerHandler(UserCreatedEvent.class, userCreatedEventHandler); dispatcher.registerHandler(UserUpdatedEvent.class, userUpdatedEventHandler); - User user = new User("iluwatar"); + var user = new User("iluwatar"); - UserCreatedEvent userCreatedEvent = new UserCreatedEvent(user); - UserUpdatedEvent userUpdatedEvent = new UserUpdatedEvent(user); + var userCreatedEvent = new UserCreatedEvent(user); + var userUpdatedEvent = new UserUpdatedEvent(user); - //fire a userCreatedEvent and verify that userCreatedEventHandler has been invoked. + // fire a userCreatedEvent and verify that userCreatedEventHandler has been invoked. dispatcher.dispatch(userCreatedEvent); verify(userCreatedEventHandler).onEvent(userCreatedEvent); verify(dispatcher).dispatch(userCreatedEvent); - //fire a userCreatedEvent and verify that userUpdatedEventHandler has been invoked. + // fire a userCreatedEvent and verify that userUpdatedEventHandler has been invoked. dispatcher.dispatch(userUpdatedEvent); verify(userUpdatedEventHandler).onEvent(userUpdatedEvent); verify(dispatcher).dispatch(userUpdatedEvent); } - } diff --git a/event-queue/README.md b/event-queue/README.md index 081c0144970c..08d807937ead 100644 --- a/event-queue/README.md +++ b/event-queue/README.md @@ -1,29 +1,185 @@ --- -layout: pattern -title: Event Queue -folder: event-queue -permalink: /patterns/event-queue/ -categories: Concurrency -tags: - - Java - - Difficulty Intermediate - - Queue +title: "Event Queue Pattern in Java: Managing Concurrent Events Efficiently" +shortTitle: Event Queue +description: "Learn about the Event Queue design pattern in Java. Discover its best practices, examples, and how to implement it effectively in your Java projects." +category: Concurrency +language: en +tag: + - Asynchronous + - Decoupling + - Messaging + - Event-driven + - Scalability --- -## Intent -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 -removes it from the queue. +## Also known as -![alt text](./etc/model.png "Event Queue") +* Event Stream +* Message Queue -## Applicability -Use the Event Queue pattern when +## Intent of Event Queue Design Pattern -* You have a limited accessibility resource and the asynchronous process is acceptable to reach that +The Event Queue pattern is designed to manage tasks in an asynchronous manner, allowing applications to handle operations without blocking user interactions or other processes. This improves scalability and system performance. -## Credits +## Detailed Explanation of Event Queue Pattern with Real-World Examples -* [Mihaly Kuprivecz - Event Queue] (http://gameprogrammingpatterns.com/event-queue.html) +Real-world example + +> The modern emailing system is an example of the fundamental process behind the event-queue design pattern. When an email is sent, the sender continues their daily tasks without the necessity of an immediate response from the receiver. Additionally, the receiver has the freedom to access and process the email at their leisure. Therefore, this process decouples the sender and receiver so that they are not required to engage with the queue at the same time. + +In plain words + +> The buffer between sender and receiver improves maintainability and scalability of a system. Event queues are typically used to organize and carry out interprocess communication (IPC). + +Wikipedia says + +> Message queues (also known as event queues) implement an asynchronous communication pattern between two or more processes/threads whereby the sending and receiving party do not need to interact with the queue at the same time. + +Sequence diagram + +![Event Queue sequence diagram](./etc/event-queue-sequence-diagram.png) + +## Programmatic Example of Event Queue Pattern in Java + +This example demonstrates an application using an event queue system to handle audio playback asynchronously. + +The `App` class sets up an instance of `Audio`, plays two sounds, and waits for user input to exit. It demonstrates how an event queue could be used to manage asynchronous operations in a software application. + +```java +public class App { + + public static void main(String[] args) throws UnsupportedAudioFileException, IOException, + InterruptedException { + var audio = Audio.getInstance(); + audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); + audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f); + + LOGGER.info("Press Enter key to stop the program..."); + try (var br = new BufferedReader(new InputStreamReader(System.in))) { + br.read(); + } + audio.stopService(); + } +} +``` + +The `Audio` class holds the singleton pattern implementation, manages a queue of audio play requests, and controls thread operations for asynchronous processing. + +```java +public class Audio { + private static final Audio INSTANCE = new Audio(); + + private static final int MAX_PENDING = 16; + + private int headIndex; + + private int tailIndex; + + private volatile Thread updateThread = null; + + private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING]; + + Audio() {} + + public static Audio getInstance() { + return INSTANCE; + } +} +``` + +These methods manage the lifecycle of the thread used to process the audio events. The `init` and `startThread` methods ensure the thread is properly initialized and running. + +```java +public synchronized void stopService() throws InterruptedException { + if(updateThread != null) { + updateThread.interrupt(); + updateThread.join(); + updateThread = null; + } +} + +public synchronized boolean isServiceRunning() { + return updateThread != null && updateThread.isAlive(); +} + +public void init() { + if(updateThread == null) { + updateThread = new Thread(() -> { + while (!Thread.currentThread().isInterrupted()) { + update(); + } + }); + startThread(); + } +} + +private synchronized void startThread() { + if (!updateThread.isAlive()) { + updateThread.start(); + headIndex = 0; + tailIndex = 0; + } +} +``` + +The `playSound` method checks if the audio is already in the queue and either updates the volume or enqueues a new request, demonstrating the management of asynchronous tasks within the event queue. + +```java +public void playSound(AudioInputStream stream, float volume) { + init(); + for(var i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) { + var playMessage = getPendingAudio()[i]; + if(playMessage.getStream() == stream) { + playMessage.setVolume(Math.max(volume, playMessage.getVolume())); + return; + } + } + getPendingAudio()[tailIndex] = new PlayMessage(stream, volume); + tailIndex = (tailIndex + 1) % MAX_PENDING; +} +``` + +## When to Use the Event Queue Pattern in Java + +This pattern is applicable in scenarios where tasks can be handled asynchronously outside the main application flow, such as in GUI applications, server-side event handling, or in systems that require task scheduling without immediate execution. In particular: + +* The sender does not require a response from the receiver. +* You wish to decouple the sender & the receiver. +* You want to process events asynchronously. +* You have a limited accessibility resource and the asynchronous process is acceptable to reach that. + +## Real-World Applications of Event Queue Pattern in Java + +* Event-driven architectures +* GUI frameworks in Java (such as Swing and JavaFX) +* Server applications handling requests asynchronously + +## Benefits and Trade-offs of Event Queue Pattern + +Benefits: + +* Reduces system coupling. +* Enhances responsiveness of applications. +* Improves scalability by allowing event handling to be distributed across multiple threads or processors. + +Trade-offs: + +* Complexity in managing the event queue. +* Potential for difficult-to-track bugs due to asynchronous behavior. +* Overhead of maintaining event queue integrity and performance. +* As the event queue model decouples the sender-receiver relationship - this means that the event-queue design pattern is unsuitable for scenarios in which the sender requires a response. For example, this is a prominent feature within online multiplayer games, therefore, this approach requires thorough consideration. + +## Related Java Design Patterns + +* [Command](https://java-design-patterns.com/patterns/command/) (for encapsulating request processing in a command object) +* [Observer](https://java-design-patterns.com/patterns/observer/) (for subscribing and notifying changes to multiple observers) +* [Reactor](https://java-design-patterns.com/patterns/reactor/) (handles requests in a non-blocking event-driven manner similar to Event Queue) + +## References and Credits + +* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3xzSlC2) +* [Game Programming Patterns](https://amzn.to/3K96fOn) +* [Java Concurrency in Practice](https://amzn.to/3Ji16mX) +* [Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3U2hlcy) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3xtVtPJ) +* [Event Queue (Game Programming Patterns)](http://gameprogrammingpatterns.com/event-queue.html) diff --git a/event-queue/etc/event-queue-sequence-diagram.png b/event-queue/etc/event-queue-sequence-diagram.png new file mode 100644 index 000000000000..26e01a79e18e Binary files /dev/null and b/event-queue/etc/event-queue-sequence-diagram.png differ diff --git a/event-queue/etc/event-queue.urm.puml b/event-queue/etc/event-queue.urm.puml new file mode 100644 index 000000000000..de4390e4e599 --- /dev/null +++ b/event-queue/etc/event-queue.urm.puml @@ -0,0 +1,38 @@ +@startuml +package com.iluwatar.event.queue { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Audio { + - INSTANCE : Audio {static} + - LOGGER : Logger {static} + - MAX_PENDING : int {static} + - headIndex : int + - pendingAudio : PlayMessage[] + - tailIndex : int + - updateThread : Thread + ~ Audio() + + getAudioStream(filePath : String) : AudioInputStream + + getInstance() : Audio {static} + + getPendingAudio() : PlayMessage[] + + init() + + isServiceRunning() : boolean + + playSound(stream : AudioInputStream, volume : float) + - startThread() + + stopService() + - update() + } + class PlayMessage { + - stream : AudioInputStream + - volume : float + + PlayMessage(stream : AudioInputStream, volume : float) + + getStream() : AudioInputStream + + getVolume() : float + - setStream(stream : AudioInputStream) + + setVolume(volume : float) + } +} +Audio --> "-INSTANCE" Audio +@enduml \ No newline at end of file diff --git a/event-queue/etc/model.png b/event-queue/etc/model.png deleted file mode 100644 index 45620e6f69a1..000000000000 Binary files a/event-queue/etc/model.png and /dev/null differ diff --git a/event-queue/etc/model.ucls b/event-queue/etc/model.ucls deleted file mode 100644 index ed923014b40c..000000000000 --- a/event-queue/etc/model.ucls +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/event-queue/pom.xml b/event-queue/pom.xml index a0c1913a7a56..4b7566df445b 100644 --- a/event-queue/pom.xml +++ b/event-queue/pom.xml @@ -1,8 +1,10 @@ - + 4.0.0 java-design-patterns com.iluwatar - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT event-queue - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -45,4 +48,23 @@ test - \ No newline at end of file + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.event.queue.App + + + + + + + + + diff --git a/event-queue/src/main/java/com/iluwatar/event/queue/App.java b/event-queue/src/main/java/com/iluwatar/event/queue/App.java index ea107d6ca4cd..3ea957a5a9be 100644 --- a/event-queue/src/main/java/com/iluwatar/event/queue/App.java +++ b/event-queue/src/main/java/com/iluwatar/event/queue/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,40 +22,44 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.event.queue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; - import javax.sound.sampled.UnsupportedAudioFileException; +import lombok.extern.slf4j.Slf4j; /** * Event or message queues provide an asynchronous communications protocol, meaning that the sender - * and receiver of the message do not need to interact with the message queue at the same time. - * Events or messages placed onto the queue are stored until the recipient retrieves them. Event - * or message queues have implicit or explicit limits on the size of data that may be transmitted - * in a single message and the number of messages that may remain outstanding on the queue. - * A queue stores a series of notifications or requests in first-in, first-out order. - * Sending a notification enqueues the request and returns. The request processor then processes - * items from the queue at a later time. + * and receiver of the message do not need to interact with the message queue at the same time. + * Events or messages placed onto the queue are stored until the recipient retrieves them. Event or + * message queues have implicit or explicit limits on the size of data that may be transmitted in a + * single message and the number of messages that may remain outstanding on the queue. A queue + * stores a series of notifications or requests in first-in, first-out order. Sending a notification + * enqueues the request and returns. The request processor then processes items from the queue at a + * later time. */ +@Slf4j public class App { + /** * Program entry point. - * + * * @param args command line args * @throws IOException when there is a problem with the audio file loading - * @throws UnsupportedAudioFileException when the loaded audio file is unsupported + * @throws UnsupportedAudioFileException when the loaded audio file is unsupported */ - public static void main(String[] args) throws UnsupportedAudioFileException, IOException { - Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); - Audio.playSound(Audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f); - - System.out.println("Press Enter key to stop the program..."); - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - br.read(); - Audio.stopService(); + public static void main(String[] args) + throws UnsupportedAudioFileException, IOException, InterruptedException { + var audio = Audio.getInstance(); + audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); + audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f); + + LOGGER.info("Press Enter key to stop the program..."); + try (var br = new BufferedReader(new InputStreamReader(System.in))) { + br.read(); + } + audio.stopService(); } } diff --git a/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java b/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java index 6534b563e2c7..02bee71b86e2 100644 --- a/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java +++ b/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,77 +22,76 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.event.queue; import java.io.File; import java.io.IOException; - import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; -import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; -/** - * This class implements the Event Queue pattern. - * @author mkuprivecz - * - */ +/** This class implements the Event Queue pattern. */ +@Slf4j public class Audio { + private static final Audio INSTANCE = new Audio(); private static final int MAX_PENDING = 16; - private static int headIndex; + private int headIndex; - private static int tailIndex; + private int tailIndex; - private static Thread updateThread = null; + private volatile Thread updateThread = null; - private static PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING]; + @Getter private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING]; - /** - * This method stops the Update Method's thread. - */ - public static synchronized void stopService() { + // Visible only for testing purposes + Audio() {} + + public static Audio getInstance() { + return INSTANCE; + } + + /** This method stops the Update Method's thread and waits till service stops. */ + public synchronized void stopService() throws InterruptedException { if (updateThread != null) { updateThread.interrupt(); } + updateThread.join(); + updateThread = null; } - + /** * This method check the Update Method's thread is started. + * * @return boolean */ - public static synchronized boolean isServiceRunning() { - if (updateThread != null && updateThread.isAlive() ) { - return true; - } else { - return false; - } + public synchronized boolean isServiceRunning() { + return updateThread != null && updateThread.isAlive(); } /** - * Starts the thread for the Update Method pattern if it was not started previously. - * Also when the thread is is ready initializes the indexes of the queue + * Starts the thread for the Update Method pattern if it was not started previously. Also, when + * the thread is ready initializes the indexes of the queue */ - public static void init() { + public void init() { if (updateThread == null) { - updateThread = new Thread(new Runnable() { - public void run() { - while (!Thread.currentThread().isInterrupted()) { - Audio.update(); - } - } - }); + updateThread = + new Thread( + () -> { + while (!Thread.currentThread().isInterrupted()) { + update(); + } + }); } startThread(); } - - /** - * This is a synchronized thread starter - */ - public static synchronized void startThread() { + + /** This is a synchronized thread starter. */ + private synchronized void startThread() { if (!updateThread.isAlive()) { updateThread.start(); headIndex = 0; @@ -100,16 +101,18 @@ public static synchronized void startThread() { /** * This method adds a new audio into the queue. + * * @param stream is the AudioInputStream for the method - * @param volume is the level of the audio's volume + * @param volume is the level of the audio's volume */ - public static void playSound(AudioInputStream stream, float volume) { + public void playSound(AudioInputStream stream, float volume) { init(); // Walk the pending requests. - for (int i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) { - if (getPendingAudio()[i].getStream() == stream) { + for (var i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) { + var playMessage = getPendingAudio()[i]; + if (playMessage.getStream() == stream) { // Use the larger of the two volumes. - getPendingAudio()[i].setVolume(Math.max(volume, getPendingAudio()[i].getVolume())); + playMessage.setVolume(Math.max(volume, playMessage.getVolume())); // Don't need to enqueue. return; @@ -118,52 +121,38 @@ public static void playSound(AudioInputStream stream, float volume) { getPendingAudio()[tailIndex] = new PlayMessage(stream, volume); tailIndex = (tailIndex + 1) % MAX_PENDING; } - - /** - * This method uses the Update Method pattern. - * It takes the audio from the queue and plays it - */ - public static void update() { + + /** This method uses the Update Method pattern. It takes the audio from the queue and plays it */ + private void update() { // If there are no pending requests, do nothing. if (headIndex == tailIndex) { return; } - Clip clip = null; try { - AudioInputStream audioStream = getPendingAudio()[headIndex].getStream(); + var audioStream = getPendingAudio()[headIndex].getStream(); headIndex++; - clip = AudioSystem.getClip(); + var clip = AudioSystem.getClip(); clip.open(audioStream); clip.start(); } catch (LineUnavailableException e) { - System.err.println("Error occoured while loading the audio: The line is unavailable"); - e.printStackTrace(); + LOGGER.trace("Error occurred while loading the audio: The line is unavailable", e); } catch (IOException e) { - System.err.println("Input/Output error while loading the audio"); - e.printStackTrace(); + LOGGER.trace("Input/Output error while loading the audio", e); } catch (IllegalArgumentException e) { - System.err.println("The system doesn't support the sound: " + e.getMessage()); + LOGGER.trace("The system doesn't support the sound: " + e.getMessage(), e); } } /** - * Returns the AudioInputStream of a file + * Returns the AudioInputStream of a file. + * * @param filePath is the path of the audio file * @return AudioInputStream - * @throws UnsupportedAudioFileException when the audio file is not supported + * @throws UnsupportedAudioFileException when the audio file is not supported * @throws IOException when the file is not readable */ - public static AudioInputStream getAudioStream(String filePath) + public AudioInputStream getAudioStream(String filePath) throws UnsupportedAudioFileException, IOException { return AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile()); } - - /** - * Returns with the message array of the queue - * @return PlayMessage[] - */ - public static PlayMessage[] getPendingAudio() { - return pendingAudio; - } - } diff --git a/event-queue/src/main/java/com/iluwatar/event/queue/PlayMessage.java b/event-queue/src/main/java/com/iluwatar/event/queue/PlayMessage.java index 5ced2e3b3811..60f328d79bd0 100644 --- a/event-queue/src/main/java/com/iluwatar/event/queue/PlayMessage.java +++ b/event-queue/src/main/java/com/iluwatar/event/queue/PlayMessage.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,40 +22,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.event.queue; import javax.sound.sampled.AudioInputStream; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; -/** - * The Event Queue's queue will store the instances of this class. - * @author mkuprivecz - * - */ +/** The Event Queue's queue will store the instances of this class. */ +@Getter +@AllArgsConstructor public class PlayMessage { - - private AudioInputStream stream; - - private float volume; - - public PlayMessage(AudioInputStream stream, float volume) { - setStream(stream); - setVolume(volume); - } - - public AudioInputStream getStream() { - return stream; - } - - private void setStream(AudioInputStream stream) { - this.stream = stream; - } - public float getVolume() { - return volume; - } + private final AudioInputStream stream; - public void setVolume(float volume) { - this.volume = volume; - } + @Setter private float volume; } diff --git a/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java b/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java index 47f332526d26..4f2abbdac895 100644 --- a/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java +++ b/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,60 +22,66 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.event.queue; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import javax.sound.sampled.UnsupportedAudioFileException; import java.io.IOException; +import javax.sound.sampled.UnsupportedAudioFileException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +/** Testing the Audio service of the Queue */ +class AudioTest { + private Audio audio; -/** - * Testing the Audio service of the Queue - * @author mkuprivecz - * - */ -public class AudioTest { + @BeforeEach + void createAudioInstance() { + audio = new Audio(); + } /** * Test here that the playSound method works correctly - * @throws UnsupportedAudioFileException when the audio file is not supported + * + * @throws UnsupportedAudioFileException when the audio file is not supported * @throws IOException when the file is not readable * @throws InterruptedException when the test is interrupted externally */ @Test - public void testPlaySound() throws UnsupportedAudioFileException, IOException, InterruptedException { - Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); + void testPlaySound() throws UnsupportedAudioFileException, IOException, InterruptedException { + audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); // test that service is started - assertTrue(Audio.isServiceRunning()); + assertTrue(audio.isServiceRunning()); // adding a small pause to be sure that the sound is ended Thread.sleep(5000); + + audio.stopService(); // test that service is finished - assertFalse(!Audio.isServiceRunning()); + assertFalse(audio.isServiceRunning()); } /** * Test here that the Queue - * @throws UnsupportedAudioFileException when the audio file is not supported + * + * @throws UnsupportedAudioFileException when the audio file is not supported * @throws IOException when the file is not readable * @throws InterruptedException when the test is interrupted externally */ @Test - public void testQueue() throws UnsupportedAudioFileException, IOException, InterruptedException { - Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); - Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); - Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); - assertTrue(Audio.getPendingAudio().length > 0); + void testQueue() throws UnsupportedAudioFileException, IOException, InterruptedException { + audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); + audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); + audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); + assertTrue(audio.getPendingAudio().length > 0); // test that service is started - assertTrue(Audio.isServiceRunning()); + assertTrue(audio.isServiceRunning()); // adding a small pause to be sure that the sound is ended Thread.sleep(10000); + + audio.stopService(); // test that service is finished - assertFalse(!Audio.isServiceRunning()); + assertFalse(audio.isServiceRunning()); } - } diff --git a/event-sourcing/README.md b/event-sourcing/README.md index 1079405fa885..4de1c2dd5025 100644 --- a/event-sourcing/README.md +++ b/event-sourcing/README.md @@ -1,33 +1,245 @@ --- -layout: pattern -title: Event Sourcing -folder: event-sourcing -permalink: /patterns/event-sourcing/ -categories: Architectural -tags: - - Java - - Difficulty Intermediate - - Performance +title: "Event Sourcing Pattern in Java: Building Immutable Historical Records for Robust Systems" +shortTitle: Event Sourcing +description: "Discover the Event Sourcing design pattern in Java. Learn how it stores state changes as events and benefits complex applications. See examples and explanations on Java Design Patterns." +category: Architectural +language: en +tag: + - Decoupling + - Event-driven + - Fault tolerance + - Messaging + - Persistence + - Scalability + - Transactions +head: + - - meta + - name: keywords + content: --- -## 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. +## Also known as -![alt text](./etc/event-sourcing.png "Event Sourcing") +* Event Logging +* Event Streaming -## Applicability -Use the Event Sourcing pattern when +## Intent of Event Sourcing Design Pattern -* 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. +Event Sourcing is a design pattern that advocates for the storage of state changes as a sequence of events. Instead of updating a record in a database, all changes are stored as individual events which, when replayed, can recreate the state of an application at any point in time. -## Real world examples +## Detailed Explanation of Event Sourcing Pattern with Real-World Examples -* [The Lmax Architecture] (https://martinfowler.com/articles/lmax.html) +Real-world example -## Credits +> Consider a banking application that tracks all transactions for user accounts. In this system, every deposit, withdrawal, and transfer is recorded as an individual event in an event log. Instead of simply updating the current account balance, each transaction is stored as a discrete event. This approach allows the bank to maintain a complete and immutable history of all account activities. If a discrepancy occurs, the bank can replay the sequence of events to reconstruct the account state at any point in time. This provides a robust audit trail, facilitates debugging, and supports features like transaction rollback and historical data analysis. -* [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) +In plain words + +> Event Sourcing records all state changes as a sequence of immutable events to ensure reliable state reconstruction and auditability. + +[Microsoft's documentation](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing) says + +> The Event Sourcing pattern defines an approach to handling operations on data that's driven by a sequence of events, each of which is recorded in an append-only store. Application code sends a series of events that imperatively describe each action that has occurred on the data to the event store, where they're persisted. Each event represents a set of changes to the data (such as AddedItemToOrder). + +Architecture diagram + +![Event Sourcing Architecture Diagram](./etc/event-sourcing-architecture-diagram.png) + +## Programmatic Example of Event Sourcing Pattern in Java + +In the programmatic example we transfer some money between bank accounts. + +The `Event` class manages a queue of events and controls thread operations for asynchronous processing. Each event can be seen as a state change that affects the state of the system. + +```java +public class Event { + private static final Event INSTANCE = new Event(); + + private static final int MAX_PENDING = 16; + + private int headIndex; + + private int tailIndex; + + private volatile Thread updateThread = null; + + private final EventMessage[] pendingEvents = new EventMessage[MAX_PENDING]; + + Event() {} + + public static Event getInstance() { + return INSTANCE; + } +} +``` + +The `triggerEvent` method is where the events are created. Each time an event is triggered, it is created and added to the queue. This event contains the details of the state change. + +```java +public void triggerEvent(EventMessage eventMessage) { + init(); + for(var i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) { + var pendingEvent = getPendingEvents()[i]; + if(pendingEvent.equals(eventMessage)) { + return; + } + } + getPendingEvents()[tailIndex] = eventMessage; + tailIndex = (tailIndex + 1) % MAX_PENDING; +} +``` + +The `init` and `startThread` methods ensure the thread is properly initialized and running. The `stopService` method is used to stop the thread when it's no longer needed. These methods manage the lifecycle of the thread used to process the events. + +```java +public synchronized void stopService() throws InterruptedException { + if(updateThread != null) { + updateThread.interrupt(); + updateThread.join(); + updateThread = null; + } +} + +public synchronized boolean isServiceRunning() { + return updateThread != null && updateThread.isAlive(); +} + +public void init() { + if(updateThread == null) { + updateThread = new Thread(() -> { + while (!Thread.currentThread().isInterrupted()) { + update(); + } + }); + startThread(); + } +} + +private synchronized void startThread() { + if (!updateThread.isAlive()) { + updateThread.start(); + headIndex = 0; + tailIndex = 0; + } +} +``` + +The example is driven by the `App` class and its `main` method. + +```java +@Slf4j +public class App { + + public static final int ACCOUNT_OF_DAENERYS = 1; + + public static final int ACCOUNT_OF_JON = 2; + + public static void main(String[] args) { + + var eventProcessor = new DomainEventProcessor(new JsonFileJournal()); + + LOGGER.info("Running the system first time............"); + eventProcessor.reset(); + + LOGGER.info("Creating the 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 shut down, state in memory is cleared............"); + AccountAggregate.resetState(); + + LOGGER.info("Recover the system by the events in journal file............"); + + eventProcessor = new DomainEventProcessor(new JsonFileJournal()); + eventProcessor.recover(); + + LOGGER.info("...............Recovered State:............"); + LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString()); + LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString()); + } +} +``` + +Running the example produces the following console output. + +``` +22:40:47.982 [main] INFO com.iluwatar.event.sourcing.app.App -- Running the system first time............ +22:40:47.984 [main] INFO com.iluwatar.event.sourcing.app.App -- Creating the accounts............ +22:40:47.985 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here. +22:40:48.089 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here. +22:40:48.090 [main] INFO com.iluwatar.event.sourcing.app.App -- Do some money operations............ +22:40:48.090 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here. +22:40:48.095 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here. +22:40:48.099 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here. +22:40:48.099 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here. +22:40:48.101 [main] INFO com.iluwatar.event.sourcing.app.App -- ...............State:............ +22:40:48.104 [main] INFO com.iluwatar.event.sourcing.app.App -- Account{accountNo=1, owner='Daenerys Targaryen', money=90000} +22:40:48.104 [main] INFO com.iluwatar.event.sourcing.app.App -- Account{accountNo=2, owner='Jon Snow', money=10100} +22:40:48.104 [main] INFO com.iluwatar.event.sourcing.app.App -- At that point system had a shut down, state in memory is cleared............ +22:40:48.104 [main] INFO com.iluwatar.event.sourcing.app.App -- Recover the system by the events in journal file............ +22:40:48.124 [main] INFO com.iluwatar.event.sourcing.app.App -- ...............Recovered State:............ +22:40:48.124 [main] INFO com.iluwatar.event.sourcing.app.App -- Account{accountNo=1, owner='Daenerys Targaryen', money=90000} +22:40:48.124 [main] INFO com.iluwatar.event.sourcing.app.App -- Account{accountNo=2, owner='Jon Snow', money=10100} +``` + +In this example, the state of the system can be recreated at any point by replaying the events in the queue. This is a key feature of the Event Sourcing pattern. + +## When to Use the Event Sourcing Pattern in Java + +* In systems where complete audit trails and historical changes are crucial. +* In complex domains where the state of an application is derived from a series of changes. +* For systems that benefit from high availability and scalability as Event Sourcing naturally lends itself to distributed systems. + +## Real-World Applications of Event Sourcing Pattern in Java + +* Financial systems to track transactions and account balances over time. +* E-commerce applications for order and inventory management. +* Real-time data processing systems where event consistency and replayability are critical. +* [The LMAX Architecture](https://martinfowler.com/articles/lmax.html) + +## Benefits and Trade-offs of Event Sourcing Pattern + +Benefits: + +* Auditability: Each change to the state is recorded, allowing for comprehensive auditing. +* Replayability: Events can be reprocessed to recreate historical states or move to new states. +* Scalability: Events can be processed asynchronously and in parallel. + +Trade-offs + +* Complexity: Implementing and maintaining an event-sourced system can introduce additional complexity. +* Event store size: Storing every state change can lead to large data volumes. +* Event versioning: Changes in event structure over time require careful handling to ensure system integrity. + +## Related Java Design Patterns + +* [Command Query Responsibility Segregation (CQRS)](https://java-design-patterns.com/patterns/cqrs/): Often used together with Event Sourcing to separate read and write responsibilities, enhancing performance and scalability. +* Snapshot: Used to optimize Event Sourcing systems by periodically saving the current state to avoid replaying a long sequence of events. + +## References and Credits + +* [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/443WfiS) +* [Implementing Domain-Driven Design](https://amzn.to/3JgvA8V) +* [Patterns, Principles, and Practices of Domain-Driven Design](https://amzn.to/3VVhfWX) +* [Event Sourcing (Martin Fowler)](https://martinfowler.com/eaaDev/EventSourcing.html) +* [Event Sourcing pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing) diff --git a/event-sourcing/etc/event-sourcing-architecture-diagram.png b/event-sourcing/etc/event-sourcing-architecture-diagram.png new file mode 100644 index 000000000000..2ad8b3531e56 Binary files /dev/null and b/event-sourcing/etc/event-sourcing-architecture-diagram.png differ diff --git a/event-sourcing/etc/event-sourcing.urm.puml b/event-sourcing/etc/event-sourcing.urm.puml new file mode 100644 index 000000000000..363af9967012 --- /dev/null +++ b/event-sourcing/etc/event-sourcing.urm.puml @@ -0,0 +1,107 @@ +@startuml +package com.iluwatar.event.sourcing.processor { + class DomainEventProcessor { + - processorJournal : JsonFileJournal + + DomainEventProcessor() + + process(domainEvent : DomainEvent) + + recover() + + reset() + } + class JsonFileJournal { + - events : List + - file : File + - index : int + + JsonFileJournal() + + readNext() : DomainEvent + + reset() + + write(domainEvent : DomainEvent) + } +} +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() + } + 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) + } + 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() + } +} +package com.iluwatar.event.sourcing.app { + class App { + + ACCOUNT_OF_DAENERYS : int {static} + + ACCOUNT_OF_JON : int {static} + - LOGGER : Logger {static} + + 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 { + - LOGGER : Logger {static} + - MSG : String {static} + - accountNo : int + - money : BigDecimal + - owner : String + + Account(accountNo : int, owner : String) + + copy() : Account + - depositMoney(money : BigDecimal) + + getAccountNo() : int + + getMoney() : BigDecimal + + getOwner() : String + - handleDeposit(money : BigDecimal, realTime : boolean) + + handleEvent(accountCreateEvent : AccountCreateEvent) + + handleEvent(moneyDepositEvent : MoneyDepositEvent) + + handleTransferFromEvent(moneyTransferEvent : MoneyTransferEvent) + + handleTransferToEvent(moneyTransferEvent : MoneyTransferEvent) + - handleWithdrawal(money : BigDecimal, realTime : boolean) + + setMoney(money : BigDecimal) + + toString() : String + - withdrawMoney(money : BigDecimal) + } +} +DomainEventProcessor --> "-processorJournal" JsonFileJournal +AccountCreateEvent --|> DomainEvent +MoneyDepositEvent --|> DomainEvent +MoneyTransferEvent --|> DomainEvent +@enduml \ No newline at end of file diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml index 785d72c68324..5660054d8195 100644 --- a/event-sourcing/pom.xml +++ b/event-sourcing/pom.xml @@ -1,8 +1,10 @@ - + 4.0.0 java-design-patterns com.iluwatar - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT event-sourcing - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter junit-jupiter-engine test - - com.google.code.gson - gson - 2.8.1 + com.fasterxml.jackson.core + jackson-core + 2.19.0 + + + com.fasterxml.jackson.core + jackson-databind + 2.18.3 - - \ No newline at end of file + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.event.sourcing.App + + + + + + + + + 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 index 50e9b503edbd..a625e9ace9d3 100644 --- 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -26,14 +28,14 @@ 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.processor.JsonFileJournal; import com.iluwatar.event.sourcing.state.AccountAggregate; import java.math.BigDecimal; import java.util.Date; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * Event Sourcing : Instead of storing just the current state of the data in a domain, use an + * 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, @@ -41,24 +43,20 @@ * 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. + *

    This App class is an example usage of an Event Sourcing pattern. As an example, two bank + * accounts are 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 shut-down. + * After the shut-down, system state is recovered by re-creating the past events from event + * journals. Then state is printed so a user can view the last state is same with the state before a + * system shut-down. */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * The constant ACCOUNT OF DAENERYS. - */ + /** The constant ACCOUNT OF DAENERYS. */ public static final int ACCOUNT_OF_DAENERYS = 1; - /** - * The constant ACCOUNT OF JON. - */ + + /** The constant ACCOUNT OF JON. */ public static final int ACCOUNT_OF_JON = 2; /** @@ -68,48 +66,46 @@ public class App { */ public static void main(String[] args) { - DomainEventProcessor eventProcessor = new DomainEventProcessor(); - + var eventProcessor = new DomainEventProcessor(new JsonFileJournal()); LOGGER.info("Running the system first time............"); eventProcessor.reset(); - LOGGER.info("Creating th accounts............"); + LOGGER.info("Creating the accounts............"); - eventProcessor.process(new AccountCreateEvent( - 0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); + 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 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( + 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 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)); + 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............"); + LOGGER.info("At that point system had a shut down, state in memory is cleared............"); AccountAggregate.resetState(); LOGGER.info("Recover the system by the events in journal file............"); - eventProcessor = new DomainEventProcessor(); + eventProcessor = new DomainEventProcessor(new JsonFileJournal()); 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 index d2e5f429b5d4..89f4219d740b 100644 --- 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -27,72 +29,30 @@ 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; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; /** - * 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. + * 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. + *

    Created by Serdar Hamzaogullari on 06.08.2017. */ +@Setter +@Getter +@RequiredArgsConstructor +@Slf4j 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; - } + private BigDecimal money = BigDecimal.ZERO; + private static final String MSG = + "Some external api for only realtime execution could be called here."; /** * Copy account. @@ -100,7 +60,7 @@ public void setMoney(BigDecimal money) { * @return the account */ public Account copy() { - Account account = new Account(accountNo, owner); + var account = new Account(accountNo, owner); account.setMoney(money); return account; } @@ -108,9 +68,13 @@ public Account copy() { @Override public String toString() { return "Account{" - + "accountNo=" + accountNo - + ", owner='" + owner + '\'' - + ", money=" + money + + "accountNo=" + + accountNo + + ", owner='" + + owner + + '\'' + + ", money=" + + money + '}'; } @@ -126,19 +90,19 @@ 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."); + LOGGER.info(MSG); } } private void handleWithdrawal(BigDecimal money, boolean realTime) { - if (this.money.compareTo(money) == -1) { + if (this.money.compareTo(money) < 0) { 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."); + LOGGER.info(MSG); } } @@ -151,16 +115,15 @@ public void handleEvent(MoneyDepositEvent moneyDepositEvent) { handleDeposit(moneyDepositEvent.getMoney(), moneyDepositEvent.isRealTime()); } - /** * Handles the AccountCreateEvent. * - * @param accountCreateEvent the account create event + * @param accountCreateEvent the account created 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."); + LOGGER.info(MSG); } } @@ -181,6 +144,4 @@ public void handleTransferFromEvent(MoneyTransferEvent moneyTransferEvent) { 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 index c526396f3976..087752cbf9c6 100644 --- 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,57 +24,47 @@ */ package com.iluwatar.event.sourcing.event; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import com.iluwatar.event.sourcing.domain.Account; import com.iluwatar.event.sourcing.state.AccountAggregate; +import lombok.Getter; /** - * 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 + * This is the class that implements account created event. Holds the necessary info for an account + * created 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. + *

    Created by Serdar Hamzaogullari on 06.08.2017. */ +@Getter public class AccountCreateEvent extends DomainEvent { private final int accountNo; private final String owner; /** - * Instantiates a new Account create event. + * Instantiates a new Account created 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) { + @JsonCreator + public AccountCreateEvent( + @JsonProperty("sequenceId") long sequenceId, + @JsonProperty("createdTime") long createdTime, + @JsonProperty("accountNo") int accountNo, + @JsonProperty("owner") 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); + var account = AccountAggregate.getAccount(accountNo); if (account != null) { throw new RuntimeException("Account already exists"); } 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 index fa6539a4fba2..f39ebda43eb0 100644 --- 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,12 +25,18 @@ package com.iluwatar.event.sourcing.event; import java.io.Serializable; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; /** * This is the base class for domain events. All events must extend this class. * - * Created by Serdar Hamzaogullari on 06.08.2017. + *

    Created by Serdar Hamzaogullari on 06.08.2017. */ +@Setter +@Getter +@RequiredArgsConstructor public abstract class DomainEvent implements Serializable { private final long sequenceId; @@ -36,66 +44,6 @@ public abstract class DomainEvent implements Serializable { 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. - */ + /** 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 index 1629263a7ec6..4f80ec6b6dfc 100644 --- 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,21 @@ */ package com.iluwatar.event.sourcing.event; -import com.iluwatar.event.sourcing.domain.Account; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import com.iluwatar.event.sourcing.state.AccountAggregate; import java.math.BigDecimal; +import java.util.Optional; +import lombok.Getter; /** - * 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 + * 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. + *

    Created by Serdar Hamzaogullari on 06.08.2017. */ +@Getter public class MoneyDepositEvent extends DomainEvent { private final BigDecimal money; @@ -47,36 +52,22 @@ public class MoneyDepositEvent extends DomainEvent { * @param accountNo the account no * @param money the money */ - public MoneyDepositEvent(long sequenceId, long createdTime, int accountNo, BigDecimal money) { + @JsonCreator + public MoneyDepositEvent( + @JsonProperty("sequenceId") long sequenceId, + @JsonProperty("createdTime") long createdTime, + @JsonProperty("accountNo") int accountNo, + @JsonProperty("money") 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"); - } + var account = + Optional.ofNullable(AccountAggregate.getAccount(accountNo)) + .orElseThrow(() -> 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 index 0307d3af712f..e6e257dded04 100644 --- 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,21 @@ */ package com.iluwatar.event.sourcing.event; -import com.iluwatar.event.sourcing.domain.Account; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import com.iluwatar.event.sourcing.state.AccountAggregate; import java.math.BigDecimal; +import java.util.Optional; +import lombok.Getter; /** - * 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 + * 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. + *

    Created by Serdar Hamzaogullari on 06.08.2017. */ +@Getter public class MoneyTransferEvent extends DomainEvent { private final BigDecimal money; @@ -49,52 +54,27 @@ public class MoneyTransferEvent extends DomainEvent { * @param accountNoFrom the account no from * @param accountNoTo the account no to */ - public MoneyTransferEvent(long sequenceId, long createdTime, BigDecimal money, int accountNoFrom, - int accountNoTo) { + @JsonCreator + public MoneyTransferEvent( + @JsonProperty("sequenceId") long sequenceId, + @JsonProperty("createdTime") long createdTime, + @JsonProperty("money") BigDecimal money, + @JsonProperty("accountNoFrom") int accountNoFrom, + @JsonProperty("accountNoTo") 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); - } - + var accountFrom = + Optional.ofNullable(AccountAggregate.getAccount(accountNoFrom)) + .orElseThrow(() -> new RuntimeException("Account not found " + accountNoFrom)); + var accountTo = + Optional.ofNullable(AccountAggregate.getAccount(accountNoTo)) + .orElseThrow(() -> new RuntimeException("Account not found " + accountNoTo)); accountFrom.handleTransferFromEvent(this); accountTo.handleTransferToEvent(this); } diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java index 05308c7c1f3a..6b0658b40a43 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,15 +27,18 @@ import com.iluwatar.event.sourcing.event.DomainEvent; /** - * This is the implementation of event processor. - * All events are processed by this class. - * This processor uses processorJournal to persist and recover events. + * This is the implementation of event processor. All events are processed by this class. This + * processor uses eventJournal to persist and recover events. * - * Created by Serdar Hamzaogullari on 06.08.2017. + *

    Created by Serdar Hamzaogullari on 06.08.2017. */ public class DomainEventProcessor { - private final JsonFileJournal processorJournal = new JsonFileJournal(); + private final EventJournal eventJournal; + + public DomainEventProcessor(EventJournal eventJournal) { + this.eventJournal = eventJournal; + } /** * Process. @@ -42,28 +47,19 @@ public class DomainEventProcessor { */ public void process(DomainEvent domainEvent) { domainEvent.process(); - processorJournal.write(domainEvent); + eventJournal.write(domainEvent); } - /** - * Reset. - */ + /** Reset. */ public void reset() { - processorJournal.reset(); + eventJournal.reset(); } - /** - * Recover. - */ + /** Recover. */ public void recover() { DomainEvent domainEvent; - while (true) { - domainEvent = processorJournal.readNext(); - if (domainEvent == null) { - break; - } else { - domainEvent.process(); - } + while ((domainEvent = eventJournal.readNext()) != null) { + domainEvent.process(); } } } diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java new file mode 100644 index 000000000000..3b4cdfd3ec3e --- /dev/null +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.iluwatar.event.sourcing.event.DomainEvent; +import java.io.File; +import lombok.extern.slf4j.Slf4j; + +/** Base class for Journaling implementations. */ +@Slf4j +public abstract class EventJournal { + + File file; + + /** + * Write. + * + * @param domainEvent the domain event. + */ + abstract void write(DomainEvent domainEvent); + + /** Reset. */ + void reset() { + if (file.delete()) { + LOGGER.info("File cleared successfully............"); + } + } + + /** + * Read domain event. + * + * @return the domain event. + */ + abstract DomainEvent readNext(); +} 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 index 870d8d00ffe3..106dbf95e93a 100644 --- 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,9 +24,8 @@ */ package com.iluwatar.event.sourcing.processor; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.iluwatar.event.sourcing.event.AccountCreateEvent; import com.iluwatar.event.sourcing.event.DomainEvent; import com.iluwatar.event.sourcing.event.MoneyDepositEvent; @@ -37,31 +38,28 @@ import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; -import java.io.Writer; +import java.nio.charset.StandardCharsets; 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. + * 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. + *

    Created by Serdar Hamzaogullari on 06.08.2017. */ -public class JsonFileJournal { +public class JsonFileJournal extends EventJournal { - private final File aFile; private final List events = new ArrayList<>(); private int index = 0; - /** - * Instantiates a new Json file journal. - */ + /** 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"))) { + file = new File("Journal.json"); + if (file.exists()) { + try (var input = + new BufferedReader( + new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { String line; while ((line = input.readLine()) != null) { events.add(line); @@ -74,45 +72,26 @@ public JsonFileJournal() { } } - /** * Write. * * @param domainEvent the domain event */ + @Override 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(); + var mapper = new ObjectMapper(); + try (var output = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8))) { + var eventString = mapper.writeValueAsString(domainEvent); output.write(eventString + "\r\n"); } catch (IOException e) { throw new RuntimeException(e); } } - - /** - * Reset. - */ - public void reset() { - aFile.delete(); - } - - /** - * Read next domain event. + * Read the next domain event. * * @return the domain event */ @@ -120,22 +99,23 @@ public DomainEvent readNext() { if (index >= events.size()) { return null; } - String event = events.get(index); + var 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(); + var mapper = new ObjectMapper(); 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"); + try { + var jsonElement = mapper.readTree(event); + var eventClassName = jsonElement.get("eventClassName").asText(); + domainEvent = + switch (eventClassName) { + case "AccountCreateEvent" -> mapper.treeToValue(jsonElement, AccountCreateEvent.class); + case "MoneyDepositEvent" -> mapper.treeToValue(jsonElement, MoneyDepositEvent.class); + case "MoneyTransferEvent" -> mapper.treeToValue(jsonElement, MoneyTransferEvent.class); + default -> throw new RuntimeException("Journal Event not recognized"); + }; + } catch (JsonProcessingException jsonProcessingException) { + throw new RuntimeException("Failed to convert JSON"); } domainEvent.setRealTime(false); diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java index 2d957268ec9e..80253036f223 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,19 +27,18 @@ import com.iluwatar.event.sourcing.domain.Account; import java.util.HashMap; import java.util.Map; +import java.util.Optional; /** - * This is the static accounts map holder class. - * This class holds the state of the accounts. + * This is the static accounts map holder class. This class holds the state of the accounts. * - * Created by Serdar Hamzaogullari on 06.08.2017. + *

    Created by Serdar Hamzaogullari on 06.08.2017. */ public class AccountAggregate { private static Map accounts = new HashMap<>(); - private AccountAggregate() { - } + private AccountAggregate() {} /** * Put account. @@ -55,16 +56,10 @@ public static void putAccount(Account account) { * @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(); + return Optional.of(accountNo).map(accounts::get).map(Account::copy).orElse(null); } - /** - * Reset state. - */ + /** 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 index aab1ea7ea157..89c7a77fe91e 100644 --- a/event-sourcing/src/test/java/IntegrationTest.java +++ b/event-sourcing/src/test/java/IntegrationTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -21,79 +23,72 @@ * THE SOFTWARE. */ -import com.iluwatar.event.sourcing.domain.Account; +import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS; +import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON; +import static org.junit.jupiter.api.Assertions.assertEquals; + 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.processor.JsonFileJournal; import com.iluwatar.event.sourcing.state.AccountAggregate; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.math.BigDecimal; import java.util.Date; - -import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS; -import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** - * Intergartion Test for Event Sourcing state recovery + * Integration Test for Event-Sourcing state recovery * - * Created by Serdar Hamzaogullari on 19.08.2017. + *

    Created by Serdar Hamzaogullari on 19.08.2017. */ -public class IntegrationTest { +class IntegrationTest { - /** - * The Domain event processor. - */ + /** The Domain event processor. */ private DomainEventProcessor eventProcessor; - /** - * Initialize. - */ + /** Initialize. */ @BeforeEach - public void initialize() { - eventProcessor = new DomainEventProcessor(); + void initialize() { + eventProcessor = new DomainEventProcessor(new JsonFileJournal()); } - /** - * Test state recovery. - */ + /** Test state recovery. */ @Test - public void testStateRecovery() { + void testStateRecovery() { eventProcessor.reset(); - eventProcessor.process(new AccountCreateEvent( - 0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); + 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 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( + 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 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)); + 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); + var accountOfDaenerysBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); + var accountOfJonBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); AccountAggregate.resetState(); - eventProcessor = new DomainEventProcessor(); + eventProcessor = new DomainEventProcessor(new JsonFileJournal()); eventProcessor.recover(); - Account accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); - Account accountOfJonAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); + var accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); + var accountOfJonAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); - assertEquals(accountOfDaenerysBeforeShotDown.getMoney(), - accountOfDaenerysAfterShotDown.getMoney()); + assertEquals( + accountOfDaenerysBeforeShotDown.getMoney(), accountOfDaenerysAfterShotDown.getMoney()); assertEquals(accountOfJonBeforeShotDown.getMoney(), accountOfJonAfterShotDown.getMoney()); } - -} \ No newline at end of file +} diff --git a/exclude-pmd.properties b/exclude-pmd.properties deleted file mode 100644 index 288ee9b2d318..000000000000 --- a/exclude-pmd.properties +++ /dev/null @@ -1,26 +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. -# - -com.iluwatar.servicelayer.common.BaseEntity=UnusedPrivateField -com.iluwatar.doublechecked.locking.App=EmptyStatementNotInLoop,EmptyWhileStmt -com.iluwatar.doublechecked.locking.InventoryTest=EmptyStatementNotInLoop,EmptyWhileStmt diff --git a/execute-around/README.md b/execute-around/README.md index f669f18ff0f3..9587674ded1e 100644 --- a/execute-around/README.md +++ b/execute-around/README.md @@ -1,27 +1,140 @@ --- -layout: pattern -title: Execute Around -folder: execute-around -permalink: /patterns/execute-around/ -categories: Other -tags: - - Java - - Difficulty-Beginner - - Idiom +title: "Execute Around Pattern in Java: Encapsulating Pre and Post Execution Steps" +shortTitle: Execute Around +description: "Explore the Execute Around Pattern in Java with detailed explanations, real-world examples, and best practices. Learn how to implement this design pattern to streamline resource management." +category: Behavioral +language: en +tag: + - Closure + - Code simplification + - Encapsulation + - Functional decomposition + - Resource management +head: + - - meta + - name: keywords + content: --- -## Intent -Execute Around idiom frees the user from certain actions that -should always be executed before and after the business method. A good example -of this is resource allocation and deallocation leaving the user to specify -only what to do with the resource. +## Also known as -![alt text](./etc/execute-around.png "Execute Around") +* Around Method Pattern +* Resource Block Management -## Applicability -Use the Execute Around idiom when +## Intent of Execute Around Design Pattern -* you use an API that requires methods to be called in pairs such as open/close or allocate/deallocate. +Real-world business applications often require executing necessary operations before and after the business method invocation. The Execute Around Pattern in Java provides a way to encapsulate these operations, enhancing code readability and reusability. -## Credits -* [Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions](http://www.amazon.com/Functional-Programming-Java-Harnessing-Expressions/dp/1937785467/ref=sr_1_1) +## Detailed Explanation of Execute Around Pattern with Real-World Examples + +Real-world example + +> A real-world analogy for the Execute Around pattern can be found in the use of rental cars. When you rent a car, the rental company handles all the setup (cleaning the car, filling it with gas, ensuring it's in good condition) and cleanup (checking the car back in, inspecting it for damage, refueling it if necessary) processes for you. As a customer, you simply use the car for your intended purpose without worrying about the setup and cleanup. This pattern of abstracting away the repetitive tasks around the main operation is similar to the Execute Around pattern in software, where the setup and cleanup of resources are handled by a reusable method, allowing the main logic to be executed seamlessly. + +In plain words + +> Execute Around idiom handles boilerplate code before and after business method. + +[Stack Overflow](https://stackoverflow.com/questions/341971/what-is-the-execute-around-idiom) says + +> Basically it's the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in "what we want to do with the resource". + +Flowchart + +![Execute Around flowchart](./etc/execute-around-flowchart.png) + +## Programmatic Example of Execute Around Pattern in Java + +The Execute Around Pattern is a design pattern that is widely used in Java programming to manage resource allocation and deallocation. It ensures that important setup and cleanup operations are performed reliably around a core business operation. This pattern is particularly useful for resource management, such as handling files, databases, or network connections in Java applications. + +A class needs to be provided for writing text strings to files. To make it easy for the user, the service class opens and closes the file automatically. The user only has to specify what is written into which file. + +`SimpleFileWriter` class implements the Execute Around idiom. It takes `FileWriterAction` as a constructor argument allowing the user to specify what gets written into the file. + +```java + +@FunctionalInterface +public interface FileWriterAction { + void writeFile(FileWriter writer) throws IOException; +} + +@Slf4j +public class SimpleFileWriter { + public SimpleFileWriter(String filename, FileWriterAction action) throws IOException { + LOGGER.info("Opening the file"); + try (var writer = new FileWriter(filename)) { + LOGGER.info("Executing the action"); + action.writeFile(writer); + LOGGER.info("Closing the file"); + } + } +} +``` + +The following code demonstrates how `SimpleFileWriter` is used. `Scanner` is used to print the file contents after the writing finishes. + +```java + public static void main(String[] args) throws IOException { + + // create the file writer and execute the custom action + FileWriterAction writeHello = writer -> writer.write("Gandalf was here"); + new SimpleFileWriter("testfile.txt", writeHello); + + // print the file contents + try (var scanner = new Scanner(new File("testfile.txt"))) { + while (scanner.hasNextLine()) { + LOGGER.info(scanner.nextLine()); + } + } +} +``` + +Here's the console output. + +``` +21:18:07.185 [main] INFO com.iluwatar.execute.around.SimpleFileWriter - Opening the file +21:18:07.188 [main] INFO com.iluwatar.execute.around.SimpleFileWriter - Executing the action +21:18:07.189 [main] INFO com.iluwatar.execute.around.SimpleFileWriter - Closing the file +21:18:07.199 [main] INFO com.iluwatar.execute.around.App - Gandalf was here +``` + +## When to Use the Execute Around Pattern in Java + +When to use the Execute Around Pattern in Java: + +* Useful in scenarios requiring repetitive setup and cleanup activities, particularly in resource management (e.g., files, network connections, database sessions). +* Ideal for ensuring proper resource handling and cleanup in the face of exceptions, ensuring resources do not leak. +* Suitable in any Java application where the same preparation and finalization steps are executed around varying core functionalities. + +## Real-World Applications of Execute Around Pattern in Java + +In real-world Java applications, the Execute Around Pattern is applied in these scenarios: + +* Java's try-with-resources statement, which ensures that resources are closed after execution regardless of whether an exception was thrown. +* Frameworks like Spring for managing database transactions, where predefined cleanup or rollback operations are performed depending on the execution outcome. + +## Benefits and Trade-offs of Execute Around Pattern + +Implementing the Execute Around Pattern in Java offers several benefits and trade-offs. + +Benefits: + +* Reduces boilerplate code by abstracting routine setup and cleanup tasks. +* Increases code clarity and maintainability by separating business logic from resource management. +* Ensures robustness by automatically handling resource cleanup, even in error situations. + +Trade-offs: + +* Introduces additional abstraction layers, which might increase complexity and obscure control flow for some developers. +* May require more sophisticated understanding of closures and functional interfaces in Java. + +## Related Java Design Patterns + +* [Template Method](https://java-design-patterns.com/patterns/template-method/): Similar in concept but differs in that it uses inheritance and abstract classes, while Execute Around typically uses interfaces and lambdas. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Shares the concept of adding functionality around a core component; can be extended to wrap additional behaviors dynamically. + +## References and Credits + +* [Effective Java](https://amzn.to/4aDdWbs) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3vUGApm) +* [Functional Programming in Java](https://amzn.to/3JUIc5Q) diff --git a/execute-around/etc/execute-around-flowchart.png b/execute-around/etc/execute-around-flowchart.png new file mode 100644 index 000000000000..3a9048585f62 Binary files /dev/null and b/execute-around/etc/execute-around-flowchart.png differ diff --git a/execute-around/etc/execute-around.urm.puml b/execute-around/etc/execute-around.urm.puml new file mode 100644 index 000000000000..fd01a5fe1fe9 --- /dev/null +++ b/execute-around/etc/execute-around.urm.puml @@ -0,0 +1,14 @@ +@startuml +package com.iluwatar.execute.around { + class App { + + App() + + main(args : String[]) {static} + } + interface FileWriterAction { + + writeFile(FileWriter) {abstract} + } + class SimpleFileWriter { + + SimpleFileWriter(filename : String, action : FileWriterAction) + } +} +@enduml \ No newline at end of file diff --git a/execute-around/pom.xml b/execute-around/pom.xml index 358f4eae4f99..83a9372b4fe3 100644 --- a/execute-around/pom.xml +++ b/execute-around/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT execute-around - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.execute.around.App + + + + + + + + diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/App.java b/execute-around/src/main/java/com/iluwatar/execute/around/App.java index 11775462af18..9dc88fbfdad9 100644 --- a/execute-around/src/main/java/com/iluwatar/execute/around/App.java +++ b/execute-around/src/main/java/com/iluwatar/execute/around/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,34 +24,35 @@ */ package com.iluwatar.execute.around; -import java.io.FileWriter; +import java.io.File; import java.io.IOException; +import java.util.Scanner; +import lombok.extern.slf4j.Slf4j; /** - * The Execute Around idiom specifies some code to be executed before and after a method. Typically - * the idiom is used when the API has methods to be executed in pairs, such as resource + * The Execute Around idiom specifies executable code before and after a method. Typically, the + * idiom is used when the API has methods to be executed in pairs, such as resource * allocation/deallocation or lock acquisition/release. - *

    - * In this example, we have {@link SimpleFileWriter} class that opens and closes the file for the + * + *

    In this example, we have {@link SimpleFileWriter} class that opens and closes the file for the * user. The user specifies only what to do with the file by providing the {@link FileWriterAction} * implementation. - * */ +@Slf4j public class App { - /** - * Program entry point - */ + /** Program entry point. */ public static void main(String[] args) throws IOException { - new SimpleFileWriter("testfile.txt", new FileWriterAction() { + // create the file writer and execute the custom action + FileWriterAction writeHello = writer -> writer.write("Gandalf was here"); + new SimpleFileWriter("testfile.txt", writeHello); - @Override - public void writeFile(FileWriter writer) throws IOException { - writer.write("Hello"); - writer.append(" "); - writer.append("there!"); + // print the file contents + try (var scanner = new Scanner(new File("testfile.txt"))) { + while (scanner.hasNextLine()) { + LOGGER.info(scanner.nextLine()); } - }); + } } } diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java b/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java index 83670c361d38..0627177a31f1 100644 --- a/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java +++ b/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,13 +27,9 @@ import java.io.FileWriter; import java.io.IOException; -/** - * - * Interface for specifying what to do with the file resource. - * - */ +/** Interface for specifying what to do with the file resource. */ +@FunctionalInterface public interface FileWriterAction { void writeFile(FileWriter writer) throws IOException; - } diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java index 3c98597cb7da..d3bd54d4ec6b 100644 --- a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java +++ b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,24 +26,22 @@ import java.io.FileWriter; import java.io.IOException; +import lombok.extern.slf4j.Slf4j; /** - * * SimpleFileWriter handles opening and closing file for the user. The user only has to specify what * to do with the file resource through {@link FileWriterAction} parameter. - * */ +@Slf4j public class SimpleFileWriter { - /** - * Constructor - */ + /** Constructor. */ public SimpleFileWriter(String filename, FileWriterAction action) throws IOException { - FileWriter writer = new FileWriter(filename); - try { + LOGGER.info("Opening the file"); + try (var writer = new FileWriter(filename)) { + LOGGER.info("Executing the action"); action.writeFile(writer); - } finally { - writer.close(); + LOGGER.info("Closing the file"); } } } diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java index 298f7e0d790b..1e06beb12d3b 100644 --- a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java +++ b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,30 +24,25 @@ */ package com.iluwatar.execute.around; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import java.io.File; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.File; -import java.io.IOException; - -/** - * - * Tests execute-around example. - * - */ -public class AppTest { +/** Tests execute-around example. */ +class AppTest { @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } @BeforeEach @AfterEach - public void cleanup() { - File file = new File("testfile.txt"); + void cleanup() { + var file = new File("testfile.txt"); file.delete(); } } diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java index 22bdf68f7ea6..60c4ecb6bdba 100644 --- a/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java +++ b/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,80 +24,65 @@ */ package com.iluwatar.execute.around; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import lombok.SneakyThrows; import org.junit.Rule; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; import org.junit.rules.TemporaryFolder; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Date: 12/12/15 - 3:21 PM - * - * @author Jeroen Meulemeester - */ +/** SimpleFileWriterTest */ @EnableRuleMigrationSupport -public class SimpleFileWriterTest { +class SimpleFileWriterTest { - /** - * Create a temporary folder, used to generate files in during this test - */ - @Rule - public final TemporaryFolder testFolder = new TemporaryFolder(); + @Rule public final TemporaryFolder testFolder = new TemporaryFolder(); - /** - * Verify if the given writer is not 'null' - */ @Test - public void testWriterNotNull() throws Exception { - final File temporaryFile = this.testFolder.newFile(); + void testWriterNotNull() throws Exception { + final var temporaryFile = this.testFolder.newFile(); new SimpleFileWriter(temporaryFile.getPath(), Assertions::assertNotNull); } - /** - * Test if the {@link SimpleFileWriter} creates a file if it doesn't exist - */ @Test - public void testNonExistentFile() throws Exception { - final File nonExistingFile = new File(this.testFolder.getRoot(), "non-existing-file"); + void testCreatesNonExistentFile() throws Exception { + final var nonExistingFile = new File(this.testFolder.getRoot(), "non-existing-file"); assertFalse(nonExistingFile.exists()); new SimpleFileWriter(nonExistingFile.getPath(), Assertions::assertNotNull); assertTrue(nonExistingFile.exists()); } - /** - * Test if the data written to the file writer actually gets in the file - */ @Test - public void testActualWrite() throws Exception { - final String testMessage = "Test message"; + void testContentsAreWrittenToFile() throws Exception { + final var testMessage = "Test message"; - final File temporaryFile = this.testFolder.newFile(); + final var temporaryFile = this.testFolder.newFile(); assertTrue(temporaryFile.exists()); new SimpleFileWriter(temporaryFile.getPath(), writer -> writer.write(testMessage)); assertTrue(Files.lines(temporaryFile.toPath()).allMatch(testMessage::equals)); } - /** - * Verify if an {@link IOException} during the write ripples through - */ @Test - public void testIoException() throws Exception { - assertThrows(IOException.class, () -> { - final File temporaryFile = this.testFolder.newFile(); - new SimpleFileWriter(temporaryFile.getPath(), writer -> { - throw new IOException(""); - }); - }); + @SneakyThrows + void testRipplesIoExceptionOccurredWhileWriting() { + var message = "Some error"; + final var temporaryFile = this.testFolder.newFile(); + assertThrows( + IOException.class, + () -> + new SimpleFileWriter( + temporaryFile.getPath(), + writer -> { + throw new IOException("error"); + }), + message); } - } diff --git a/extension-objects/README.md b/extension-objects/README.md index 9b5c93a2200d..82704008dca6 100644 --- a/extension-objects/README.md +++ b/extension-objects/README.md @@ -1,28 +1,185 @@ --- -layout: pattern -title: Extension objects -folder: extension-objects -permalink: /patterns/extension-objects/ -categories: Behavioral -tags: - - Java - - Difficulty-Intermediate +title: "Extension Objects Pattern in Java: Enhancing Object Functionality Flexibly" +shortTitle: Extension Objects +description: "Learn about the Extension Objects Design Pattern in Java. Understand its purpose, benefits, and implementation with examples to enhance your software design." +category: Structural +language: en +tag: + - Encapsulation + - Extensibility + - Object composition + - Polymorphism --- -## Intent -Anticipate that an object’s interface needs to be extended in the future. Additional -interfaces are defined by extension objects. +## Also known as -![Extension_objects](./etc/extension_obj.png "Extension objects") +* Interface Extensions -## Applicability -Use the Extension Objects pattern when: +## Intent of Extension Objects Design Pattern -* you need to support the addition of new or unforeseen interfaces to existing classes and you don't want to impact clients that don't need this new interface. Extension Objects lets you keep related operations together by defining them in a separate class -* a class representing a key abstraction plays different roles for different clients. The number of roles the class can play should be open-ended. There is a need to preserve the key abstraction itself. For example, a customer object is still a customer object even if different subsystems view it differently. -* a class should be extensible with new behavior without subclassing from it. +The Extension Objects pattern allows for the flexible extension of an object's behavior without modifying its structure, by attaching additional objects that can dynamically add new functionality. -## Real world examples +## Detailed Explanation of Extension Objects Pattern with Real-World Examples +Real-world example + +> An analogous real-world example of the Extension Objects design pattern can be found in modular kitchen appliances. Consider a base blender unit to which different attachments can be added, such as a food processor, juicer, or grinder. Each attachment adds new functionality to the blender without altering the base unit itself. Users can dynamically switch between different functionalities based on their current needs, making the blender highly versatile and adaptable to various tasks. This mirrors the Extension Objects pattern in software, where new functionalities are added to an object dynamically and contextually, enhancing flexibility and reuse. + +In plain words + +> The Extension Objects pattern is used to dynamically add functionality to objects without modifying their core classes. It is a behavioural design pattern used for adding new functionality to existing classes and objects within a program. This pattern provides programmers with the ability to extend/modify class functionality without having to refactor existing source code. + +Wikipedia says + +> In object-oriented computer programming, an extension objects pattern is a design pattern added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension object patterns are features of some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition. + +Sequence diagram + +![Extension Objects sequence diagram](./etc/extension-objects-sequence-diagram.png) + +## Programmatic Example of Extension Objects Pattern in Java + +The Extension Objects pattern allows for the flexible extension of an object's behavior without modifying its structure, by attaching additional objects that can dynamically add new functionality. + +In this Java implementation, we have three types of units: `SoldierUnit`, `SergeantUnit`, and `CommanderUnit`. Each unit can have extensions that provide additional functionality. The extensions are `SoldierExtension`, `SergeantExtension`, and `CommanderExtension`. + +The `Unit` class is the base class for all units. It has a method `getUnitExtension` that returns an extension object based on the extension name. + +```java +public abstract class Unit { + private String name; + + protected Unit(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public abstract UnitExtension getUnitExtension(String extensionName); +} +``` + +The `UnitExtension` interface is the base interface for all extensions. Each specific extension will implement this interface. + +```java +public interface UnitExtension { + String getName(); +} +``` + +The `SoldierUnit` class is a specific type of unit. It overrides the `getUnitExtension` method to return a `SoldierExtension` object. + +```java +public class SoldierUnit extends Unit { + public SoldierUnit(String name) { + super(name); + } + + @Override + public UnitExtension getUnitExtension(String extensionName) { + if ("SoldierExtension".equals(extensionName)) { + return new SoldierExtension(this); + } + return null; + } +} +``` + +The `SoldierExtension` class is a specific type of extension. It implements the `UnitExtension` interface and provides additional functionality for the `SoldierUnit`. + +```java +public class SoldierExtension implements UnitExtension { + private SoldierUnit unit; + + public SoldierExtension(SoldierUnit unit) { + this.unit = unit; + } + + @Override + public String getName() { + return "SoldierExtension"; + } + + public void soldierReady() { + // additional functionality for SoldierUnit + } +} +``` + +In the `main` application, we create different types of units and check for each unit to have an extension. If the extension exists, we call the specific method on the extension object. + +```java +public class App { + public static void main(String[] args) { + var soldierUnit = new SoldierUnit("SoldierUnit1"); + var sergeantUnit = new SergeantUnit("SergeantUnit1"); + var commanderUnit = new CommanderUnit("CommanderUnit1"); + + checkExtensionsForUnit(soldierUnit); + checkExtensionsForUnit(sergeantUnit); + checkExtensionsForUnit(commanderUnit); + } + + private static void checkExtensionsForUnit(Unit unit) { + var extension = "SoldierExtension"; + Optional.ofNullable(unit.getUnitExtension(extension)) + .map(e -> (SoldierExtension) e) + .ifPresentOrElse(SoldierExtension::soldierReady, () -> System.out.println(unit.getName() + " without " + extension)); + } +} +``` + +This produces the following console output. + +``` +22:58:03.779 [main] INFO concreteextensions.Soldier -- [Soldier] SoldierUnit1 is ready! +22:58:03.781 [main] INFO App -- SoldierUnit1 without SergeantExtension +22:58:03.782 [main] INFO App -- SoldierUnit1 without CommanderExtension +22:58:03.782 [main] INFO App -- SergeantUnit1 without SoldierExtension +22:58:03.783 [main] INFO concreteextensions.Sergeant -- [Sergeant] SergeantUnit1 is ready! +22:58:03.783 [main] INFO App -- SergeantUnit1 without CommanderExtension +22:58:03.783 [main] INFO App -- CommanderUnit1 without SoldierExtension +22:58:03.783 [main] INFO App -- CommanderUnit1 without SergeantExtension +22:58:03.783 [main] INFO concreteextensions.Commander -- [Commander] CommanderUnit1 is ready! +``` + +This example demonstrates how the Extension Objects pattern allows for the flexible extension of an object's behavior without modifying its structure. + +## When to Use the Extension Objects Pattern in Java + +This pattern is applicable in scenarios where an object's functionality needs to be extended at runtime, avoiding the complications of subclassing. It's particularly useful in systems where object capabilities need to be augmented post-deployment, or where the capabilities might vary significantly across instances. + +## Real-World Applications of Extension Objects Pattern in Java + +* Extending services in an application server without altering existing code. +* Plugins in IDEs like IntelliJ IDEA or Eclipse to add features to the base application. +* Enabling additional features in enterprise software based on license levels. * [OpenDoc](https://en.wikipedia.org/wiki/OpenDoc) * [Object Linking and Embedding](https://en.wikipedia.org/wiki/Object_Linking_and_Embedding) + +## Benefits and Trade-offs of Extension Objects Pattern + +Benefits: + +* Enhances flexibility by allowing dynamic extension of an object's capabilities. +* Promotes loose coupling between the base object and its extensions. +* Supports the [Open/Closed Principle](https://java-design-patterns.com/principles/#open-closed-principle) by keeping the object open for extension but closed for modification. + +Trade-offs: + +* Can increase complexity due to the management of extension objects. +* May introduce performance overhead if the interaction between objects and extensions is not efficiently designed. + +## Related Java Design Patterns + +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar in intent to add responsibilities dynamically, but uses a different structure. +* [Composite](https://java-design-patterns.com/patterns/composite/): Also manages a group of objects, which can be seen as a form of extension. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Offers an alternative way to change the behavior of an object dynamically. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/4aBMuuL) +* [Pattern-Oriented Software Architecture: A System of Patterns](https://amzn.to/3Q9YOtX) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3W6IZYQ) diff --git a/extension-objects/etc/extension-objects-sequence-diagram.png b/extension-objects/etc/extension-objects-sequence-diagram.png new file mode 100644 index 000000000000..46850163ab9b Binary files /dev/null and b/extension-objects/etc/extension-objects-sequence-diagram.png differ diff --git a/extension-objects/etc/extension-objects.urm.puml b/extension-objects/etc/extension-objects.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/extension-objects/etc/extension-objects.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/extension-objects/pom.xml b/extension-objects/pom.xml index 74f233775756..92297162fed4 100644 --- a/extension-objects/pom.xml +++ b/extension-objects/pom.xml @@ -1,8 +1,10 @@ - + java-design-patterns com.iluwatar - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT 4.0.0 - extension-objects - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -46,5 +48,23 @@ test - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + App + + + + + + + + diff --git a/extension-objects/src/main/java/App.java b/extension-objects/src/main/java/App.java index 0fcc548dc04c..db48032f1499 100644 --- a/extension-objects/src/main/java/App.java +++ b/extension-objects/src/main/java/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,62 +25,57 @@ import abstractextensions.CommanderExtension; import abstractextensions.SergeantExtension; import abstractextensions.SoldierExtension; +import java.util.Optional; +import java.util.function.Function; +import org.slf4j.LoggerFactory; import units.CommanderUnit; import units.SergeantUnit; import units.SoldierUnit; import units.Unit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** - * Anticipate that an object’s interface needs to be extended in the future. - * Additional interfaces are defined by extension objects. + * Anticipate that an object’s interface needs to be extended in the future. Additional interfaces + * are defined by extension objects. */ public class App { /** - * Program entry point + * Program entry point. * * @param args command line args */ public static void main(String[] args) { - //Create 3 different units - Unit soldierUnit = new SoldierUnit("SoldierUnit1"); - Unit sergeantUnit = new SergeantUnit("SergeantUnit1"); - Unit commanderUnit = new CommanderUnit("CommanderUnit1"); + // Create 3 different units + var soldierUnit = new SoldierUnit("SoldierUnit1"); + var sergeantUnit = new SergeantUnit("SergeantUnit1"); + var commanderUnit = new CommanderUnit("CommanderUnit1"); - //check for each unit to have an extension + // check for each unit to have an extension checkExtensionsForUnit(soldierUnit); checkExtensionsForUnit(sergeantUnit); checkExtensionsForUnit(commanderUnit); - } private static void checkExtensionsForUnit(Unit unit) { - final Logger logger = LoggerFactory.getLogger(App.class); + final var logger = LoggerFactory.getLogger(App.class); - SoldierExtension soldierExtension = (SoldierExtension) unit.getUnitExtension("SoldierExtension"); - SergeantExtension sergeantExtension = (SergeantExtension) unit.getUnitExtension("SergeantExtension"); - CommanderExtension commanderExtension = (CommanderExtension) unit.getUnitExtension("CommanderExtension"); + var name = unit.getName(); + Function func = e -> () -> logger.info("{} without {}", name, e); - //if unit have extension call the method - if (soldierExtension != null) { - soldierExtension.soldierReady(); - } else { - logger.info(unit.getName() + " without SoldierExtension"); - } + var extension = "SoldierExtension"; + Optional.ofNullable(unit.getUnitExtension(extension)) + .map(e -> (SoldierExtension) e) + .ifPresentOrElse(SoldierExtension::soldierReady, func.apply(extension)); - if (sergeantExtension != null) { - sergeantExtension.sergeantReady(); - } else { - logger.info(unit.getName() + " without SergeantExtension"); - } + extension = "SergeantExtension"; + Optional.ofNullable(unit.getUnitExtension(extension)) + .map(e -> (SergeantExtension) e) + .ifPresentOrElse(SergeantExtension::sergeantReady, func.apply(extension)); - if (commanderExtension != null) { - commanderExtension.commanderReady(); - } else { - logger.info(unit.getName() + " without CommanderExtension"); - } + extension = "CommanderExtension"; + Optional.ofNullable(unit.getUnitExtension(extension)) + .map(e -> (CommanderExtension) e) + .ifPresentOrElse(CommanderExtension::commanderReady, func.apply(extension)); } } diff --git a/extension-objects/src/main/java/abstractextensions/CommanderExtension.java b/extension-objects/src/main/java/abstractextensions/CommanderExtension.java index 66dd3a25e5b5..bcad9db942c8 100644 --- a/extension-objects/src/main/java/abstractextensions/CommanderExtension.java +++ b/extension-objects/src/main/java/abstractextensions/CommanderExtension.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,9 +24,7 @@ */ package abstractextensions; -/** - * Interface with their method - */ +/** Interface with their method. */ public interface CommanderExtension extends UnitExtension { void commanderReady(); diff --git a/extension-objects/src/main/java/abstractextensions/SergeantExtension.java b/extension-objects/src/main/java/abstractextensions/SergeantExtension.java index 8df30c63e776..7eea21d0cb3f 100644 --- a/extension-objects/src/main/java/abstractextensions/SergeantExtension.java +++ b/extension-objects/src/main/java/abstractextensions/SergeantExtension.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,9 +24,7 @@ */ package abstractextensions; -/** - * Interface with their method - */ +/** Interface with their method. */ public interface SergeantExtension extends UnitExtension { void sergeantReady(); diff --git a/extension-objects/src/main/java/abstractextensions/SoldierExtension.java b/extension-objects/src/main/java/abstractextensions/SoldierExtension.java index 9296b620474e..579e3c1d0497 100644 --- a/extension-objects/src/main/java/abstractextensions/SoldierExtension.java +++ b/extension-objects/src/main/java/abstractextensions/SoldierExtension.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,9 +24,7 @@ */ package abstractextensions; -/** - * Interface with their method - */ +/** Interface with their method. */ public interface SoldierExtension extends UnitExtension { void soldierReady(); } diff --git a/extension-objects/src/main/java/abstractextensions/UnitExtension.java b/extension-objects/src/main/java/abstractextensions/UnitExtension.java index b3b3bf7fad1d..d79868d547ba 100644 --- a/extension-objects/src/main/java/abstractextensions/UnitExtension.java +++ b/extension-objects/src/main/java/abstractextensions/UnitExtension.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,8 +24,5 @@ */ package abstractextensions; -/** - * Other Extensions will extend this interface - */ -public interface UnitExtension { -} +/** Other Extensions will extend this interface. */ +public interface UnitExtension {} diff --git a/extension-objects/src/main/java/concreteextensions/Commander.java b/extension-objects/src/main/java/concreteextensions/Commander.java index 8094d2887ab9..0716d2e9bb25 100644 --- a/extension-objects/src/main/java/concreteextensions/Commander.java +++ b/extension-objects/src/main/java/concreteextensions/Commander.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,25 +25,15 @@ package concreteextensions; import abstractextensions.CommanderExtension; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; import units.CommanderUnit; -/** - * Class defining Commander - */ -public class Commander implements CommanderExtension { - - private CommanderUnit unit; - - public Commander(CommanderUnit commanderUnit) { - this.unit = commanderUnit; - } - - final Logger logger = LoggerFactory.getLogger(Commander.class); +/** Class defining Commander. */ +@Slf4j +public record Commander(CommanderUnit unit) implements CommanderExtension { @Override public void commanderReady() { - logger.info("[Commander] " + unit.getName() + " is ready!"); + LOGGER.info("[Commander] " + unit.getName() + " is ready!"); } } diff --git a/extension-objects/src/main/java/concreteextensions/Sergeant.java b/extension-objects/src/main/java/concreteextensions/Sergeant.java index 892a3d3728c5..fb8f815c8c38 100644 --- a/extension-objects/src/main/java/concreteextensions/Sergeant.java +++ b/extension-objects/src/main/java/concreteextensions/Sergeant.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,25 +25,15 @@ package concreteextensions; import abstractextensions.SergeantExtension; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; import units.SergeantUnit; -/** - * Class defining Sergeant - */ -public class Sergeant implements SergeantExtension { - - private SergeantUnit unit; - - public Sergeant(SergeantUnit sergeantUnit) { - this.unit = sergeantUnit; - } - - final Logger logger = LoggerFactory.getLogger(Sergeant.class); +/** Class defining Sergeant. */ +@Slf4j +public record Sergeant(SergeantUnit unit) implements SergeantExtension { @Override public void sergeantReady() { - logger.info("[Sergeant] " + unit.getName() + " is ready! "); + LOGGER.info("[Sergeant] " + unit.getName() + " is ready!"); } } diff --git a/extension-objects/src/main/java/concreteextensions/Soldier.java b/extension-objects/src/main/java/concreteextensions/Soldier.java index 79db74d6cf29..dd2338a5389f 100644 --- a/extension-objects/src/main/java/concreteextensions/Soldier.java +++ b/extension-objects/src/main/java/concreteextensions/Soldier.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,25 +25,15 @@ package concreteextensions; import abstractextensions.SoldierExtension; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; import units.SoldierUnit; -/** - * Class defining Soldier - */ -public class Soldier implements SoldierExtension { - - private SoldierUnit unit; - - public Soldier(SoldierUnit soldierUnit) { - this.unit = soldierUnit; - } - - final Logger logger = LoggerFactory.getLogger(Soldier.class); +/** Class defining Soldier. */ +@Slf4j +public record Soldier(SoldierUnit unit) implements SoldierExtension { @Override public void soldierReady() { - logger.info("[Solider] " + unit.getName() + " is ready!"); + LOGGER.info("[Soldier] " + unit.getName() + " is ready!"); } } diff --git a/extension-objects/src/main/java/units/CommanderUnit.java b/extension-objects/src/main/java/units/CommanderUnit.java index 61b7a050d67f..94e92807f30d 100644 --- a/extension-objects/src/main/java/units/CommanderUnit.java +++ b/extension-objects/src/main/java/units/CommanderUnit.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,10 +26,9 @@ import abstractextensions.UnitExtension; import concreteextensions.Commander; +import java.util.Optional; -/** - * Class defining CommanderUnit - */ +/** Class defining CommanderUnit. */ public class CommanderUnit extends Unit { public CommanderUnit(String name) { @@ -38,10 +39,7 @@ public CommanderUnit(String name) { public UnitExtension getUnitExtension(String extensionName) { if (extensionName.equals("CommanderExtension")) { - if (unitExtension == null) { - unitExtension = new Commander(this); - } - return unitExtension; + return Optional.ofNullable(unitExtension).orElseGet(() -> new Commander(this)); } return super.getUnitExtension(extensionName); diff --git a/extension-objects/src/main/java/units/SergeantUnit.java b/extension-objects/src/main/java/units/SergeantUnit.java index a655abac4c52..ae882d92943a 100644 --- a/extension-objects/src/main/java/units/SergeantUnit.java +++ b/extension-objects/src/main/java/units/SergeantUnit.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,10 +26,9 @@ import abstractextensions.UnitExtension; import concreteextensions.Sergeant; +import java.util.Optional; -/** - * Class defining SergeantUnit - */ +/** Class defining SergeantUnit. */ public class SergeantUnit extends Unit { public SergeantUnit(String name) { @@ -38,10 +39,7 @@ public SergeantUnit(String name) { public UnitExtension getUnitExtension(String extensionName) { if (extensionName.equals("SergeantExtension")) { - if (unitExtension == null) { - unitExtension = new Sergeant(this); - } - return unitExtension; + return Optional.ofNullable(unitExtension).orElseGet(() -> new Sergeant(this)); } return super.getUnitExtension(extensionName); diff --git a/extension-objects/src/main/java/units/SoldierUnit.java b/extension-objects/src/main/java/units/SoldierUnit.java index 03617dd27586..b1db8930e625 100644 --- a/extension-objects/src/main/java/units/SoldierUnit.java +++ b/extension-objects/src/main/java/units/SoldierUnit.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,10 +26,9 @@ import abstractextensions.UnitExtension; import concreteextensions.Soldier; +import java.util.Optional; -/** - * Class defining SoldierUnit - */ +/** Class defining SoldierUnit. */ public class SoldierUnit extends Unit { public SoldierUnit(String name) { @@ -38,12 +39,9 @@ public SoldierUnit(String name) { public UnitExtension getUnitExtension(String extensionName) { if (extensionName.equals("SoldierExtension")) { - if (unitExtension == null) { - unitExtension = new Soldier(this); - } - - return unitExtension; + return Optional.ofNullable(unitExtension).orElseGet(() -> new Soldier(this)); } + return super.getUnitExtension(extensionName); } } diff --git a/extension-objects/src/main/java/units/Unit.java b/extension-objects/src/main/java/units/Unit.java index 1bf251a8e7b5..1957771821b7 100644 --- a/extension-objects/src/main/java/units/Unit.java +++ b/extension-objects/src/main/java/units/Unit.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,10 +25,12 @@ package units; import abstractextensions.UnitExtension; +import lombok.Getter; +import lombok.Setter; -/** - * Class defining Unit, other units will extend this class - */ +/** Class defining Unit, other units will extend this class. */ +@Setter +@Getter public class Unit { private String name; @@ -36,14 +40,6 @@ public Unit(String name) { this.name = name; } - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - public UnitExtension getUnitExtension(String extensionName) { return null; } diff --git a/extension-objects/src/test/java/AppTest.java b/extension-objects/src/test/java/AppTest.java index f3111bebbfe7..c80e472b4052 100644 --- a/extension-objects/src/test/java/AppTest.java +++ b/extension-objects/src/test/java/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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,18 +22,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Created by Srdjan on 03-May-17. - */ -public class AppTest { - @Test - public void main() throws Exception { +/** Created by Srdjan on 03-May-17. */ +class AppTest { - String[] args = {}; - App.main(args); + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } - -} \ No newline at end of file +} diff --git a/extension-objects/src/test/java/concreteextensions/CommanderTest.java b/extension-objects/src/test/java/concreteextensions/CommanderTest.java index 5dac551f437e..5271d7ea7563 100644 --- a/extension-objects/src/test/java/concreteextensions/CommanderTest.java +++ b/extension-objects/src/test/java/concreteextensions/CommanderTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,36 @@ */ package concreteextensions; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import java.util.List; import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; import units.CommanderUnit; -/** - * Created by Srdjan on 03-May-17. - */ -public class CommanderTest { +/** CommanderTest */ +class CommanderTest { + @Test - public void commanderReady() throws Exception { - final Commander commander = new Commander(new CommanderUnit("CommanderUnitTest")); + void shouldExecuteCommanderReady() { + + Logger commanderLogger = (Logger) LoggerFactory.getLogger(Commander.class); + ListAppender listAppender = new ListAppender<>(); + listAppender.start(); + + commanderLogger.addAppender(listAppender); + + final var commander = new Commander(new CommanderUnit("CommanderUnitTest")); commander.commanderReady(); - } -} \ No newline at end of file + List logsList = listAppender.list; + assertEquals( + "[Commander] " + commander.unit().getName() + " is ready!", logsList.get(0).getMessage()); + assertEquals(Level.INFO, logsList.get(0).getLevel()); + } +} diff --git a/extension-objects/src/test/java/concreteextensions/SergeantTest.java b/extension-objects/src/test/java/concreteextensions/SergeantTest.java index f26830e2c21a..83b2cb46db5d 100644 --- a/extension-objects/src/test/java/concreteextensions/SergeantTest.java +++ b/extension-objects/src/test/java/concreteextensions/SergeantTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,36 @@ */ package concreteextensions; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import java.util.List; import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; import units.SergeantUnit; -/** - * Created by Srdjan on 03-May-17. - */ -public class SergeantTest { +/** Created by Srdjan on 03-May-17. */ +class SergeantTest { + @Test - public void sergeantReady() throws Exception { - final Sergeant sergeant = new Sergeant(new SergeantUnit("SergeantUnitTest")); + void sergeantReady() { + + Logger sergeantLogger = (Logger) LoggerFactory.getLogger(Sergeant.class); + ListAppender listAppender = new ListAppender<>(); + listAppender.start(); + + sergeantLogger.addAppender(listAppender); + + final var sergeant = new Sergeant(new SergeantUnit("SergeantUnitTest")); sergeant.sergeantReady(); - } -} \ No newline at end of file + List logsList = listAppender.list; + assertEquals( + "[Sergeant] " + sergeant.unit().getName() + " is ready!", logsList.get(0).getMessage()); + assertEquals(Level.INFO, logsList.get(0).getLevel()); + } +} diff --git a/extension-objects/src/test/java/concreteextensions/SoldierTest.java b/extension-objects/src/test/java/concreteextensions/SoldierTest.java index a9a6c476859d..da3490c2bad9 100644 --- a/extension-objects/src/test/java/concreteextensions/SoldierTest.java +++ b/extension-objects/src/test/java/concreteextensions/SoldierTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,36 @@ */ package concreteextensions; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import java.util.List; import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; import units.SoldierUnit; -/** - * Created by Srdjan on 03-May-17. - */ -public class SoldierTest { +/** Created by Srdjan on 03-May-17. */ +class SoldierTest { + @Test - public void soldierReady() throws Exception { - final Soldier soldier = new Soldier(new SoldierUnit("SoldierUnitTest")); + void soldierReady() { + + Logger soldierLogger = (Logger) LoggerFactory.getLogger(Soldier.class); + ListAppender listAppender = new ListAppender<>(); + listAppender.start(); + + soldierLogger.addAppender(listAppender); + + final var soldier = new Soldier(new SoldierUnit("SoldierUnitTest")); soldier.soldierReady(); - } -} \ No newline at end of file + List logsList = listAppender.list; + assertEquals( + "[Soldier] " + soldier.unit().getName() + " is ready!", logsList.get(0).getMessage()); + assertEquals(Level.INFO, logsList.get(0).getLevel()); + } +} diff --git a/extension-objects/src/test/java/units/CommanderUnitTest.java b/extension-objects/src/test/java/units/CommanderUnitTest.java index 536c3ae3f501..1b4793e66e71 100644 --- a/extension-objects/src/test/java/units/CommanderUnitTest.java +++ b/extension-objects/src/test/java/units/CommanderUnitTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,24 +24,20 @@ */ package units; -import abstractextensions.CommanderExtension; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -/** - * Created by Srdjan on 03-May-17. - */ -public class CommanderUnitTest { - @Test - public void getUnitExtension() throws Exception { +import org.junit.jupiter.api.Test; + +/** Created by Srdjan on 03-May-17. */ +class CommanderUnitTest { - final Unit unit = new CommanderUnit("CommanderUnitName"); + @Test + void getUnitExtension() { + final var unit = new CommanderUnit("CommanderUnitName"); assertNull(unit.getUnitExtension("SoldierExtension")); assertNull(unit.getUnitExtension("SergeantExtension")); - assertNotNull((CommanderExtension) unit.getUnitExtension("CommanderExtension")); + assertNotNull(unit.getUnitExtension("CommanderExtension")); } - -} \ No newline at end of file +} diff --git a/extension-objects/src/test/java/units/SergeantUnitTest.java b/extension-objects/src/test/java/units/SergeantUnitTest.java index ac518b48828e..b211483b15e9 100644 --- a/extension-objects/src/test/java/units/SergeantUnitTest.java +++ b/extension-objects/src/test/java/units/SergeantUnitTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,24 +24,20 @@ */ package units; -import abstractextensions.SergeantExtension; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -/** - * Created by Srdjan on 03-May-17. - */ -public class SergeantUnitTest { - @Test - public void getUnitExtension() throws Exception { +import org.junit.jupiter.api.Test; + +/** Created by Srdjan on 03-May-17. */ +class SergeantUnitTest { - final Unit unit = new SergeantUnit("SergeantUnitName"); + @Test + void getUnitExtension() { + final var unit = new SergeantUnit("SergeantUnitName"); assertNull(unit.getUnitExtension("SoldierExtension")); - assertNotNull((SergeantExtension) unit.getUnitExtension("SergeantExtension")); + assertNotNull(unit.getUnitExtension("SergeantExtension")); assertNull(unit.getUnitExtension("CommanderExtension")); } - -} \ No newline at end of file +} diff --git a/extension-objects/src/test/java/units/SoldierUnitTest.java b/extension-objects/src/test/java/units/SoldierUnitTest.java index 1aeb9a3cddc2..4a3ff803e15a 100644 --- a/extension-objects/src/test/java/units/SoldierUnitTest.java +++ b/extension-objects/src/test/java/units/SoldierUnitTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,26 +24,20 @@ */ package units; -import abstractextensions.SoldierExtension; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -/** - * Created by Srdjan on 03-May-17. - */ -public class SoldierUnitTest { - @Test - public void getUnitExtension() throws Exception { +import org.junit.jupiter.api.Test; - final Unit unit = new SoldierUnit("SoldierUnitName"); +/** Created by Srdjan on 03-May-17. */ +class SoldierUnitTest { - assertNotNull((SoldierExtension) unit.getUnitExtension("SoldierExtension")); + @Test + void getUnitExtension() { + final var unit = new SoldierUnit("SoldierUnitName"); + + assertNotNull(unit.getUnitExtension("SoldierExtension")); assertNull(unit.getUnitExtension("SergeantExtension")); assertNull(unit.getUnitExtension("CommanderExtension")); - - } - -} \ No newline at end of file +} diff --git a/extension-objects/src/test/java/units/UnitTest.java b/extension-objects/src/test/java/units/UnitTest.java index 389c9f753db7..9cd0d29d71b7 100644 --- a/extension-objects/src/test/java/units/UnitTest.java +++ b/extension-objects/src/test/java/units/UnitTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,31 +24,27 @@ */ package units; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; -/** - * Created by Srdjan on 03-May-17. - */ -public class UnitTest { +import org.junit.jupiter.api.Test; + +/** Created by Srdjan on 03-May-17. */ +class UnitTest { @Test - public void testConstGetSet() throws Exception { - final String name = "testName"; - final Unit unit = new Unit(name); + void testConstGetSet() { + final var name = "testName"; + final var unit = new Unit(name); assertEquals(name, unit.getName()); - final String newName = "newName"; + final var newName = "newName"; unit.setName(newName); assertEquals(newName, unit.getName()); - assertNull(unit.getUnitExtension("")); assertNull(unit.getUnitExtension("SoldierExtension")); assertNull(unit.getUnitExtension("SergeantExtension")); assertNull(unit.getUnitExtension("CommanderExtension")); } - -} \ No newline at end of file +} diff --git a/facade/README.md b/facade/README.md index 505ceee394bb..e9f3daf0cbd8 100644 --- a/facade/README.md +++ b/facade/README.md @@ -1,24 +1,29 @@ --- -layout: pattern -title: Facade -folder: facade -permalink: /patterns/facade/ -categories: Structural -tags: - - Java - - Gang Of Four - - Difficulty-Beginner +title: "Facade Pattern in Java: Simplifying Complex System Interfaces" +shortTitle: Facade +description: "Learn how to implement the Facade Design Pattern in Java to create a unified interface for complex subsystems. Simplify your code and enhance maintainability with practical examples and use cases." +category: Structural +language: en +tag: + - Abstraction + - API design + - Code simplification + - Decoupling + - Encapsulation + - Gang of Four + - Interface + - Object composition --- -## Intent -Provide a unified interface to a set of interfaces in a subsystem. -Facade defines a higher-level interface that makes the subsystem easier to use. +## Intent of Facade Design Pattern -## Explanation +The Facade Design Pattern provides a unified interface to a set of interfaces in a subsystem. This Java design pattern simplifies complex system interactions. -Real world example +## Detailed Explanation of Facade Pattern with Real-World Examples -> How does a goldmine work? "Well, the miners go down there and dig gold!" you say. That is what you believe because you are using a simple interface that goldmine provides on the outside, internally it has to do a lot of stuff to make it happen. This simple interface to the complex subsystem is a facade. +Real-world example + +> Imagine a home theater system with multiple components: a DVD player, projector, surround sound system, and lights. Each component has a complex interface with numerous functions and settings. To simplify the use of the home theater system, a remote control (the Facade) is provided. The remote control offers a unified interface with simple buttons like "Play Movie," "Stop," "Pause," and "Volume Up/Down," which internally communicate with the various components, managing their interactions. This makes the system easier to use without needing to understand the detailed operations of each component. In plain words @@ -28,182 +33,218 @@ Wikipedia says > A facade is an object that provides a simplified interface to a larger body of code, such as a class library. -**Programmatic Example** +Sequence diagram + +![Facade sequence diagram](./etc/facade-sequence-diagram.png) + +## Programmatic Example of Facade Pattern in Java + +Here's an example of the Facade Design Pattern in a goldmine scenario, demonstrating how a Java facade can streamline complex operations. -Taking our goldmine example from above. Here we have the dwarven mine worker hierarchy +How does a goldmine work? "Well, the miners go down there and dig gold!" you say. That is what you believe because you are using a simple interface that goldmine provides on the outside, internally it has to do a lot of stuff to make it happen. This simple interface to the complex subsystem is a facade. + +Here we have the dwarven mine worker hierarchy. First, there's a base class `DwarvenMineWorker`: ```java + +@Slf4j public abstract class DwarvenMineWorker { - private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenMineWorker.class); - - public void goToSleep() { - LOGGER.info("{} goes to sleep.", name()); - } - - public void wakeUp() { - LOGGER.info("{} wakes up.", name()); - } - - public void goHome() { - LOGGER.info("{} goes home.", name()); - } - - public void goToMine() { - LOGGER.info("{} goes to the mine.", name()); - } - - private void action(Action action) { - switch (action) { - case GO_TO_SLEEP: - goToSleep(); - break; - case WAKE_UP: - wakeUp(); - break; - case GO_HOME: - goHome(); - break; - case GO_TO_MINE: - goToMine(); - break; - case WORK: - work(); - break; - default: - LOGGER.info("Undefined action"); - break; - } - } - - public void action(Action... actions) { - for (Action action : actions) { - action(action); - } - } - - public abstract void work(); - - public abstract String name(); - - static enum Action { - GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK - } + public void goToSleep() { + LOGGER.info("{} goes to sleep.", name()); + } + + public void wakeUp() { + LOGGER.info("{} wakes up.", name()); + } + + public void goHome() { + LOGGER.info("{} goes home.", name()); + } + + public void goToMine() { + LOGGER.info("{} goes to the mine.", name()); + } + + private void action(Action action) { + switch (action) { + case GO_TO_SLEEP -> goToSleep(); + case WAKE_UP -> wakeUp(); + case GO_HOME -> goHome(); + case GO_TO_MINE -> goToMine(); + case WORK -> work(); + default -> LOGGER.info("Undefined action"); + } + } + + public void action(Action... actions) { + Arrays.stream(actions).forEach(this::action); + } + + public abstract void work(); + + public abstract String name(); + + enum Action { + GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK + } } +``` -public class DwarvenTunnelDigger extends DwarvenMineWorker { +Then we have the concrete dwarf classes `DwarvenTunnelDigger`, `DwarvenGoldDigger` and `DwarvenCartOperator`: - private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenTunnelDigger.class); +```java - @Override - public void work() { - LOGGER.info("{} creates another promising tunnel.", name()); - } +@Slf4j +public class DwarvenTunnelDigger extends DwarvenMineWorker { - @Override - public String name() { - return "Dwarven tunnel digger"; - } + @Override + public void work() { + LOGGER.info("{} creates another promising tunnel.", name()); + } + + @Override + public String name() { + return "Dwarven tunnel digger"; + } } +@Slf4j public class DwarvenGoldDigger extends DwarvenMineWorker { - private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenGoldDigger.class); - - @Override - public void work() { - LOGGER.info("{} digs for gold.", name()); - } + @Override + public void work() { + LOGGER.info("{} digs for gold.", name()); + } - @Override - public String name() { - return "Dwarf gold digger"; - } + @Override + public String name() { + return "Dwarf gold digger"; + } } +@Slf4j public class DwarvenCartOperator extends DwarvenMineWorker { - private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenCartOperator.class); - - @Override - public void work() { - LOGGER.info("{} moves gold chunks out of the mine.", name()); - } + @Override + public void work() { + LOGGER.info("{} moves gold chunks out of the mine.", name()); + } - @Override - public String name() { - return "Dwarf cart operator"; - } + @Override + public String name() { + return "Dwarf cart operator"; + } } ``` -To operate all these goldmine workers we have the facade +To operate all these goldmine workers we have the `DwarvenGoldmineFacade`: ```java public class DwarvenGoldmineFacade { - private final List workers; + private final List workers; - public DwarvenGoldmineFacade() { - workers = new ArrayList<>(); - workers.add(new DwarvenGoldDigger()); - workers.add(new DwarvenCartOperator()); - workers.add(new DwarvenTunnelDigger()); - } + public DwarvenGoldmineFacade() { + workers = List.of( + new DwarvenGoldDigger(), + new DwarvenCartOperator(), + new DwarvenTunnelDigger()); + } - public void startNewDay() { - makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); - } + public void startNewDay() { + makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); + } - public void digOutGold() { - makeActions(workers, DwarvenMineWorker.Action.WORK); - } + public void digOutGold() { + makeActions(workers, DwarvenMineWorker.Action.WORK); + } - public void endDay() { - makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); - } + public void endDay() { + makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); + } - private static void makeActions(Collection workers, - DwarvenMineWorker.Action... actions) { - for (DwarvenMineWorker worker : workers) { - worker.action(actions); + private static void makeActions(Collection workers, + DwarvenMineWorker.Action... actions) { + workers.forEach(worker -> worker.action(actions)); } - } } ``` -Now to use the facade +Now let's use the facade: ```java -DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade(); -facade.startNewDay(); -// Dwarf gold digger wakes up. -// Dwarf gold digger goes to the mine. -// Dwarf cart operator wakes up. -// Dwarf cart operator goes to the mine. -// Dwarven tunnel digger wakes up. -// Dwarven tunnel digger goes to the mine. -facade.digOutGold(); -// Dwarf gold digger digs for gold. -// Dwarf cart operator moves gold chunks out of the mine. -// Dwarven tunnel digger creates another promising tunnel. -facade.endDay(); -// Dwarf gold digger goes home. -// Dwarf gold digger goes to sleep. -// Dwarf cart operator goes home. -// Dwarf cart operator goes to sleep. -// Dwarven tunnel digger goes home. -// Dwarven tunnel digger goes to sleep. +public static void main(String[] args) { + var facade = new DwarvenGoldmineFacade(); + facade.startNewDay(); + facade.digOutGold(); + facade.endDay(); +} +``` + +Program output: + ``` +06:07:20.676 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf gold digger wakes up. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf gold digger goes to the mine. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf cart operator wakes up. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf cart operator goes to the mine. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarven tunnel digger wakes up. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarven tunnel digger goes to the mine. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenGoldDigger -- Dwarf gold digger digs for gold. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenCartOperator -- Dwarf cart operator moves gold chunks out of the mine. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenTunnelDigger -- Dwarven tunnel digger creates another promising tunnel. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf gold digger goes home. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf gold digger goes to sleep. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf cart operator goes home. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf cart operator goes to sleep. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarven tunnel digger goes home. +06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarven tunnel digger goes to sleep. +``` + +## When to Use the Facade Pattern in Java + +Use the Facade pattern in Java when: + +* You want to provide a simple interface to a complex subsystem. +* Subsystems are getting more complex and depend on multiple classes, but most clients only need a part of the functionality. +* There is a need to layer your subsystems. Use a facade to define an entry point to each subsystem level. +* You want to reduce dependencies and enhance code readability in Java development. + +## Facade Pattern Java Tutorials + +* [Facade Design Pattern in Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/facade-design-pattern-in-java) +* [Facade (Refactoring Guru)](https://refactoring.guru/design-patterns/facade) +* [Facade Method Design Pattern (GeekforGeeks)](https://www.geeksforgeeks.org/facade-design-pattern-introduction/) +* [Design Patterns - Facade Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/facade_pattern.htm) + +## Real-World Applications of Facade Pattern in Java + +* Java libraries such as java.net.URL and javax.faces.context.FacesContext use Facade to simplify complex underlying classes. +* In many Java frameworks, facades are used to simplify the usage of APIs by providing a simpler interface to more complex underlying code structures. + +## Benefits and Trade-offs of Facade Pattern + +Benefits: + +Implementing the Facade Design Pattern in Java: + +* Isolates clients from subsystem components, making it easier to use and reducing dependencies. +* Promotes weak coupling between the subsystem and its clients. +* Often simplifies the API of complex systems. + +Trade-offs: + +* A facade can become a god object coupled to all classes of an app if not implemented correctly. -## Applicability -Use the Facade pattern when +## Related Java Design Patterns -* you want to provide a simple interface to a complex subsystem. Subsystems often get more complex as they evolve. Most patterns, when applied, result in more and smaller classes. This makes the subsystem more reusable and easier to customize, but it also becomes harder to use for clients that don't need to customize it. A facade can provide a simple default view of the subsystem that is good enough for most clients. Only clients needing more customizability will need to look beyond the facade. -* there are many dependencies between clients and the implementation classes of an abstraction. Introduce a facade to decouple the subsystem from clients and other subsystems, thereby promoting subsystem independence and portability. -* you want to layer your subsystems. Use a facade to define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies between them by making them communicate with each other solely through their facades. +* [Adapter](https://java-design-patterns.com/patterns/adapter/): Facade provides a unified interface while Adapter makes two existing interfaces work together. +* [Mediator](https://java-design-patterns.com/patterns/mediator/): Facade defines a simpler interface to a subsystem while Mediator centralizes complex communications and control between objects. -## Credits +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3QbO7qN) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG) diff --git a/facade/etc/facade-sequence-diagram.png b/facade/etc/facade-sequence-diagram.png new file mode 100644 index 000000000000..d0172c01c5c8 Binary files /dev/null and b/facade/etc/facade-sequence-diagram.png differ diff --git a/facade/etc/facade.urm.png b/facade/etc/facade.urm.png new file mode 100644 index 000000000000..8e3ec7aca45e Binary files /dev/null and b/facade/etc/facade.urm.png differ diff --git a/facade/etc/facade.urm.puml b/facade/etc/facade.urm.puml new file mode 100644 index 000000000000..477f9eee7e47 --- /dev/null +++ b/facade/etc/facade.urm.puml @@ -0,0 +1,60 @@ +@startuml +package com.iluwatar.facade { + class App { + + App() + + main(args : String[]) {static} + } + class DwarvenCartOperator { + - LOGGER : Logger {static} + + DwarvenCartOperator() + + name() : String + + work() + } + class DwarvenGoldDigger { + - LOGGER : Logger {static} + + DwarvenGoldDigger() + + name() : String + + work() + } + class DwarvenGoldmineFacade { + - workers : List + + DwarvenGoldmineFacade() + + digOutGold() + + endDay() + - makeActions(workers : Collection, actions : Action[]) {static} + + startNewDay() + } + abstract class DwarvenMineWorker { + - LOGGER : Logger {static} + + DwarvenMineWorker() + - action(action : Action) + + action(actions : Action[]) + + goHome() + + goToMine() + + goToSleep() + + name() : String {abstract} + + wakeUp() + + work() {abstract} + } + ~enum Action { + + GO_HOME {static} + + GO_TO_MINE {static} + + GO_TO_SLEEP {static} + + WAKE_UP {static} + + WORK {static} + + valueOf(name : String) : Action {static} + + values() : Action[] {static} + } + class DwarvenTunnelDigger { + - LOGGER : Logger {static} + + DwarvenTunnelDigger() + + name() : String + + work() + } +} +DwarvenGoldmineFacade --> "-workers" DwarvenMineWorker +Action ..+ DwarvenMineWorker +DwarvenCartOperator --|> DwarvenMineWorker +DwarvenGoldDigger --|> DwarvenMineWorker +DwarvenTunnelDigger --|> DwarvenMineWorker +@enduml \ No newline at end of file diff --git a/facade/pom.xml b/facade/pom.xml index d0c459428aa7..916a3b0c45b8 100644 --- a/facade/pom.xml +++ b/facade/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT facade - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.facade.App + + + + + + + + diff --git a/facade/src/main/java/com/iluwatar/facade/App.java b/facade/src/main/java/com/iluwatar/facade/App.java index 93c38710b2c9..3773e269217c 100644 --- a/facade/src/main/java/com/iluwatar/facade/App.java +++ b/facade/src/main/java/com/iluwatar/facade/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,27 +25,25 @@ package com.iluwatar.facade; /** - * * The Facade design pattern is often used when a system is very complex or difficult to understand * because the system has a large number of interdependent classes or its source code is * unavailable. This pattern hides the complexities of the larger system and provides a simpler * interface to the client. It typically involves a single wrapper class which contains a set of * members required by client. These members access the system on behalf of the facade client and * hide the implementation details. - *

    - * In this example the Facade is ({@link DwarvenGoldmineFacade}) and it provides a simpler interface - * to the goldmine subsystem. - * + * + *

    In this example the Facade is ({@link DwarvenGoldmineFacade}) and it provides a simpler + * interface to the goldmine subsystem. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade(); + var facade = new DwarvenGoldmineFacade(); facade.startNewDay(); facade.digOutGold(); facade.endDay(); diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java b/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java index 01737dc8517e..9b077b242973 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java @@ -1,46 +1,42 @@ -/** - * 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.facade; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * DwarvenCartOperator is one of the goldmine subsystems. - * - */ -public class DwarvenCartOperator extends DwarvenMineWorker { - - private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenCartOperator.class); - - @Override - public void work() { - LOGGER.info("{} moves gold chunks out of the mine.", name()); - } - - @Override - public String name() { - return "Dwarf cart operator"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.facade; + +import lombok.extern.slf4j.Slf4j; + +/** DwarvenCartOperator is one of the goldmine subsystems. */ +@Slf4j +public class DwarvenCartOperator extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} moves gold chunks out of the mine.", name()); + } + + @Override + public String name() { + return "Dwarf cart operator"; + } +} diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java index a4e547f9e7bd..29cdc7424667 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java @@ -1,46 +1,42 @@ -/** - * 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.facade; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * DwarvenGoldDigger is one of the goldmine subsystems. - * - */ -public class DwarvenGoldDigger extends DwarvenMineWorker { - - private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenGoldDigger.class); - - @Override - public void work() { - LOGGER.info("{} digs for gold.", name()); - } - - @Override - public String name() { - return "Dwarf gold digger"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.facade; + +import lombok.extern.slf4j.Slf4j; + +/** DwarvenGoldDigger is one of the goldmine subsystems. */ +@Slf4j +public class DwarvenGoldDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} digs for gold.", name()); + } + + @Override + public String name() { + return "Dwarf gold digger"; + } +} diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java index d6cce8efd1cc..3e4151674b51 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java @@ -1,69 +1,62 @@ -/** - * 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.facade; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * - * DwarvenGoldmineFacade provides a single interface through which users can operate the subsystems. - * - * This makes the goldmine easier to operate and cuts the dependencies from the goldmine user to the - * subsystems. - * - */ -public class DwarvenGoldmineFacade { - - private final List workers; - - /** - * Constructor - */ - public DwarvenGoldmineFacade() { - workers = new ArrayList<>(); - workers.add(new DwarvenGoldDigger()); - workers.add(new DwarvenCartOperator()); - workers.add(new DwarvenTunnelDigger()); - } - - public void startNewDay() { - makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); - } - - public void digOutGold() { - makeActions(workers, DwarvenMineWorker.Action.WORK); - } - - public void endDay() { - makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); - } - - private static void makeActions(Collection workers, - DwarvenMineWorker.Action... actions) { - for (DwarvenMineWorker worker : workers) { - worker.action(actions); - } - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.facade; + +import java.util.Collection; +import java.util.List; + +/** + * DwarvenGoldmineFacade provides a single interface through which users can operate the subsystems. + * + *

    This makes the goldmine easier to operate and cuts the dependencies from the goldmine user to + * the subsystems. + */ +public class DwarvenGoldmineFacade { + + private final List workers; + + /** Constructor. */ + public DwarvenGoldmineFacade() { + workers = + List.of(new DwarvenGoldDigger(), new DwarvenCartOperator(), new DwarvenTunnelDigger()); + } + + public void startNewDay() { + makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); + } + + public void digOutGold() { + makeActions(workers, DwarvenMineWorker.Action.WORK); + } + + public void endDay() { + makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); + } + + private static void makeActions( + Collection workers, DwarvenMineWorker.Action... actions) { + workers.forEach(worker -> worker.action(actions)); + } +} diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java index bb80ae87409d..08af7cc2c878 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java @@ -1,92 +1,77 @@ -/** - * 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.facade; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * DwarvenMineWorker is one of the goldmine subsystems. - * - */ -public abstract class DwarvenMineWorker { - - private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenMineWorker.class); - - public void goToSleep() { - LOGGER.info("{} goes to sleep.", name()); - } - - public void wakeUp() { - LOGGER.info("{} wakes up.", name()); - } - - public void goHome() { - LOGGER.info("{} goes home.", name()); - } - - public void goToMine() { - LOGGER.info("{} goes to the mine.", name()); - } - - private void action(Action action) { - switch (action) { - case GO_TO_SLEEP: - goToSleep(); - break; - case WAKE_UP: - wakeUp(); - break; - case GO_HOME: - goHome(); - break; - case GO_TO_MINE: - goToMine(); - break; - case WORK: - work(); - break; - default: - LOGGER.info("Undefined action"); - break; - } - } - - /** - * Perform actions - */ - public void action(Action... actions) { - for (Action action : actions) { - action(action); - } - } - - public abstract void work(); - - public abstract String name(); - - static enum Action { - GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.facade; + +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; + +/** DwarvenMineWorker is one of the goldmine subsystems. */ +@Slf4j +public abstract class DwarvenMineWorker { + + public void goToSleep() { + LOGGER.info("{} goes to sleep.", name()); + } + + public void wakeUp() { + LOGGER.info("{} wakes up.", name()); + } + + public void goHome() { + LOGGER.info("{} goes home.", name()); + } + + public void goToMine() { + LOGGER.info("{} goes to the mine.", name()); + } + + private void action(Action action) { + switch (action) { + case GO_TO_SLEEP -> goToSleep(); + case WAKE_UP -> wakeUp(); + case GO_HOME -> goHome(); + case GO_TO_MINE -> goToMine(); + case WORK -> work(); + default -> LOGGER.info("Undefined action"); + } + } + + /** Perform actions. */ + public void action(Action... actions) { + Arrays.stream(actions).forEach(this::action); + } + + public abstract void work(); + + public abstract String name(); + + enum Action { + GO_TO_SLEEP, + WAKE_UP, + GO_HOME, + GO_TO_MINE, + WORK + } +} diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java b/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java index ac573b2421b0..4a8fa5a89959 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java @@ -1,46 +1,42 @@ -/** - * 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.facade; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * DwarvenTunnelDigger is one of the goldmine subsystems. - * - */ -public class DwarvenTunnelDigger extends DwarvenMineWorker { - - private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenTunnelDigger.class); - - @Override - public void work() { - LOGGER.info("{} creates another promising tunnel.", name()); - } - - @Override - public String name() { - return "Dwarven tunnel digger"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.facade; + +import lombok.extern.slf4j.Slf4j; + +/** DwarvenTunnelDigger is one of the goldmine subsystems. */ +@Slf4j +public class DwarvenTunnelDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} creates another promising tunnel.", name()); + } + + @Override + public String name() { + return "Dwarven tunnel digger"; + } +} diff --git a/facade/src/test/java/com/iluwatar/facade/AppTest.java b/facade/src/test/java/com/iluwatar/facade/AppTest.java index 366315e9e0d9..41d6d2a942b7 100644 --- a/facade/src/test/java/com/iluwatar/facade/AppTest.java +++ b/facade/src/test/java/com/iluwatar/facade/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.facade; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java index 19987acbc480..55baf907da56 100644 --- a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java +++ b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,49 +24,44 @@ */ package com.iluwatar.facade; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Date: 12/9/15 - 9:40 PM - * - * @author Jeroen Meulemeester - */ -public class DwarvenGoldmineFacadeTest { +/** DwarvenGoldmineFacadeTest */ +class DwarvenGoldmineFacadeTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } - /** + /** * Test a complete day cycle in the gold mine by executing all three different steps: {@link * DwarvenGoldmineFacade#startNewDay()}, {@link DwarvenGoldmineFacade#digOutGold()} and {@link * DwarvenGoldmineFacade#endDay()}. * - * See if the workers are doing what's expected from them on each step. + *

    See if the workers are doing what's expected from them on each step. */ @Test - public void testFullWorkDay() { - final DwarvenGoldmineFacade goldMine = new DwarvenGoldmineFacade(); + void testFullWorkDay() { + final var goldMine = new DwarvenGoldmineFacade(); goldMine.startNewDay(); // On the start of a day, all workers should wake up ... @@ -83,7 +80,7 @@ public void testFullWorkDay() { // Now do some actual work, start digging gold! goldMine.digOutGold(); - // Since we gave the dig command, every worker should be doing it's job ... + // Since we gave the dig command, every worker should be doing its job ... assertTrue(appender.logContains("Dwarf gold digger digs for gold.")); assertTrue(appender.logContains("Dwarf cart operator moves gold chunks out of the mine.")); assertTrue(appender.logContains("Dwarven tunnel digger creates another promising tunnel.")); @@ -108,9 +105,9 @@ public void testFullWorkDay() { assertEquals(15, appender.getLogSize()); } - private class InMemoryAppender extends AppenderBase { + private static class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); + private final List log = new LinkedList<>(); public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); @@ -127,9 +124,7 @@ public int getLogSize() { } public boolean logContains(String message) { - return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + return log.stream().map(ILoggingEvent::getFormattedMessage).anyMatch(message::equals); } } - - } diff --git a/factory-kit/README.md b/factory-kit/README.md index c257010479bd..cd97e53f915f 100644 --- a/factory-kit/README.md +++ b/factory-kit/README.md @@ -1,28 +1,158 @@ --- -layout: pattern -title: Factory Kit -folder: factory-kit -permalink: /patterns/factory-kit/ -categories: Creational -tags: - - Java - - Difficulty-Beginner - - Functional +title: "Factory Kit Pattern in Java: Crafting Flexible Component Assemblies" +shortTitle: Factory Kit +description: "Learn about the Factory Kit Pattern in Java with detailed explanations, real-world examples, and practical applications. Improve your Java skills with our comprehensive guide." +category: Creational +language: en +tag: + - Abstraction + - Decoupling + - Encapsulation + - Generic + - Instantiation + - Object composition --- -## Intent -Define a factory of immutable content with separated builder and factory interfaces. +## Also known as -![alt text](./etc/factory-kit.png "Factory Kit") +* Object Kit +* Toolkit -## Applicability -Use the Factory Kit pattern when +## Intent of Factory Kit Design Pattern -* a class can't anticipate the class of objects it must create -* you just want a new instance of a custom builder instead of the global one -* you explicitly want to define types of objects, that factory can build -* you want a separated builder and creator interface +The Factory Kit Pattern in Java is a powerful design pattern that helps in creating factories with separated builder and factory interfaces. This pattern is essential for managing complex object creation scenarios. -## Credits +## Detailed Explanation of Factory Kit Pattern with Real-World Examples -* [Design Pattern Reloaded by Remi Forax: ](https://www.youtube.com/watch?v=-k2X7guaArU) +Real-world example + +> An analogous real-world example of the Factory Kit Pattern is a restaurant kitchen where different types of dishes are prepared efficiently. This setup promotes flexibility and consistency, similar to how the Factory Kit Pattern operates in Java. Imagine the kitchen has a central station with various ingredients and recipes registered for different dishes. When an order comes in, the chef consults this central station to gather the necessary ingredients and follow the registered recipe to prepare the dish. This setup allows the kitchen to efficiently manage and switch between different dish preparations without the need for each chef to know the specifics of every recipe, promoting flexibility and consistency in the cooking process. + +In plain words + +> Factory kit is a configurable object builder, a factory to create factories. + +Sequence diagram + +![Factory Kit sequence diagram](./etc/factory-kit-sequence-diagram.png) + +## Programmatic Example of Factory Kit Pattern in Java + +Imagine a magical weapon factory in Java capable of creating any desired weapon using the Factory Kit Pattern. This pattern allows for configurable object builders, making it ideal for scenarios where the types of objects are not known upfront. + +Upon activation, the master recites the names of the weapon types needed to configure it. Once set up, any of these weapon types can be summoned instantly. + +Let's first define the simple `Weapon` hierarchy. + +```java +public interface Weapon { +} + +public enum WeaponType { + SWORD, + AXE, + BOW, + SPEAR +} + +public class Sword implements Weapon { + @Override + public String toString() { + return "Sword"; + } +} + +// Axe, Bow, and Spear are defined similarly... +``` + +Next, we define a functional interface that allows adding a builder with a name to the factory. + +```java +public interface Builder { + void add(WeaponType name, Supplier supplier); +} +``` + +The meat of the example is the `WeaponFactory` interface that effectively implements the factory kit pattern. The method `#factory` is used to configure the factory with the classes it needs to be able to construct. The method `#create` is then used to create object instances. + +```java +public interface WeaponFactory { + + static WeaponFactory factory(Consumer consumer) { + var map = new HashMap>(); + consumer.accept(map::put); + return name -> map.get(name).get(); + } + + Weapon create(WeaponType name); +} +``` + +Now, we can show how `WeaponFactory` can be used. + +```java + public static void main(String[] args) { + var factory = WeaponFactory.factory(builder -> { + builder.add(WeaponType.SWORD, Sword::new); + builder.add(WeaponType.AXE, Axe::new); + builder.add(WeaponType.SPEAR, Spear::new); + builder.add(WeaponType.BOW, Bow::new); + }); + var list = new ArrayList(); + list.add(factory.create(WeaponType.AXE)); + list.add(factory.create(WeaponType.SPEAR)); + list.add(factory.create(WeaponType.SWORD)); + list.add(factory.create(WeaponType.BOW)); + list.forEach(weapon -> LOGGER.info("{}", weapon.toString())); +} +``` + +Here is the console output when the example is run. + +``` +06:32:23.026 [main] INFO com.iluwatar.factorykit.App -- Axe +06:32:23.029 [main] INFO com.iluwatar.factorykit.App -- Spear +06:32:23.029 [main] INFO com.iluwatar.factorykit.App -- Sword +06:32:23.029 [main] INFO com.iluwatar.factorykit.App -- Bow +``` + +## When to Use the Factory Kit Pattern in Java + +Use the Factory Kit Pattern when + +* The factory class cannot anticipate the types of objects it must create, and a new instance of a custom builder is needed. +* A new instance of a custom builder is needed instead of a global one. +* The types of objects that the factory can build need to be defined outside the class. +* The builder and creator interfaces need to be separated. +* Game developments and other applications that have user customization. + +## Factory Kit Pattern Java Tutorials + +* [Factory Kit Pattern (Diego Pacheco)](https://diego-pacheco.medium.com/factory-kit-pattern-66d5ccb0c405) + +## Real-World Applications of Factory Kit Pattern in Java + +* In Java libraries such as the Java Development Kit (JDK) where different rendering engines might be instantiated based on the runtime environment. +* Frameworks like Spring or applications where dependency injection is heavily used, often implement this pattern to manage object creation more flexibly. + +## Benefits and Trade-offs of Factory Kit Pattern + +Benefits: + +* The Factory Kit Pattern in Java promotes loose coupling by eliminating the need to bind application-specific classes into the code. +* It simplifies the code by shifting the responsibility of instantiation to a factory object, making the development process more efficient. + +Trade-offs: + +* Can introduce complexity into the code by requiring additional classes and interfaces. +* Sometimes can lead to dependency issues if not properly managed. + +## Related Java Design Patterns + +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Often used together with the Factory Kit to create families of related objects. +* [Builder](https://java-design-patterns.com/patterns/builder/): Can be used to construct complex objects step-by-step using a similar approach. +* [Prototype](https://java-design-patterns.com/patterns/prototype/): Objects that are created by cloning a prototypical instance often use a factory to manage it. + +## References and Credits + +* [Design Pattern Reloaded (Remi Forax)](https://www.youtube.com/watch?v=-k2X7guaArU) diff --git a/factory-kit/etc/factory-kit-sequence-diagram.png b/factory-kit/etc/factory-kit-sequence-diagram.png new file mode 100644 index 000000000000..c2f07c2b9bf3 Binary files /dev/null and b/factory-kit/etc/factory-kit-sequence-diagram.png differ diff --git a/factory-kit/etc/factory-kit.urm.puml b/factory-kit/etc/factory-kit.urm.puml new file mode 100644 index 000000000000..23cf658f467e --- /dev/null +++ b/factory-kit/etc/factory-kit.urm.puml @@ -0,0 +1,46 @@ +@startuml +package com.iluwatar.factorykit { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Axe { + + Axe() + + toString() : String + } + class Bow { + + Bow() + + toString() : String + } + interface Builder { + + add(WeaponType, Supplier) {abstract} + } + class Spear { + + Spear() + + toString() : String + } + class Sword { + + Sword() + + toString() : String + } + interface Weapon { + } + interface WeaponFactory { + + create(WeaponType) : Weapon {abstract} + + factory(consumer : Consumer) : WeaponFactory {static} + } + enum WeaponType { + + AXE {static} + + BOW {static} + + SPEAR {static} + + SWORD {static} + + valueOf(name : String) : WeaponType {static} + + values() : WeaponType[] {static} + } +} +Axe ..|> Weapon +Bow ..|> Weapon +Spear ..|> Weapon +Sword ..|> Weapon +@enduml \ No newline at end of file diff --git a/factory-kit/pom.xml b/factory-kit/pom.xml index 1c8f4248ea10..729ea8c6b12d 100644 --- a/factory-kit/pom.xml +++ b/factory-kit/pom.xml @@ -1,8 +1,10 @@ - + - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - factory-kit - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - \ No newline at end of file + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + factory-kit + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.factorykit.App + + + + + + + + + diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/App.java b/factory-kit/src/main/java/com/iluwatar/factorykit/App.java index 7663701118da..e545c313e564 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/App.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,39 +24,43 @@ */ package com.iluwatar.factorykit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import lombok.extern.slf4j.Slf4j; /** - * Factory-kit is a creational pattern which defines a factory of immutable content - * with separated builder and factory interfaces to deal with the problem of - * creating one of the objects specified directly in the factory-kit instance. + * Factory kit is a creational pattern that defines a factory of immutable content with separated + * builder and factory interfaces to deal with the problem of creating one of the objects specified + * directly in the factory kit instance. * - *

    - * In the given example {@link WeaponFactory} represents the factory-kit, that contains - * four {@link Builder}s for creating new objects of - * the classes implementing {@link Weapon} interface. - *
    Each of them can be called with {@link WeaponFactory#create(WeaponType)} method, with - * an input representing an instance of {@link WeaponType} that needs to - * be mapped explicitly with desired class type in the factory instance. + *

    In the given example {@link WeaponFactory} represents the factory kit, that contains four + * {@link Builder}s for creating new objects of the classes implementing {@link Weapon} interface. + * + *

    Each of them can be called with {@link WeaponFactory#create(WeaponType)} method, with an input + * representing an instance of {@link WeaponType} that needs to be mapped explicitly with desired + * class type in the factory instance. */ +@Slf4j 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) { - WeaponFactory factory = WeaponFactory.factory(builder -> { - builder.add(WeaponType.SWORD, Sword::new); - builder.add(WeaponType.AXE, Axe::new); - builder.add(WeaponType.SPEAR, Spear::new); - builder.add(WeaponType.BOW, Bow::new); - }); - Weapon axe = factory.create(WeaponType.AXE); - LOGGER.info(axe.toString()); + var factory = + WeaponFactory.factory( + builder -> { + builder.add(WeaponType.SWORD, Sword::new); + builder.add(WeaponType.AXE, Axe::new); + builder.add(WeaponType.SPEAR, Spear::new); + builder.add(WeaponType.BOW, Bow::new); + }); + var list = new ArrayList(); + list.add(factory.create(WeaponType.AXE)); + list.add(factory.create(WeaponType.SPEAR)); + list.add(factory.create(WeaponType.SWORD)); + list.add(factory.create(WeaponType.BOW)); + list.forEach(weapon -> LOGGER.info("{}", weapon.toString())); } } diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java index 429728cbc721..583fa44a515b 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,9 +24,7 @@ */ package com.iluwatar.factorykit; -/** - * Class representing Axe - */ +/** Class representing Axe. */ public class Axe implements Weapon { @Override public String toString() { diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java index c655c3be851a..f052db8109a9 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,9 +24,7 @@ */ package com.iluwatar.factorykit; -/** - * Class representing Bows - */ +/** Class representing Bows. */ public class Bow implements Weapon { @Override public String toString() { diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Builder.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Builder.java index 8426c36a5a84..541932e8c8f1 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Builder.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Builder.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,9 +26,7 @@ import java.util.function.Supplier; -/** - * Functional interface that allows adding builder with name to the factory. - */ +/** Functional interface that allows adding builder with name to the factory. */ public interface Builder { void add(WeaponType name, Supplier supplier); } diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java index 15ff8b246283..9dfd97a07573 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -21,9 +23,8 @@ * THE SOFTWARE. */ package com.iluwatar.factorykit; -/** - * Class representing Spear - */ + +/** Class representing Spear. */ public class Spear implements Weapon { @Override public String toString() { diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java index 42ab5379992b..7f0320a3bc06 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -21,9 +23,8 @@ * THE SOFTWARE. */ package com.iluwatar.factorykit; -/** - * Class representing Swords - */ + +/** Class representing Swords. */ public class Sword implements Weapon { @Override public String toString() { diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Weapon.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Weapon.java index cf6a140dcd55..8501fd59f635 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Weapon.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Weapon.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,8 +24,5 @@ */ package com.iluwatar.factorykit; -/** - * Interface representing weapon. - */ -public interface Weapon { -} +/** Interface representing weapon. */ +public interface Weapon {} diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java b/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java index 8ee9c6c399f7..74bf0623b1a9 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,21 +25,21 @@ package com.iluwatar.factorykit; import java.util.HashMap; -import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; /** - * Functional interface, an example of the factory-kit design pattern. - *
    Instance created locally gives an opportunity to strictly define - * which objects types the instance of a factory will be able to create. - *
    Factory is a placeholder for {@link Builder}s - * with {@link WeaponFactory#create(WeaponType)} method to initialize new objects. + * Functional interface, an example of the factory-kit design pattern.
    + * Instance created locally gives an opportunity to strictly define which objects types the instance + * of a factory will be able to create.
    + * Factory is a placeholder for {@link Builder}s with {@link WeaponFactory#create(WeaponType)} + * method to initialize new objects. */ public interface WeaponFactory { /** * Creates an instance of the given type. + * * @param name representing enum of an object type to be created. * @return new instance of a requested class implementing {@link Weapon} interface. */ @@ -45,11 +47,12 @@ public interface WeaponFactory { /** * Creates factory - placeholder for specified {@link Builder}s. + * * @param consumer for the new builder to the factory. * @return factory with specified {@link Builder}s */ static WeaponFactory factory(Consumer consumer) { - Map> map = new HashMap<>(); + var map = new HashMap>(); consumer.accept(map::put); return name -> map.get(name).get(); } diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponType.java b/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponType.java index 3f0520190115..eee7e1136b29 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponType.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponType.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,9 +24,10 @@ */ package com.iluwatar.factorykit; -/** - * Enumerates {@link Weapon} types - */ +/** Enumerates {@link Weapon} types. */ public enum WeaponType { - SWORD, AXE, BOW, SPEAR + SWORD, + AXE, + BOW, + SPEAR } diff --git a/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java b/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java index 0be22b9b027d..afd4f6404711 100644 --- a/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java +++ b/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,16 @@ */ package com.iluwatar.factorykit.app; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import com.iluwatar.factorykit.App; import org.junit.jupiter.api.Test; -/** - * Application Test Entrypoint - */ -public class AppTest { +/** Application Test Entrypoint */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } - diff --git a/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java b/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java index f15223feb43c..02862a5d8cc3 100644 --- a/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java +++ b/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java @@ -1,6 +1,8 @@ - /** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,6 +24,8 @@ */ package com.iluwatar.factorykit.factorykit; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.factorykit.Axe; import com.iluwatar.factorykit.Spear; import com.iluwatar.factorykit.Sword; @@ -31,49 +35,49 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; - - /** - * Test Factory Kit Pattern - */ -public class FactoryKitTest { +/** Test Factory Kit Pattern */ +class FactoryKitTest { private WeaponFactory factory; @BeforeEach - public void init() { - factory = WeaponFactory.factory(builder -> { - builder.add(WeaponType.SPEAR, Spear::new); - builder.add(WeaponType.AXE, Axe::new); - builder.add(WeaponType.SWORD, Sword::new); - }); + void init() { + factory = + WeaponFactory.factory( + builder -> { + builder.add(WeaponType.SPEAR, Spear::new); + builder.add(WeaponType.AXE, Axe::new); + builder.add(WeaponType.SWORD, Sword::new); + }); } /** - * Testing {@link WeaponFactory} to produce a SPEAR asserting that the Weapon is an instance of {@link Spear} + * Testing {@link WeaponFactory} to produce a SPEAR asserting that the Weapon is an instance of + * {@link Spear} */ @Test - public void testSpearWeapon() { - Weapon weapon = factory.create(WeaponType.SPEAR); + void testSpearWeapon() { + var weapon = factory.create(WeaponType.SPEAR); verifyWeapon(weapon, Spear.class); } /** - * Testing {@link WeaponFactory} to produce a AXE asserting that the Weapon is an instance of {@link Axe} + * Testing {@link WeaponFactory} to produce a AXE asserting that the Weapon is an instance of + * {@link Axe} */ @Test - public void testAxeWeapon() { - Weapon weapon = factory.create(WeaponType.AXE); + void testAxeWeapon() { + var weapon = factory.create(WeaponType.AXE); verifyWeapon(weapon, Axe.class); } - /** - * Testing {@link WeaponFactory} to produce a SWORD asserting that the Weapon is an instance of {@link Sword} + * Testing {@link WeaponFactory} to produce a SWORD asserting that the Weapon is an instance of + * {@link Sword} */ @Test - public void testWeapon() { - Weapon weapon = factory.create(WeaponType.SWORD); + void testWeapon() { + var weapon = factory.create(WeaponType.SWORD); verifyWeapon(weapon, Sword.class); } @@ -81,9 +85,9 @@ public void testWeapon() { * This method asserts that the weapon object that is passed is an instance of the clazz * * @param weapon weapon object which is to be verified - * @param clazz expected class of the weapon + * @param clazz expected class of the weapon */ - private void verifyWeapon(Weapon weapon, Class clazz) { + private void verifyWeapon(Weapon weapon, Class clazz) { assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); } } diff --git a/factory-method/README.md b/factory-method/README.md index 087221fb9dfe..4334b052353d 100644 --- a/factory-method/README.md +++ b/factory-method/README.md @@ -1,27 +1,32 @@ --- -layout: pattern -title: Factory Method -folder: factory-method -permalink: /patterns/factory-method/ -categories: Creational -tags: - - Java - - Difficulty-Beginner - - Gang Of Four +title: "Factory Method Pattern in Java: Enhancing Flexibility with Polymorphic Manufacturing" +shortTitle: Factory Method +description: "Learn about the Factory Method pattern in Java. Explore examples, uses, benefits, and how it enhances code flexibility and maintenance." +category: Creational +language: en +tag: + - Encapsulation + - Gang of Four + - Instantiation + - Object composition + - Polymorphism --- ## Also known as -Virtual Constructor -## Intent -Define an interface for creating an object, but let subclasses -decide which class to instantiate. Factory Method lets a class defer -instantiation to subclasses. +* Virtual Constructor -## Explanation -Real world example +## Intent of Factory Method Design Pattern -> 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. +Define an interface for creating an object using the Factory Method Pattern, but let subclasses decide which class to instantiate. This creational design pattern lets a class defer instantiation to subclasses, enhancing code flexibility and maintenance. + +## Detailed Explanation of Factory Method Pattern with Real-World Examples + +Real-world example + +> Imagine a logistics company that needs to deliver different types of packages: standard, express, and oversized. The company has a central system that processes delivery requests but does not know the specifics of how each package type is handled. To manage this, the company uses a Factory Method pattern. +> +> In this setup, there is a central `DeliveryRequest` class with a method `createPackage()`. This method is overridden in subclasses like `StandardDelivery`, `ExpressDelivery`, and `OversizedDelivery`, each of which knows how to create and manage the respective package type. This way, the central system can handle delivery requests without needing to know the details of how each package type is created and processed, allowing for flexibility and easier maintenance. In plain words @@ -29,11 +34,19 @@ In plain words 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. +> 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. + +Sequence diagram + +![Factory Method sequence diagram](./etc/factory-method-sequence-diagram.png) - **Programmatic Example** +## Programmatic Example of Factory Method Pattern in Java -Taking our blacksmith example above. First of all we have a blacksmith interface and some implementations for it +The Factory Method approach is pivotal in Java Design Patterns for achieving flexible and maintainable code as we see in the following 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. + +First of all, we have a `Blacksmith` interface and some implementations for it: ```java public interface Blacksmith { @@ -42,38 +55,53 @@ public interface Blacksmith { public class ElfBlacksmith implements Blacksmith { public Weapon manufactureWeapon(WeaponType weaponType) { - return new ElfWeapon(weaponType); + return ELFARSENAL.get(weaponType); } } public class OrcBlacksmith implements Blacksmith { public Weapon manufactureWeapon(WeaponType weaponType) { - return new OrcWeapon(weaponType); + return ORCARSENAL.get(weaponType); } } ``` -Now as the customers come the correct type of blacksmith is summoned and requested weapons are manufactured +When the customers come, the correct type of blacksmith is summoned and requested weapons are manufactured: ```java -Blacksmith blacksmith = new ElfBlacksmith(); -blacksmith.manufactureWeapon(WeaponType.SPEAR); -blacksmith.manufactureWeapon(WeaponType.AXE); -// Elvish weapons are created +public static void main(String[] args) { + + Blacksmith blacksmith = new OrcBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + LOGGER.info(MANUFACTURED, blacksmith, weapon); + weapon = blacksmith.manufactureWeapon(WeaponType.AXE); + LOGGER.info(MANUFACTURED, blacksmith, weapon); + + blacksmith = new ElfBlacksmith(); + weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + LOGGER.info(MANUFACTURED, blacksmith, weapon); + weapon = blacksmith.manufactureWeapon(WeaponType.AXE); + LOGGER.info(MANUFACTURED, blacksmith, weapon); +} ``` -## Applicability -Use the Factory Method pattern when +Program output: +``` +06:40:07.269 [main] INFO com.iluwatar.factory.method.App -- The orc blacksmith manufactured an orcish spear +06:40:07.271 [main] INFO com.iluwatar.factory.method.App -- The orc blacksmith manufactured an orcish axe +06:40:07.272 [main] INFO com.iluwatar.factory.method.App -- The elf blacksmith manufactured an elven spear +06:40:07.272 [main] INFO com.iluwatar.factory.method.App -- The elf blacksmith manufactured an elven axe +``` -* a class can't anticipate the class of objects it must create -* a class wants its subclasses to specify the objects it creates -* classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate +## When to Use the Factory Method Pattern in Java -## Presentations +Use the Factory Method Pattern in Java when: -* [Factory Method Pattern](etc/presentation.html) +* Class cannot anticipate the class of objects it must create. +* Class wants its subclasses to specify the objects it creates. +* Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate. -## Real world examples +## Real-World Applications of Factory Method Pattern in Java * [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) * [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) @@ -82,7 +110,27 @@ Use the Factory Method pattern when * [java.net.URLStreamHandlerFactory](http://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html#createURLStreamHandler-java.lang.String-) * [java.util.EnumSet](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of-E-) * [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) +* Frameworks that run application components, configured dynamically at runtime. + +## Benefits and Trade-offs of Factory Method Pattern + +Benefits: + +* The Factory Method Pattern provides hooks for subclasses, enhancing code flexibility and maintainability. +* Connects parallel class hierarchies. +* Eliminates the need to bind application-specific classes into the code. The code only deals with the product interface; hence it can work with any user-defined concrete product classes. + +Trade-offs: + +* Can complicate the code by requiring the addition of new subclasses to implement the extended factory methods. + +## Related Java Design Patterns + +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Factory methods are often called within Abstract Factory patterns. +* [Prototype](https://java-design-patterns.com/patterns/prototype/): A factory method that returns a new instance of a class that is a clone of a prototype class. -## Credits +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0Rk5y) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG) +* [Patterns of Enterprise Application Architecture](https://amzn.to/4b2ZxoM) diff --git a/factory-method/etc/diagram1.png b/factory-method/etc/diagram1.png deleted file mode 100644 index fa325edf002a..000000000000 Binary files a/factory-method/etc/diagram1.png and /dev/null differ diff --git a/factory-method/etc/factory-method-sequence-diagram.png b/factory-method/etc/factory-method-sequence-diagram.png new file mode 100644 index 000000000000..d055d9ca956b Binary files /dev/null and b/factory-method/etc/factory-method-sequence-diagram.png differ diff --git a/factory-method/etc/factory-method.urm.png b/factory-method/etc/factory-method.urm.png new file mode 100644 index 000000000000..7c97aff91ee6 Binary files /dev/null and b/factory-method/etc/factory-method.urm.png differ diff --git a/factory-method/etc/factory-method.urm.puml b/factory-method/etc/factory-method.urm.puml new file mode 100644 index 000000000000..a5d8d4e22f7c --- /dev/null +++ b/factory-method/etc/factory-method.urm.puml @@ -0,0 +1,56 @@ +@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 { + - ELFARSENAL : Map {static} + + ElfBlacksmith() + + manufactureWeapon(weaponType : WeaponType) : Weapon + } + class ElfWeapon { + - weaponType : WeaponType + + ElfWeapon(weaponType : WeaponType) + + getWeaponType() : WeaponType + + toString() : String + } + class OrcBlacksmith { + - ORCARSENAL : Map {static} + + 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/presentation.html b/factory-method/etc/presentation.html deleted file mode 100644 index a78057836562..000000000000 --- a/factory-method/etc/presentation.html +++ /dev/null @@ -1,185 +0,0 @@ - - - - - Design Patterns - Factory Method Presentation - - - - - - - - - \ No newline at end of file diff --git a/factory-method/pom.xml b/factory-method/pom.xml index 124b1a73c40d..bdcfcea3cfcb 100644 --- a/factory-method/pom.xml +++ b/factory-method/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT factory-method - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.factory.method.App + + + + + + + + diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/App.java b/factory-method/src/main/java/com/iluwatar/factory/method/App.java index 3fb1056821ea..2094d2d6928a 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/App.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,61 +24,42 @@ */ package com.iluwatar.factory.method; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * - * The Factory Method is a creational design pattern which uses factory methods to deal with the + * The Factory Method is a creational design pattern that uses factory methods to deal with the * problem of creating objects without specifying the exact class of object that will be created. * This is done by creating objects via 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. - *

    - * In this Factory Method example we have an interface ({@link Blacksmith}) with a method for - * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses ( - * {@link OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce objects of - * their liking. - * + * + *

    In this Factory Method example we have an interface ({@link Blacksmith}) with a method for + * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses ( {@link + * OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce objects of their + * liking. */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + private static final String MANUFACTURED = "{} manufactured {}"; - private final Blacksmith blacksmith; - - /** - * Creates an instance of App which will use blacksmith to manufacture - * the weapons for war. - * App is unaware which concrete implementation of {@link Blacksmith} it is using. - * The decision of which blacksmith implementation to use may depend on configuration, or - * the type of rival in war. - * @param blacksmith a non-null implementation of blacksmith - */ - public App(Blacksmith blacksmith) { - this.blacksmith = blacksmith; - } - /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - // Lets go to war with Orc weapons - App app = new App(new OrcBlacksmith()); - app.manufactureWeapons(); - - // Lets go to war with Elf weapons - app = new App(new ElfBlacksmith()); - app.manufactureWeapons(); - } - - private void manufactureWeapons() { - Weapon weapon; + + Blacksmith blacksmith = new OrcBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + LOGGER.info(MANUFACTURED, blacksmith, weapon); + weapon = blacksmith.manufactureWeapon(WeaponType.AXE); + LOGGER.info(MANUFACTURED, blacksmith, weapon); + + blacksmith = new ElfBlacksmith(); weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); - LOGGER.info(weapon.toString()); + LOGGER.info(MANUFACTURED, blacksmith, weapon); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); - LOGGER.info(weapon.toString()); + LOGGER.info(MANUFACTURED, blacksmith, weapon); } } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java index e856d467eb6e..b027763ed673 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,13 +24,8 @@ */ package com.iluwatar.factory.method; -/** - * - * The interface containing method for producing objects. - * - */ +/** The interface containing method for producing objects. */ public interface Blacksmith { Weapon manufactureWeapon(WeaponType weaponType); - } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java index 66938bb1773b..881b82a6a3f4 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,15 +24,27 @@ */ package com.iluwatar.factory.method; -/** - * - * Concrete subclass for creating new objects. - * - */ +import java.util.Arrays; +import java.util.EnumMap; +import java.util.Map; + +/** Concrete subclass for creating new objects. */ public class ElfBlacksmith implements Blacksmith { + private static final Map ELFARSENAL; + + static { + ELFARSENAL = new EnumMap<>(WeaponType.class); + Arrays.stream(WeaponType.values()).forEach(type -> ELFARSENAL.put(type, new ElfWeapon(type))); + } + + @Override public Weapon manufactureWeapon(WeaponType weaponType) { - return new ElfWeapon(weaponType); + return ELFARSENAL.get(weaponType); } + @Override + public String toString() { + return "The elf blacksmith"; + } } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java index 95771e248b9e..58b188e2996c 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,24 +24,11 @@ */ package com.iluwatar.factory.method; -/** - * ElfWeapon. - */ -public class ElfWeapon implements Weapon { - - private WeaponType weaponType; - - public ElfWeapon(WeaponType weaponType) { - this.weaponType = weaponType; - } +/** ElfWeapon. */ +public record ElfWeapon(WeaponType weaponType) implements Weapon { @Override public String toString() { - return "Elven " + weaponType; - } - - @Override - public WeaponType getWeaponType() { - return weaponType; + return "an elven " + weaponType; } } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java index e2921a4b52cf..6657b66a4974 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,27 @@ */ package com.iluwatar.factory.method; -/** - * - * Concrete subclass for creating new objects. - * - */ +import java.util.Arrays; +import java.util.EnumMap; +import java.util.Map; + +/** Concrete subclass for creating new objects. */ public class OrcBlacksmith implements Blacksmith { + private static final Map ORCARSENAL; + + static { + ORCARSENAL = new EnumMap<>(WeaponType.class); + Arrays.stream(WeaponType.values()).forEach(type -> ORCARSENAL.put(type, new OrcWeapon(type))); + } + + @Override public Weapon manufactureWeapon(WeaponType weaponType) { - return new OrcWeapon(weaponType); + return ORCARSENAL.get(weaponType); + } + + @Override + public String toString() { + return "The orc blacksmith"; } } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java index 59ae0e7dc639..c7bf473ce275 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,24 +24,11 @@ */ package com.iluwatar.factory.method; -/** - * OrcWeapon. - */ -public class OrcWeapon implements Weapon { - - private WeaponType weaponType; - - public OrcWeapon(WeaponType weaponType) { - this.weaponType = weaponType; - } +/** OrcWeapon. */ +public record OrcWeapon(WeaponType weaponType) implements Weapon { @Override public String toString() { - return "Orcish " + weaponType; - } - - @Override - public WeaponType getWeaponType() { - return weaponType; + return "an orcish " + weaponType; } } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java index c642622c3313..0d5f12e488e0 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,8 @@ */ package com.iluwatar.factory.method; -/** - * Weapon interface. - */ +/** Weapon interface. */ public interface Weapon { - WeaponType getWeaponType(); - + WeaponType weaponType(); } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java index 9f5ce18764bb..e1ab11a1f22a 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,17 @@ */ package com.iluwatar.factory.method; -/** - * - * WeaponType enumeration - * - */ -public enum WeaponType { +import lombok.RequiredArgsConstructor; - SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED(""); - - private String title; +/** WeaponType enumeration. */ +@RequiredArgsConstructor +public enum WeaponType { + SHORT_SWORD("short sword"), + SPEAR("spear"), + AXE("axe"), + UNDEFINED(""); - WeaponType(String title) { - this.title = title; - } + private final String title; @Override public String toString() { diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java index 4a73077c1440..88fe6f6d7aa2 100644 --- a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java +++ b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,15 @@ */ package com.iluwatar.factory.method; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -import java.io.IOException; +/** Tests that Factory Method example runs without errors. */ +class AppTest { -/** - * Tests that Factory Method example runs without errors. - */ -public class AppTest { @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); + void shouldExecuteWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java index 75d8e46779c6..7cd4dbeb234d 100644 --- a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java +++ b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,79 +24,80 @@ */ package com.iluwatar.factory.method; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * The Factory Method is a creational design pattern which uses factory methods to deal with the * problem of creating objects without specifying the exact class of object that will be created. * This is done by creating objects via 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. - * - *

    Factory produces the object of its liking. - * The weapon {@link Weapon} manufactured by the + * + *

    Factory produces the object of its liking. The weapon {@link Weapon} manufactured by the * blacksmith depends on the kind of factory implementation it is referring to. - *

    */ -public class FactoryMethodTest { +class FactoryMethodTest { /** - * Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance - * of {@link OrcWeapon}. + * Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance of + * {@link OrcWeapon}. */ @Test - public void testOrcBlacksmithWithSpear() { - Blacksmith blacksmith = new OrcBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + void testOrcBlacksmithWithSpear() { + var blacksmith = new OrcBlacksmith(); + var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); verifyWeapon(weapon, WeaponType.SPEAR, OrcWeapon.class); } /** - * Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance - * of {@link OrcWeapon}. + * Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance of + * {@link OrcWeapon}. */ @Test - public void testOrcBlacksmithWithAxe() { - Blacksmith blacksmith = new OrcBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.AXE); + void testOrcBlacksmithWithAxe() { + var blacksmith = new OrcBlacksmith(); + var weapon = blacksmith.manufactureWeapon(WeaponType.AXE); verifyWeapon(weapon, WeaponType.AXE, OrcWeapon.class); } /** - * Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an - * instance of {@link ElfWeapon}. + * Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an instance + * of {@link ElfWeapon}. */ @Test - public void testElfBlacksmithWithShortSword() { - Blacksmith blacksmith = new ElfBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD); + void testElfBlacksmithWithShortSword() { + var blacksmith = new ElfBlacksmith(); + var weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD); verifyWeapon(weapon, WeaponType.SHORT_SWORD, ElfWeapon.class); } /** - * Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance - * of {@link ElfWeapon}. + * Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance of + * {@link ElfWeapon}. */ @Test - public void testElfBlacksmithWithSpear() { - Blacksmith blacksmith = new ElfBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + void testElfBlacksmithWithSpear() { + var blacksmith = new ElfBlacksmith(); + var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); verifyWeapon(weapon, WeaponType.SPEAR, ElfWeapon.class); } /** * This method asserts that the weapon object that is passed is an instance of the clazz and the * weapon is of type expectedWeaponType. - * + * * @param weapon weapon object which is to be verified * @param expectedWeaponType expected WeaponType of the weapon * @param clazz expected class of the weapon */ private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class clazz) { assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); - assertEquals(expectedWeaponType, weapon.getWeaponType(), "Weapon must be of weaponType: " + expectedWeaponType); + assertEquals( + expectedWeaponType, + weapon.weaponType(), + "Weapon must be of weaponType: " + expectedWeaponType); } } diff --git a/factory/README.md b/factory/README.md new file mode 100644 index 000000000000..e048b4b82e20 --- /dev/null +++ b/factory/README.md @@ -0,0 +1,154 @@ +--- +title: "Factory Pattern in Java: Streamlining Object Creation" +shortTitle: Factory +description: "Learn the Factory Design Pattern in Java with detailed examples and explanations. Understand how to create flexible and scalable code using the Factory Pattern. Ideal for developers looking to improve their object-oriented design skills." +category: Creational +language: en +tag: + - Abstraction + - Encapsulation + - Gang of Four + - Instantiation + - Polymorphism +--- + +## Intent of Factory Design Pattern + +The Factory Design Pattern in Java is a creational pattern that defines an interface for creating an object but allows subclasses to alter the type of objects that will be created. This pattern promotes flexibility and scalability in your codebase. + +## Detailed Explanation of Factory Pattern with Real-World Examples + +Real-world example + +> Imagine a scenario in a bakery where different types of cakes are made using a Factory Design Pattern. The bakery's `CakeFactory` handles the creation process, allowing easy addition of new cake types without altering the core cake-making process. The `CakeFactory` can produce various types of cakes such as chocolate cake, vanilla cake, and strawberry cake. Instead of the bakery staff manually selecting ingredients and following specific recipes for each type of cake, they use the `CakeFactory` to handle the process. The customer simply requests a cake type, and the `CakeFactory` determines the appropriate ingredients and recipe to use, then creates the specific type of cake. This setup allows the bakery to easily add new cake types without modifying the core cake-making process, promoting flexibility and scalability. + +Wikipedia says + +> Factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class. + +Sequence diagram + +![Factory sequence diagram](./etc/factory-sequence-diagram.png) + +## Programmatic Example of Factory Pattern in Java + +Imagine an alchemist who is about to manufacture coins. The alchemist must be able to create both gold and copper coins and switching between them must be possible without modifying the existing source code. The factory pattern makes it possible by providing a static construction method which can be called with relevant parameters. + +In Java, you can implement the Factory Pattern by defining an interface `Coin` and its implementations `GoldCoin` and `CopperCoin`. The `CoinFactory` class provides a static method `getCoin` to create coin objects based on the type. + +```java +public interface Coin { + String getDescription(); +} +``` + +```java +public class GoldCoin implements Coin { + + static final String DESCRIPTION = "This is a gold coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +```java +public class CopperCoin implements Coin { + + static final String DESCRIPTION = "This is a copper coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +Enumeration below represents types of coins that we support (`GoldCoin` and `CopperCoin`). + +```java +@RequiredArgsConstructor +@Getter +public enum CoinType { + + COPPER(CopperCoin::new), + GOLD(GoldCoin::new); + + private final Supplier constructor; +} +``` + +Then we have the static method `getCoin` to create coin objects encapsulated in the factory class `CoinFactory`. + +```java +public class CoinFactory { + + public static Coin getCoin(CoinType type) { + return type.getConstructor().get(); + } +} +``` + +Now, in the client code, we can generate various types of coins using the factory class. + +```java +public static void main(String[] args) { + LOGGER.info("The alchemist begins his work."); + var coin1 = CoinFactory.getCoin(CoinType.COPPER); + var coin2 = CoinFactory.getCoin(CoinType.GOLD); + LOGGER.info(coin1.getDescription()); + LOGGER.info(coin2.getDescription()); +} +``` + +Program output: + +``` +06:19:53.530 [main] INFO com.iluwatar.factory.App -- The alchemist begins his work. +06:19:53.533 [main] INFO com.iluwatar.factory.App -- This is a copper coin. +06:19:53.533 [main] INFO com.iluwatar.factory.App -- This is a gold coin. +``` + +## When to Use the Factory Pattern in Java + +* Use the Factory Design Pattern in Java when the class does not know beforehand the exact types and dependencies of the objects it needs to create. +* When a method returns one of several possible classes that share a common super class and wants to encapsulate the logic of which object to create. +* The pattern is commonly used when designing frameworks or libraries to give the best flexibility and isolation from concrete class types. + +## Real-World Applications of Factory Pattern in Java + +* [java.util.Calendar#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +* [java.util.ResourceBundle#getBundle()](https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +* [java.text.NumberFormat#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +* [java.nio.charset.Charset#forName()](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +* [java.net.URLStreamHandlerFactory#createURLStreamHandler(String)](https://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html) (returns different singleton objects, depending on a protocol) +* [java.util.EnumSet#of()](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of(E)) +* [javax.xml.bind.JAXBContext#createMarshaller()](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) and other similar methods. +* JavaFX uses Factory patterns for creating various UI controls tailored to the specifics of the user's environment. + +## Benefits and Trade-offs of Factory Pattern + +Benefits: + +* Implementing the Factory Pattern in your Java application reduces coupling between the implementation and the classes it uses. +* Supports the [Open/Closed Principle](https://java-design-patterns.com/principles/#open-closed-principle), as the system can introduce new types without changing existing code. + +Trade-offs: + +* The code can become more complicated due to the introduction of multiple additional classes. +* Overuse can make the code less readable if the underlying complexity of the object creation is low or unnecessary. + +## Related Java Design Patterns + +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Can be considered a kind of Factory that works with groups of products. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used in conjunction with Factory to ensure that a class has only one instance. +* [Builder](https://java-design-patterns.com/patterns/builder/): Separates the construction of a complex object from its representation, similar to how factories manage instantiation. +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): Is a factory of immutable content with separated builder and factory interfaces. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0Rk5y) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG) diff --git a/factory/etc/factory-sequence-diagram.png b/factory/etc/factory-sequence-diagram.png new file mode 100644 index 000000000000..260bea92f247 Binary files /dev/null and b/factory/etc/factory-sequence-diagram.png differ diff --git a/factory/etc/factory.urm.png b/factory/etc/factory.urm.png new file mode 100644 index 000000000000..4b3420792e06 Binary files /dev/null and b/factory/etc/factory.urm.png differ diff --git a/factory/etc/factory.urm.puml b/factory/etc/factory.urm.puml new file mode 100644 index 000000000000..eb08a4596cb4 --- /dev/null +++ b/factory/etc/factory.urm.puml @@ -0,0 +1,36 @@ +@startuml +package com.iluwatar.factory { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + interface Coin { + + getDescription() : String {abstract} + } + class CoinFactory { + + CoinFactory() + + getCoin(type : CoinType) : Coin {static} + } + enum CoinType { + + COPPER {static} + + GOLD {static} + - constructor : Supplier + + getConstructor() : Supplier + + valueOf(name : String) : CoinType {static} + + values() : CoinType[] {static} + } + class CopperCoin { + ~ DESCRIPTION : String {static} + + CopperCoin() + + getDescription() : String + } + class GoldCoin { + ~ DESCRIPTION : String {static} + + GoldCoin() + + getDescription() : String + } +} +CopperCoin ..|> Coin +GoldCoin ..|> Coin +@enduml \ No newline at end of file diff --git a/factory/pom.xml b/factory/pom.xml new file mode 100644 index 000000000000..7280d8b6d64a --- /dev/null +++ b/factory/pom.xml @@ -0,0 +1,72 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + factory + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.factory.App + + + + + + + + + diff --git a/factory/src/main/java/com/iluwatar/factory/App.java b/factory/src/main/java/com/iluwatar/factory/App.java new file mode 100644 index 000000000000..ce9f205b0f15 --- /dev/null +++ b/factory/src/main/java/com/iluwatar/factory/App.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.factory; + +import lombok.extern.slf4j.Slf4j; + +/** + * Factory is an object for creating other objects. It provides a static method to create and return + * objects of varying classes, in order to hide the implementation logic and makes client code focus + * on usage rather than objects initialization and management. + * + *

    In this example an alchemist manufactures coins. CoinFactory is the factory class, and it + * provides a static method to create different types of coins. + */ +@Slf4j +public class App { + + /** Program main entry point. */ + public static void main(String[] args) { + LOGGER.info("The alchemist begins his work."); + var coin1 = CoinFactory.getCoin(CoinType.COPPER); + var coin2 = CoinFactory.getCoin(CoinType.GOLD); + LOGGER.info(coin1.getDescription()); + LOGGER.info(coin2.getDescription()); + } +} diff --git a/factory/src/main/java/com/iluwatar/factory/Coin.java b/factory/src/main/java/com/iluwatar/factory/Coin.java new file mode 100644 index 000000000000..b8824222e5a8 --- /dev/null +++ b/factory/src/main/java/com/iluwatar/factory/Coin.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.factory; + +/** Coin interface. */ +public interface Coin { + + String getDescription(); +} diff --git a/factory/src/main/java/com/iluwatar/factory/CoinFactory.java b/factory/src/main/java/com/iluwatar/factory/CoinFactory.java new file mode 100644 index 000000000000..8940e3ade568 --- /dev/null +++ b/factory/src/main/java/com/iluwatar/factory/CoinFactory.java @@ -0,0 +1,34 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.factory; + +/** Factory of coins. */ +public class CoinFactory { + + /** Factory method takes as a parameter the coin type and calls the appropriate class. */ + public static Coin getCoin(CoinType type) { + return type.getConstructor().get(); + } +} diff --git a/factory/src/main/java/com/iluwatar/factory/CoinType.java b/factory/src/main/java/com/iluwatar/factory/CoinType.java new file mode 100644 index 000000000000..de1583bf9099 --- /dev/null +++ b/factory/src/main/java/com/iluwatar/factory/CoinType.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.factory; + +import java.util.function.Supplier; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +/** Enumeration for different types of coins. */ +@RequiredArgsConstructor +@Getter +public enum CoinType { + COPPER(CopperCoin::new), + GOLD(GoldCoin::new); + + private final Supplier constructor; +} diff --git a/factory/src/main/java/com/iluwatar/factory/CopperCoin.java b/factory/src/main/java/com/iluwatar/factory/CopperCoin.java new file mode 100644 index 000000000000..fa6f3f2d8ad3 --- /dev/null +++ b/factory/src/main/java/com/iluwatar/factory/CopperCoin.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.factory; + +/** CopperCoin implementation. */ +public class CopperCoin implements Coin { + + static final String DESCRIPTION = "This is a copper coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} diff --git a/factory/src/main/java/com/iluwatar/factory/GoldCoin.java b/factory/src/main/java/com/iluwatar/factory/GoldCoin.java new file mode 100644 index 000000000000..b5e1aef1a010 --- /dev/null +++ b/factory/src/main/java/com/iluwatar/factory/GoldCoin.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.factory; + +/** GoldCoin implementation. */ +public class GoldCoin implements Coin { + + static final String DESCRIPTION = "This is a gold coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} diff --git a/factory/src/test/java/com/iluwatar/factory/AppTest.java b/factory/src/test/java/com/iluwatar/factory/AppTest.java new file mode 100644 index 000000000000..702481525d45 --- /dev/null +++ b/factory/src/test/java/com/iluwatar/factory/AppTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.factory; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void shouldExecuteWithoutExceptions() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/factory/src/test/java/com/iluwatar/factory/CoinFactoryTest.java b/factory/src/test/java/com/iluwatar/factory/CoinFactoryTest.java new file mode 100644 index 000000000000..f7cf7799e8b6 --- /dev/null +++ b/factory/src/test/java/com/iluwatar/factory/CoinFactoryTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.factory; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class CoinFactoryTest { + + @Test + void shouldReturnGoldCoinInstance() { + final var goldCoin = CoinFactory.getCoin(CoinType.GOLD); + assertTrue(goldCoin instanceof GoldCoin); + } +} diff --git a/fanout-fanin/README.md b/fanout-fanin/README.md new file mode 100644 index 000000000000..12ba7cae53f1 --- /dev/null +++ b/fanout-fanin/README.md @@ -0,0 +1,177 @@ +--- +title: "Fan-Out Fan-In Pattern in Java: Maximizing Concurrency for Efficient Data Processing" +shortTitle: Fan-Out/Fan-In +description: "Learn how the Fan-Out/Fan-In design pattern in Java can optimize concurrency and processing efficiency. Explore real-world examples, detailed explanations, and programmatic implementations." +category: Concurrency +language: en +tag: + - Asynchronous + - Data processing + - Decoupling + - Scalability +--- + +## Also known as + +* Scatter-Gather + +## Intent of Fan-Out/Fan-In Design Pattern + +The Fan-Out/Fan-In design pattern in Java aims to improve concurrency and optimize processing time by dividing a task into multiple sub-tasks that can be processed in parallel (fan-out) and then combining the results of these sub-tasks into a single outcome (fan-in). + +## Detailed Explanation of Fan-Out/Fan-In Pattern with Real-World Examples + +Real-world example + +> A real-world example of the Fan-Out/Fan-In pattern in Java is a food delivery service like UberEats or DoorDash. When a customer places an order, the service (fan-out) sends out individual tasks to different restaurants to prepare the various items. Each restaurant works independently to prepare its part of the order. Once all restaurants have completed their tasks, the delivery service (fan-in) aggregates the items from different restaurants into a single order, ensuring that everything is delivered together to the customer. This parallel processing improves efficiency and ensures timely delivery. + +In plain words + +> The Fan-Out/Fan-In pattern distributes tasks across multiple concurrent processes or threads and then aggregates the results. + +Wikipedia says + +> In message-oriented middleware, the fan-out pattern models information exchange by delivering messages to one or multiple destinations in parallel, without waiting for responses. This allows a process to distribute tasks to various receivers simultaneously. +> +> The fan-in concept, on the other hand, typically refers to the aggregation of multiple inputs. In digital electronics, it describes the number of inputs a logic gate can handle. Combining these concepts, the Fan-Out/Fan-In pattern in software engineering involves distributing tasks (fan-out) and then aggregating the results (fan-in). + +Sequence diagram + +![Fan-Out/Fan-In flowchart](./etc/fan-out-fan-in-flowchart.png) + +## Programmatic Example of Fan-Out/Fan-In Pattern in Java + +The provided implementation involves a list of numbers with the objective to square them and aggregate the results. The `FanOutFanIn` class receives the list of numbers as `SquareNumberRequest` objects and a `Consumer` instance that collects the squared results as the requests complete. Each `SquareNumberRequest` squares its number with a random delay, simulating a long-running process that finishes at unpredictable times. The `Consumer` instance gathers the results from the various `SquareNumberRequest` objects as they become available at different times. + +Here's the `FanOutFanIn` class in Java that demonstrates the Fan-Out/Fan-In pattern by asynchronously distributing the requests. + +```java +public class FanOutFanIn { + public static Long fanOutFanIn(final List requests, final Consumer consumer) { + + ExecutorService service = Executors.newFixedThreadPool(requests.size()); + + // fanning out + List> futures = requests + .stream() + .map(request -> CompletableFuture.runAsync(() -> request.delayedSquaring(consumer), service)) + .collect(Collectors.toList()); + + CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); + + return consumer.getSumOfSquaredNumbers().get(); + } +} +``` + +`Consumer` is used a callback class that will be called when a request is completed. This will aggregate the result from all requests. + +```java +public class Consumer { + + private final AtomicLong sumOfSquaredNumbers; + + Consumer(Long init) { + sumOfSquaredNumbers = new AtomicLong(init); + } + + public Long add(final Long num) { + return sumOfSquaredNumbers.addAndGet(num); + } +} +``` + +Request is represented as a `SquareNumberRequest` that squares the number with random delay and calls the `Consumer` once it is squared. + +```java +public class SquareNumberRequest { + + private final Long number; + + public void delayedSquaring(final Consumer consumer) { + + var minTimeOut = 5000L; + + SecureRandom secureRandom = new SecureRandom(); + var randomTimeOut = secureRandom.nextInt(2000); + + try { + // this will make the thread sleep from 5-7s. + Thread.sleep(minTimeOut + randomTimeOut); + } catch (InterruptedException e) { + LOGGER.error("Exception while sleep ", e); + Thread.currentThread().interrupt(); + } finally { + consumer.add(number * number); + } + } +} +``` + +Here is the App class with main method to drive the example. + +```java +public static void main(String[] args) { + final List numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L); + + LOGGER.info("Numbers to be squared and get sum --> {}", numbers); + + final List requests = + numbers.stream().map(SquareNumberRequest::new).toList(); + + var consumer = new Consumer(0L); + + // Pass the request and the consumer to fanOutFanIn or sometimes referred as Orchestrator + // function + final Long sumOfSquaredNumbers = FanOutFanIn.fanOutFanIn(requests, consumer); + + LOGGER.info("Sum of all squared numbers --> {}", sumOfSquaredNumbers); +} +``` + +Running the example produces the following console output. + +``` +06:52:04.622 [main] INFO com.iluwatar.fanout.fanin.App -- Numbers to be squared and get sum --> [1, 3, 4, 7, 8] +06:52:11.465 [main] INFO com.iluwatar.fanout.fanin.App -- Sum of all squared numbers --> 139 +``` + +## When to Use the Fan-Out/Fan-In Pattern in Java + +The Fan-Out/Fan-In design pattern in Java is appropriate in scenarios where tasks can be broken down and executed in parallel, especially suitable for data processing, batch processing, and situations requiring aggregation of results from various sources. + +## Fan-Out/Fan-In Pattern Java Tutorials + +* [Fan-out/fan-in scenario in Durable Functions - Cloud backup example (Microsoft)](https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-cloud-backup) +* [Understanding Azure Durable Functions - Part 8: The Fan Out/Fan In Pattern (Don't Code Tired)](http://dontcodetired.com/blog/post/Understanding-Azure-Durable-Functions-Part-8-The-Fan-OutFan-In-Pattern) +* [Understanding the Fan-Out/Fan-In API Integration Pattern (DZone)](https://dzone.com/articles/understanding-the-fan-out-fan-in-api-integration-p) + +## Real-World Applications of Fan-Out/Fan-In Pattern in Java + +* The Fan-Out/Fan-In pattern in Java is widely used in large-scale data processing applications. +* Services requiring aggregation from multiple sources before delivering a response, such as in distributed caching or load balancing systems. + +## Benefits and Trade-offs of Fan-Out/Fan-In Pattern + +Benefits: + +* Enhances performance by parallel processing. +* Increases responsiveness of systems. +* Efficient utilization of multi-core processor architectures. + +Trade-offs: + +* Increased complexity in error handling. +* Potential for increased overhead due to task synchronization and result aggregation. +* Dependency on the underlying infrastructure's ability to support concurrent execution. + +## Related Java Design Patterns + +* MapReduce: Similar to Fan-Out/Fan-In, MapReduce also involves distributing tasks across a number of workers (map) and aggregating the results (reduce), which is particularly useful for processing large data sets. +* [Command](https://java-design-patterns.com/patterns/command/): Command Pattern facilitates the decoupling of the sender and the receiver, akin to how Fan-Out/Fan-In decouples task submission from task processing. +* [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Works synergistically with Fan-Out/Fan-In by organizing task execution where producers distribute tasks that are processed by multiple consumers, and results are then combined, enhancing throughput and efficiency in data processing. + +## References and Credits + +* [Java Concurrency in Practice](https://amzn.to/3vXytsb) +* [Patterns of Enterprise Application Architecture](https://amzn.to/49QQcPD) diff --git a/fanout-fanin/etc/fan-out-fan-in-flowchart.png b/fanout-fanin/etc/fan-out-fan-in-flowchart.png new file mode 100644 index 000000000000..cf726696cd76 Binary files /dev/null and b/fanout-fanin/etc/fan-out-fan-in-flowchart.png differ diff --git a/fanout-fanin/etc/fanout-fanin.png b/fanout-fanin/etc/fanout-fanin.png new file mode 100644 index 000000000000..e4b85006cf1c Binary files /dev/null and b/fanout-fanin/etc/fanout-fanin.png differ diff --git a/fanout-fanin/etc/fanout-fanin.urm.puml b/fanout-fanin/etc/fanout-fanin.urm.puml new file mode 100644 index 000000000000..57b741335962 --- /dev/null +++ b/fanout-fanin/etc/fanout-fanin.urm.puml @@ -0,0 +1,39 @@ +@startuml +package com.iluwatar.fanout.fanin { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Consumer { + - sumOfSquaredNumbers : AtomicLong + ~ Consumer(init : Long) + + add(num : Long) : Long + + getSumOfSquaredNumbers() : AtomicLong + } + class FanOutFanIn { + + FanOutFanIn() + + fanOutFanIn(requests : List, consumer : Consumer) : Long {static} + } + class SquareNumberRequest { + - LOGGER : Logger {static} + - number : Long + + SquareNumberRequest(number : Long) + + delayedSquaring(consumer : Consumer) + } + + object SquareNumberRequest1 + object SquareNumberRequest2 + object SquareNumberRequest3 + diamond dia +} + +App --> FanOutFanIn +FanOutFanIn --> "fan out - running in parallel" SquareNumberRequest1 +FanOutFanIn --> "fan out" SquareNumberRequest2 +FanOutFanIn --> "fan out" SquareNumberRequest3 +SquareNumberRequest1 --> "fan in - aggregate using callback" dia +SquareNumberRequest2 --> "fan in" dia +SquareNumberRequest3 --> "fan in" dia +dia --> Consumer +@enduml \ No newline at end of file diff --git a/fanout-fanin/pom.xml b/fanout-fanin/pom.xml new file mode 100644 index 000000000000..1052918ee83f --- /dev/null +++ b/fanout-fanin/pom.xml @@ -0,0 +1,70 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + fanout-fanin + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.fanout.fanin.App + + + + + + + + + diff --git a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/App.java b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/App.java new file mode 100644 index 000000000000..7a34c22149b5 --- /dev/null +++ b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/App.java @@ -0,0 +1,71 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.fanout.fanin; + +import java.util.Arrays; +import java.util.List; +import lombok.extern.slf4j.Slf4j; + +/** + * FanOut/FanIn pattern is a concurrency pattern that refers to executing multiple instances of the + * activity function concurrently. The "fan out" part is essentially splitting the data into + * multiple chunks and then calling the activity function multiple times, passing the chunks. + * + *

    When each chunk has been processed, the "fan in" takes place that aggregates results from each + * instance of function and forms a single final result. + * + *

    This pattern is only really useful if you can “chunk” the workload in a meaningful way for + * splitting up to be processed in parallel. + */ +@Slf4j +public class App { + + /** + * Entry point. + * + *

    Implementation provided has a list of numbers that has to be squared and added. The list can + * be chunked in any way and the "activity function" {@link + * SquareNumberRequest#delayedSquaring(Consumer)} i.e. squaring the number ca be done + * concurrently. The "fan in" part is handled by the {@link Consumer} that takes in the result + * from each instance of activity and aggregates it whenever that particular activity function + * gets over. + */ + public static void main(String[] args) { + final List numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L); + + LOGGER.info("Numbers to be squared and get sum --> {}", numbers); + + final List requests = + numbers.stream().map(SquareNumberRequest::new).toList(); + + var consumer = new Consumer(0L); + + // Pass the request and the consumer to fanOutFanIn or sometimes referred as Orchestrator + // function + final Long sumOfSquaredNumbers = FanOutFanIn.fanOutFanIn(requests, consumer); + + LOGGER.info("Sum of all squared numbers --> {}", sumOfSquaredNumbers); + } +} diff --git a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/Consumer.java b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/Consumer.java new file mode 100644 index 000000000000..95b7c663abe2 --- /dev/null +++ b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/Consumer.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.fanout.fanin; + +import java.util.concurrent.atomic.AtomicLong; +import lombok.Getter; + +/** + * Consumer or callback class that will be called every time a request is complete This will + * aggregate individual result to form a final result. + */ +@Getter +public class Consumer { + + private final AtomicLong sumOfSquaredNumbers; + + Consumer(Long init) { + sumOfSquaredNumbers = new AtomicLong(init); + } + + public Long add(final Long num) { + return sumOfSquaredNumbers.addAndGet(num); + } +} diff --git a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java new file mode 100644 index 000000000000..9239e03f46ee --- /dev/null +++ b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.fanout.fanin; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * FanOutFanIn class processes long-running requests, when any of the processes gets over, result is + * passed over to the consumer or the callback function. Consumer will aggregate the results as they + * keep on completing. + */ +public class FanOutFanIn { + + /** + * the main fanOutFanIn function or orchestrator function. + * + * @param requests List of numbers that need to be squared and summed up + * @param consumer Takes in the squared number from {@link SquareNumberRequest} and sums it up + * @return Aggregated sum of all squared numbers. + */ + public static Long fanOutFanIn( + final List requests, final Consumer consumer) { + + ExecutorService service = Executors.newFixedThreadPool(requests.size()); + + // fanning out + List> futures = + requests.stream() + .map( + request -> + CompletableFuture.runAsync(() -> request.delayedSquaring(consumer), service)) + .toList(); + + CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); + + return consumer.getSumOfSquaredNumbers().get(); + } +} diff --git a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/SquareNumberRequest.java b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/SquareNumberRequest.java new file mode 100644 index 000000000000..7f12e842031e --- /dev/null +++ b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/SquareNumberRequest.java @@ -0,0 +1,64 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.fanout.fanin; + +import java.security.SecureRandom; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** + * Squares the number with a little timeout to give impression of long-running process that return + * at different times. + */ +@Slf4j +@AllArgsConstructor +public class SquareNumberRequest { + + private final Long number; + + /** + * Squares the number with a little timeout to give impression of long-running process that return + * at different times. + * + * @param consumer callback class that takes the result after the delay. + */ + public void delayedSquaring(final Consumer consumer) { + + var minTimeOut = 5000L; + + SecureRandom secureRandom = new SecureRandom(); + var randomTimeOut = secureRandom.nextInt(2000); + + try { + // this will make the thread sleep from 5-7s. + Thread.sleep(minTimeOut + randomTimeOut); + } catch (InterruptedException e) { + LOGGER.error("Exception while sleep ", e); + Thread.currentThread().interrupt(); + } finally { + consumer.add(number * number); + } + } +} diff --git a/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/AppTest.java b/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/AppTest.java new file mode 100644 index 000000000000..0fe64096fddb --- /dev/null +++ b/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/AppTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.fanout.fanin; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void shouldLaunchApp() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/FanOutFanInTest.java b/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/FanOutFanInTest.java new file mode 100644 index 000000000000..55260c36aa3c --- /dev/null +++ b/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/FanOutFanInTest.java @@ -0,0 +1,47 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.fanout.fanin; + +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class FanOutFanInTest { + + @Test + void fanOutFanInTest() { + final List numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L); + + final List requests = + numbers.stream().map(SquareNumberRequest::new).toList(); + + final Consumer consumer = new Consumer(0L); + + final Long sumOfSquaredNumbers = FanOutFanIn.fanOutFanIn(requests, consumer); + + Assertions.assertEquals(139, sumOfSquaredNumbers); + } +} diff --git a/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/SquareNumberRequestTest.java b/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/SquareNumberRequestTest.java new file mode 100644 index 000000000000..738e2fda761d --- /dev/null +++ b/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/SquareNumberRequestTest.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.fanout.fanin; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class SquareNumberRequestTest { + + @Test + void delayedSquaringTest() { + Consumer consumer = new Consumer(10L); + + SquareNumberRequest squareNumberRequest = new SquareNumberRequest(5L); + + squareNumberRequest.delayedSquaring(consumer); + + Assertions.assertEquals(35, consumer.getSumOfSquaredNumbers().get()); + } +} diff --git a/faq.md b/faq.md deleted file mode 100644 index 01a7e7b7235d..000000000000 --- a/faq.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -layout: page -title: FAQ -permalink: /faq/ -icon: fa-question -page-index: 5 ---- - -### Q1: What is the difference between State and Strategy patterns? {#Q1} - -While the implementation is similar they solve different problems. The State -pattern deals with what state an object is in - it encapsulates state-dependent -behavior. -The Strategy pattern deals with how an object performs a certain task - it -encapsulates an algorithm. - -### Q2: What is the difference between Strategy and Template Method patterns? {#Q2} - -In Template Method the algorithm is chosen at compile time via inheritance. -With Strategy pattern the algorithm is chosen at runtime via composition. - -### Q3: What is the difference between Proxy and Decorator patterns? {#Q3} - -The difference is the intent of the patterns. While Proxy controls access to -the object Decorator is used to add responsibilities to the object. - -### Q4: What is the difference between Chain of Responsibility and Intercepting Filter patterns? {#Q4} - -While the implementations look similar there are differences. The Chain of -Responsibility forms a chain of request processors and the processors are then -executed one by one until the correct processor is found. In Intercepting -Filter the chain is constructed from filters and the whole chain is always -executed. - -### Q5: What is the difference between Visitor and Double Dispatch patterns? {#Q5} - -The Visitor pattern is a means of adding a new operation to existing classes. -Double dispatch is a means of dispatching function calls with respect to two -polymorphic types, rather than a single polymorphic type, which is what -languages like C++ and Java _do not_ support directly. - -### Q6: What are the differences between Flyweight and Object Pool patterns? {#Q6} - -They differ in the way they are used. - -Pooled objects can simultaneously be used by a single "client" only. For that, -a pooled object must be checked out from the pool, then it can be used by a -client, and then the client must return the object back to the pool. Multiple -instances of identical objects may exist, up to the maximal capacity of the -pool. - -In contrast, a Flyweight object is singleton, and it can be used simultaneously -by multiple clients. - -As for concurrent access, pooled objects can be mutable and they usually don't -need to be thread safe, as typically, only one thread is going to use a -specific instance at the same time. Flyweight must either be immutable (the -best option), or implement thread safety. - -As for performance and scalability, pools can become bottlenecks, if all the -pooled objects are in use and more clients need them, threads will become -blocked waiting for available object from the pool. This is not the case with -Flyweight. - -### Q7: What are the differences between FluentInterface and Builder patterns? {#Q7} - -Fluent interfaces are sometimes confused with the Builder pattern, because they share method chaining and a fluent usage. However, fluent interfaces are not primarily used to create shared (mutable) objects, but to configure complex objects without having to respecify the target object on every property change. - -### Q8: What is the difference between java.io.Serialization and Memento pattern? {#Q8} - -Memento is typically used to implement rollback/save-point support. Example we might want to mark the state of an object at a point in time, do some work and then decide to rollback to the previous state. - -On the other hand serialization may be used as a tool to save the state of an object into byte[] and preserving the contents in memory or disk. When someone invokes the memento to revert object's previous state then we can deserialize the information stored and recreate previous state. - -So Memento is a pattern and serialization is a tool that can be used to implement this pattern. Other ways to implement the pattern can be to clone the contents of the object and keep track of those clones. diff --git a/feature-toggle/README.md b/feature-toggle/README.md index c466b8a9454b..dc2d913a86ed 100644 --- a/feature-toggle/README.md +++ b/feature-toggle/README.md @@ -1,32 +1,151 @@ --- -layout: pattern -title: Feature Toggle -folder: feature-toggle -permalink: /patterns/feature-toggle/ -categories: Behavioral -tags: - - Java - - Difficulty-Beginner +title: "Feature Toggle Pattern in Java: Managing Features in Production Seamlessly" +shortTitle: Feature Toggle +description: "Learn how to implement the Feature Toggle design pattern in Java. This guide covers dynamic feature management, benefits, use cases, and practical examples to help you enhance your software development process." +category: Behavioral +language: en +tag: + - Decoupling + - Extensibility + - Feature management + - Scalability --- ## Also known as -Feature Flag -## Intent -Used to switch code execution paths based on properties or groupings. Allowing new features to be released, tested -and rolled out. Allowing switching back to the older feature quickly if needed. It should be noted that this pattern, -can easily introduce code complexity. There is also cause for concern that the old feature that the toggle is eventually -going to phase out is never removed, causing redundant code smells and increased maintainability. +* Feature Flag +* Feature Switch -![alt text](./etc/feature-toggle.png "Feature Toggle") +## Intent of Feature Toggle Design Pattern -## Applicability -Use the Feature Toggle pattern when +To enable or disable features in a software application dynamically without deploying new code. -* Giving different features to different users. +## Detailed Explanation of Feature Toggle Pattern with Real-World Examples + +Real-world Example + +> A real-world example of the Feature Toggle pattern is Netflix's rollout of new user interface features. When Netflix decides to introduce a new feature, such as a redesigned homepage layout or a new recommendation algorithm, they use feature toggles to control the release. Initially, the new feature is toggled off for most users, allowing only a small group of users (e.g., beta testers) to experience and provide feedback on the feature. Based on the feedback and performance metrics, Netflix can quickly toggle the feature on for a broader audience or turn it off if issues are detected, all without redeploying the application. This approach allows Netflix to continuously innovate and improve their platform while minimizing risk and ensuring a stable user experience. + +In plain words + +> The Feature Toggle design pattern in Java allows developers to introduce new features gradually instead of deploying them all at once, facilitating better dynamic feature management. + +Wikipedia says + +> A feature toggle in software development provides an alternative to maintaining multiple feature branches in source code. A condition within the code enables or disables a feature during runtime. In agile settings the toggle is used in production, to switch on the feature on demand, for some or all the users. + +Flowchart + +![Feature Toggle flowchart](./etc/feature-toggle-flowchart.png) + +## Programmatic Example of Feature Toggle Pattern in Java + +This Java code example demonstrates how to display a feature when it is enabled by the developer and the user is a Premium member of the application. This approach is useful for managing subscription-locked features. + +The Feature Toggle pattern enables the seamless activation or deactivation of entire code executions. This allows features to be managed dynamically based on user information or configuration properties. + +Key Components: + +1. `PropertiesFeatureToggleVersion`: This class uses properties to control the feature toggle. The properties determine whether the enhanced version of the welcome message, which is personalized, is turned on or off. + +2. `TieredFeatureToggleVersion`: This class uses user information to control the feature toggle. The feature of the personalized welcome message is dependent on the user group the user is in. + +3. `User`: This class represents the user of the application. + +4. `UserGroup`: This class represents the group the user belongs to. + +```java +public static void main(String[] args) { + + // Demonstrates the PropertiesFeatureToggleVersion running with properties + // that set the feature toggle to enabled. + + final var properties = new Properties(); + properties.put("enhancedWelcome", true); + var service = new PropertiesFeatureToggleVersion(properties); + final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + LOGGER.info(welcomeMessage); + + // Demonstrates the PropertiesFeatureToggleVersion running with properties + // that set the feature toggle to disabled. Note the difference in the printed welcome message + // where the username is not included. + + final var turnedOff = new Properties(); + turnedOff.put("enhancedWelcome", false); + var turnedOffService = new PropertiesFeatureToggleVersion(turnedOff); + final var welcomeMessageturnedOff = + turnedOffService.getWelcomeMessage(new User("Jamie No Code")); + LOGGER.info(welcomeMessageturnedOff); + + // Demonstrates the TieredFeatureToggleVersion setup with + // two users: one on the free tier and the other on the paid tier. When the + // Service#getWelcomeMessage(User) method is called with the paid user, the welcome + // message includes their username. In contrast, calling the same service with the free tier user results + // in a more generic welcome message without the username. + + var service2 = new TieredFeatureToggleVersion(); + + final var paidUser = new User("Jamie Coder"); + final var freeUser = new User("Alan Defect"); + + UserGroup.addUserToPaidGroup(paidUser); + UserGroup.addUserToFreeGroup(freeUser); + + final var welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser); + final var welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser); + LOGGER.info(welcomeMessageFreeUser); + LOGGER.info(welcomeMessagePaidUser); +} +``` + +Running the example produces the following output. + +``` +07:31:50.802 [main] INFO com.iluwatar.featuretoggle.App -- Welcome Jamie No Code. You're using the enhanced welcome message. +07:31:50.804 [main] INFO com.iluwatar.featuretoggle.App -- Welcome to the application. +07:31:50.804 [main] INFO com.iluwatar.featuretoggle.App -- I suppose you can use this software. +07:31:50.804 [main] INFO com.iluwatar.featuretoggle.App -- You're amazing Jamie Coder. Thanks for paying for this awesome software. +``` + +## When to Use the Feature Toggle Pattern in Java + +Use the Feature Toggle Pattern in Java when: + +* Dynamic feature management to different users and groups. * Rolling out a new feature incrementally. * Switching between development and production environments. +* Quickly disable problematic features +* External management of feature deployment +* Ability to maintain multiple version releases of a feature +* 'Hidden' deployment, releasing a feature in code for designated testing but not publicly making it available + +## Real-World Applications of Feature Toggle Pattern in Java + +* Many web development platforms utilize the Feature Toggle design pattern to gradually roll out new features to users, ensuring stability and effective dynamic feature management. +* Enterprise applications use feature toggles to enable or disable features during runtime to cater to different market needs. + +## Benefits and Trade-offs of Feature Toggle Pattern + +Benefits: + +* Facilitates A/B testing and canary releases. +* Allows for quicker rollback and minimal risk deployments. +* Enables conditional feature execution without redeploying the application. + +Trade-offs: + +* Code complexity is increased. +* Testing of multiple states is harder and more time-consuming. +* Potential for technical debt if toggles remain in the code longer than necessary. +* Risk of toggle misconfiguration leading to unexpected behavior. + +## Related Java Design Patterns + +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Both patterns allow changing the behavior of software at runtime. The Feature Toggle changes features dynamically, while the Strategy allows switching algorithms or strategies. +* [Observer](https://java-design-patterns.com/patterns/observer/): Useful for implementing feature toggles by notifying components of feature state changes, which allows dynamic feature modification without restarts. -## Credits +## References and Credits -* [Martin Fowler 29 October 2010 (2010-10-29).](http://martinfowler.com/bliki/FeatureToggle.html) \ No newline at end of file +* [Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation](https://amzn.to/4488ESM) +* [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3UoeJY4) +* [Feature Toggle (Martin Fowler)](http://martinfowler.com/bliki/FeatureToggle.html) diff --git a/feature-toggle/etc/feature-toggle-flowchart.png b/feature-toggle/etc/feature-toggle-flowchart.png new file mode 100644 index 000000000000..8a62b1b59309 Binary files /dev/null and b/feature-toggle/etc/feature-toggle-flowchart.png differ diff --git a/feature-toggle/etc/feature-toggle.urm.puml b/feature-toggle/etc/feature-toggle.urm.puml new file mode 100644 index 000000000000..0febb26319d1 --- /dev/null +++ b/feature-toggle/etc/feature-toggle.urm.puml @@ -0,0 +1,48 @@ +@startuml +package com.iluwatar.featuretoggle.pattern { + interface Service { + + getWelcomeMessage(User) : String {abstract} + + isEnhanced() : boolean {abstract} + } +} +package com.iluwatar.featuretoggle.user { + class User { + - name : String + + User(name : String) + + toString() : String + } + class UserGroup { + - freeGroup : List {static} + - paidGroup : List {static} + + UserGroup() + + addUserToFreeGroup(user : User) {static} + + addUserToPaidGroup(user : User) {static} + + isPaid(user : User) : boolean {static} + } +} +package com.iluwatar.featuretoggle.pattern.tieredversion { + class TieredFeatureToggleVersion { + + TieredFeatureToggleVersion() + + getWelcomeMessage(user : User) : String + + isEnhanced() : boolean + } +} +package com.iluwatar.featuretoggle.pattern.propertiesversion { + class PropertiesFeatureToggleVersion { + - isEnhanced : boolean + + PropertiesFeatureToggleVersion(properties : Properties) + + getWelcomeMessage(user : User) : String + + isEnhanced() : boolean + } +} +package com.iluwatar.featuretoggle { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } +} +UserGroup --> "-freeGroup" User +PropertiesFeatureToggleVersion ..|> Service +TieredFeatureToggleVersion ..|> Service +@enduml \ No newline at end of file diff --git a/feature-toggle/pom.xml b/feature-toggle/pom.xml index 3c6c7af945e0..c21080827a57 100644 --- a/feature-toggle/pom.xml +++ b/feature-toggle/pom.xml @@ -1,8 +1,10 @@ - - - - java-design-patterns - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - - feature-toggle - - - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - \ No newline at end of file + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + feature-toggle + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.featuretoggle.App + + + + + + + + + diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java index 351936b2cd64..30c729dd8992 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,7 +22,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.featuretoggle; import com.iluwatar.featuretoggle.pattern.Service; @@ -28,75 +29,85 @@ import com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion; import com.iluwatar.featuretoggle.user.User; import com.iluwatar.featuretoggle.user.UserGroup; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Properties; +import lombok.extern.slf4j.Slf4j; /** - * The Feature Toggle pattern allows for complete code executions to be turned on or off with ease. This allows features - * to be controlled by either dynamic methods just as {@link User} information or by {@link Properties}. In the App - * below there are two examples. Firstly the {@link Properties} version of the feature toggle, where the enhanced - * version of the welcome message which is personalised is turned either on or off at instance creation. This method - * is not as dynamic as the {@link User} driven version where the feature of the personalised welcome message is - * dependant on the {@link UserGroup} the {@link User} is in. So if the user is a memeber of the - * {@link UserGroup#isPaid(User)} then they get an ehanced version of the welcome message. - * - * Note that this pattern can easily introduce code complexity, and if not kept in check can result in redundant - * unmaintained code within the codebase. + * The Feature Toggle pattern allows for complete code executions to be turned on or off with ease. + * This allows features to be controlled by either dynamic methods just as {@link User} information + * or by {@link Properties}. In the App below there are two examples. Firstly the {@link Properties} + * version of the feature toggle, where the enhanced version of the welcome message which is + * personalised is turned either on or off at instance creation. This method is not as dynamic as + * the {@link User} driven version where the feature of the personalised welcome message is + * dependent on the {@link UserGroup} the {@link User} is in. So if the user is a member of the + * {@link UserGroup#isPaid(User)} then they get an enhanced version of the welcome message. * + *

    Note that this pattern can easily introduce code complexity, and if not kept in check can + * result in redundant unmaintained code within the codebase. */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * Block 1 shows the {@link PropertiesFeatureToggleVersion} being run with {@link Properties} setting the feature - * toggle to enabled. + * Block 1 shows the {@link PropertiesFeatureToggleVersion} being run with {@link Properties} + * setting the feature toggle to enabled. * - * Block 2 shows the {@link PropertiesFeatureToggleVersion} being run with {@link Properties} setting the feature - * toggle to disabled. Notice the difference with the printed welcome message the username is not included. + *

    Block 2 shows the {@link PropertiesFeatureToggleVersion} being run with {@link Properties} + * setting the feature toggle to disabled. Notice the difference with the printed welcome message + * the username is not included. * - * Block 3 shows the {@link com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion} being - * set up with two users on who is on the free level, while the other is on the paid level. When the - * {@link Service#getWelcomeMessage(User)} is called with the paid {@link User} note that the welcome message - * contains their username, while the same service call with the free tier user is more generic. No username is - * printed. + *

    Block 3 shows the {@link + * com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion} being set up with + * two users on who is on the free level, while the other is on the paid level. When the {@link + * Service#getWelcomeMessage(User)} is called with the paid {@link User} note that the welcome + * message contains their username, while the same service call with the free tier user is more + * generic. No username is printed. * - * @see User - * @see UserGroup - * @see Service - * @see PropertiesFeatureToggleVersion - * @see com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion + * @see User + * @see UserGroup + * @see Service + * @see PropertiesFeatureToggleVersion + * @see com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion */ public static void main(String[] args) { - final Properties properties = new Properties(); + // Demonstrates the PropertiesFeatureToggleVersion running with properties + // that set the feature toggle to enabled. + + final var properties = new Properties(); properties.put("enhancedWelcome", true); - Service service = new PropertiesFeatureToggleVersion(properties); - final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + var service = new PropertiesFeatureToggleVersion(properties); + final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); LOGGER.info(welcomeMessage); - // --------------------------------------------- + // Demonstrates the PropertiesFeatureToggleVersion running with properties + // that set the feature toggle to disabled. Note the difference in the printed welcome message + // where the username is not included. - final Properties turnedOff = new Properties(); + final var turnedOff = new Properties(); turnedOff.put("enhancedWelcome", false); - Service turnedOffService = new PropertiesFeatureToggleVersion(turnedOff); - final String welcomeMessageturnedOff = turnedOffService.getWelcomeMessage(new User("Jamie No Code")); + var turnedOffService = new PropertiesFeatureToggleVersion(turnedOff); + final var welcomeMessageturnedOff = + turnedOffService.getWelcomeMessage(new User("Jamie No Code")); LOGGER.info(welcomeMessageturnedOff); - // -------------------------------------------- - - Service service2 = new TieredFeatureToggleVersion(); + // Demonstrates the TieredFeatureToggleVersion setup with + // two users: one on the free tier and the other on the paid tier. When the + // Service#getWelcomeMessage(User) method is called with the paid user, the welcome + // message includes their username. In contrast, calling the same service with the free tier + // user results + // in a more generic welcome message without the username. + + var service2 = new TieredFeatureToggleVersion(); - final User paidUser = new User("Jamie Coder"); - final User freeUser = new User("Alan Defect"); + final var paidUser = new User("Jamie Coder"); + final var freeUser = new User("Alan Defect"); UserGroup.addUserToPaidGroup(paidUser); UserGroup.addUserToFreeGroup(freeUser); - final String welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser); - final String welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser); + final var welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser); + final var welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser); LOGGER.info(welcomeMessageFreeUser); LOGGER.info(welcomeMessagePaidUser); } diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java index 284ccf2ab2cb..7c8287622bda 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -25,10 +27,11 @@ import com.iluwatar.featuretoggle.user.User; /** - * Simple interfaces to allow the calling of the method to generate the welcome message for a given user. While there is - * a helper method to gather the the status of the feature toggle. In some cases there is no need for the - * {@link Service#isEnhanced()} in {@link com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion} - * where the toggle is determined by the actual {@link User}. + * Simple interfaces to allow the calling of the method to generate the welcome message for a given + * user. While there is a helper method to gather the status of the feature toggle. In some cases + * there is no need for the {@link Service#isEnhanced()} in {@link + * com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion} where the toggle is + * determined by the actual {@link User}. * * @see com.iluwatar.featuretoggle.pattern.propertiesversion.PropertiesFeatureToggleVersion * @see com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion @@ -50,5 +53,4 @@ public interface Service { * @return Boolean {@code true} if enhanced. */ boolean isEnhanced(); - } diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java index 1ded334ec7d7..cfc2ab56b293 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -24,29 +26,37 @@ import com.iluwatar.featuretoggle.pattern.Service; import com.iluwatar.featuretoggle.user.User; - import java.util.Properties; +import lombok.Getter; /** - * This example of the Feature Toogle pattern is less dynamic version than - * {@link com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion} where the feature is turned on - * or off at the time of creation of the service. This example uses simple Java {@link Properties} however it could as - * easily be done with an external configuration file loaded by Spring and so on. A good example of when to use this - * version of the feature toggle is when new features are being developed. So you could have a configuration property - * boolean named development or some sort of system environment variable. + * This example of the Feature Toggle pattern is less dynamic version than {@link + * com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion} where the feature is + * turned on or off at the time of creation of the service. This example uses simple Java {@link + * Properties} however it could as easily be done with an external configuration file loaded by + * Spring and so on. A good example of when to use this version of the feature toggle is when new + * features are being developed. So you could have a configuration property boolean named + * development or some sort of system environment variable. * * @see Service * @see com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion * @see User */ +@Getter public class PropertiesFeatureToggleVersion implements Service { - private boolean isEnhanced; + /** + * True if the welcome message to be returned is the enhanced venison or not. For this service it + * will see the value of the boolean that was set in the constructor {@link + * PropertiesFeatureToggleVersion#PropertiesFeatureToggleVersion(Properties)} + */ + private final boolean enhanced; /** - * Creates an instance of {@link PropertiesFeatureToggleVersion} using the passed {@link Properties} to determine, - * the status of the feature toggle {@link PropertiesFeatureToggleVersion#isEnhanced()}. There is also some defensive - * code to ensure the {@link Properties} passed are as expected. + * Creates an instance of {@link PropertiesFeatureToggleVersion} using the passed {@link + * Properties} to determine, the status of the feature toggle {@link + * PropertiesFeatureToggleVersion#isEnhanced()}. There is also some defensive code to ensure the + * {@link Properties} passed are as expected. * * @param properties {@link Properties} used to configure the service and toggle features. * @throws IllegalArgumentException when the passed {@link Properties} is not as expected @@ -57,7 +67,7 @@ public PropertiesFeatureToggleVersion(final Properties properties) { throw new IllegalArgumentException("No Properties Provided."); } else { try { - isEnhanced = (boolean) properties.get("enhancedWelcome"); + enhanced = (boolean) properties.get("enhancedWelcome"); } catch (Exception e) { throw new IllegalArgumentException("Invalid Enhancement Settings Provided."); } @@ -65,14 +75,14 @@ public PropertiesFeatureToggleVersion(final Properties properties) { } /** - * Generate a welcome message based on the user being passed and the status of the feature toggle. If the enhanced - * version is enabled, then the message will be personalised with the name of the passed {@link User}. However if - * disabled then a generic version fo the message is returned. + * Generate a welcome message based on the user being passed and the status of the feature toggle. + * If the enhanced version is enabled, then the message will be personalised with the name of the + * passed {@link User}. However, if disabled then a generic version fo the message is returned. * - * @param user the {@link User} to be displayed in the message if the enhanced version is enabled see - * {@link PropertiesFeatureToggleVersion#isEnhanced()}. If the enhanced version is enabled, then the - * message will be personalised with the name of the passed {@link User}. However if disabled then a - * generic version fo the message is returned. + * @param user the {@link User} to be displayed in the message if the enhanced version is enabled + * see {@link PropertiesFeatureToggleVersion#isEnhanced()}. If the enhanced version is + * enabled, then the message will be personalised with the name of the passed {@link User}. + * However, if disabled then a generic version fo the message is returned. * @return Resulting welcome message. * @see User */ @@ -85,16 +95,4 @@ public String getWelcomeMessage(final User user) { return "Welcome to the application."; } - - /** - * Method that checks if the welcome message to be returned is the enhanced venison or not. For this service it will - * see the value of the boolean that was set in the constructor - * {@link PropertiesFeatureToggleVersion#PropertiesFeatureToggleVersion(Properties)} - * - * @return Boolean value {@code true} if enhanced. - */ - @Override - public boolean isEnhanced() { - return isEnhanced; - } } diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java index 887c9f663bfe..f5342da01a57 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -27,11 +29,12 @@ import com.iluwatar.featuretoggle.user.UserGroup; /** - * This example of the Feature Toogle pattern shows how it could be implemented based on a {@link User}. Therefore - * showing its use within a tiered application where the paying users get access to different content or - * better versions of features. So in this instance a {@link User} is passed in and if they are found to be - * on the {@link UserGroup#isPaid(User)} they are welcomed with a personalised message. While the other is more - * generic. However this pattern is limited to simple examples such as the one below. + * This example of the Feature Toggle pattern shows how it could be implemented based on a {@link + * User}. Therefore, showing its use within a tiered application where the paying users get access + * to different content or better versions of features. So in this instance a {@link User} is passed + * in and if they are found to be on the {@link UserGroup#isPaid(User)} they are welcomed with a + * personalised message. While the other is more generic. However, this pattern is limited to simple + * examples such as the one below. * * @see Service * @see User @@ -41,12 +44,13 @@ public class TieredFeatureToggleVersion implements Service { /** - * Generates a welcome message from the passed {@link User}. The resulting message depends on the group of the - * {@link User}. So if the {@link User} is in the {@link UserGroup#paidGroup} then the enhanced version of the - * welcome message will be returned where the username is displayed. + * Generates a welcome message from the passed {@link User}. The resulting message depends on the + * group of the {@link User}. So if the {@link User} is in the {@link UserGroup#paidGroup} then + * the enhanced version of the welcome message will be returned where the username is displayed. * - * @param user the {@link User} to generate the welcome message for, different messages are displayed if the user is - * in the {@link UserGroup#isPaid(User)} or {@link UserGroup#freeGroup} + * @param user the {@link User} to generate the welcome message for, different messages are + * displayed if the user is in the {@link UserGroup#isPaid(User)} or {@link + * UserGroup#freeGroup} * @return Resulting welcome message. * @see User * @see UserGroup @@ -61,9 +65,9 @@ public String getWelcomeMessage(User user) { } /** - * Method that checks if the welcome message to be returned is the enhanced version. For this instance as the logic - * is driven by the user group. This method is a little redundant. However can be used to show that there is an - * enhanced version available. + * Method that checks if the welcome message to be returned is the enhanced version. For this + * instance as the logic is driven by the user group. This method is a little redundant. However, + * can be used to show that there is an enhanced version available. * * @return Boolean value {@code true} if enhanced. */ @@ -71,5 +75,4 @@ public String getWelcomeMessage(User user) { public boolean isEnhanced() { return true; } - } diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java index baf25aa8b7d6..61a56845ad9d 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,25 +24,22 @@ */ package com.iluwatar.featuretoggle.user; +import lombok.RequiredArgsConstructor; + /** - * Used to demonstrate the purpose of the feature toggle. This class actually has nothing to do with the pattern. + * Used to demonstrate the purpose of the feature toggle. This class actually has nothing to do with + * the pattern. */ +@RequiredArgsConstructor public class User { - private String name; - - /** - * Default Constructor setting the username. - * - * @param name {@link String} to represent the name of the user. - */ - public User(String name) { - this.name = name; - } + private final String name; /** * {@inheritDoc} - * @return The {@link String} representation of the User, in this case just return the name of the user. + * + * @return The {@link String} representation of the User, in this case just return the name of the + * user. */ @Override public String toString() { diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java index cb84ec533274..d01c5735d19e 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -26,16 +28,16 @@ import java.util.List; /** - * Contains the lists of users of different groups paid and free. Used to demonstrate the tiered example of feature - * toggle. Allowing certain features to be available to only certain groups of users. + * Contains the lists of users of different groups paid and free. Used to demonstrate the tiered + * example of feature toggle. Allowing certain features to be available to only certain groups of + * users. * * @see User */ public class UserGroup { - private static List freeGroup = new ArrayList<>(); - private static List paidGroup = new ArrayList<>(); - + private static final List freeGroup = new ArrayList<>(); + private static final List paidGroup = new ArrayList<>(); /** * Add the passed {@link User} to the free user group list. @@ -46,7 +48,7 @@ public class UserGroup { */ public static void addUserToFreeGroup(final User user) throws IllegalArgumentException { if (paidGroup.contains(user)) { - throw new IllegalArgumentException("User all ready member of paid group."); + throw new IllegalArgumentException("User already member of paid group."); } else { if (!freeGroup.contains(user)) { freeGroup.add(user); @@ -63,7 +65,7 @@ public static void addUserToFreeGroup(final User user) throws IllegalArgumentExc */ public static void addUserToPaidGroup(final User user) throws IllegalArgumentException { if (freeGroup.contains(user)) { - throw new IllegalArgumentException("User all ready member of free group."); + throw new IllegalArgumentException("User already member of free group."); } else { if (!paidGroup.contains(user)) { paidGroup.add(user); @@ -75,7 +77,6 @@ public static void addUserToPaidGroup(final User user) throws IllegalArgumentExc * Method to take a {@link User} to determine if the user is in the {@link UserGroup#paidGroup}. * * @param user {@link User} to check if they are in the {@link UserGroup#paidGroup} - * * @return true if the {@link User} is in {@link UserGroup#paidGroup} */ public static boolean isPaid(User user) { diff --git a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java index 9f0d377fa380..52badacaba2b 100644 --- a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java +++ b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -20,58 +22,54 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.featuretoggle.pattern.propertiesversion; -import com.iluwatar.featuretoggle.pattern.Service; -import com.iluwatar.featuretoggle.user.User; -import org.junit.jupiter.api.Test; - -import java.util.Properties; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Test Properties Toggle - */ -public class PropertiesFeatureToggleVersionTest { +import com.iluwatar.featuretoggle.user.User; +import java.util.Properties; +import org.junit.jupiter.api.Test; + +/** Test Properties Toggle */ +class PropertiesFeatureToggleVersionTest { @Test - public void testNullPropertiesPassed() throws Exception { - assertThrows(IllegalArgumentException.class, () -> { - new PropertiesFeatureToggleVersion(null); - }); + void testNullPropertiesPassed() { + assertThrows(IllegalArgumentException.class, () -> new PropertiesFeatureToggleVersion(null)); } @Test - public void testNonBooleanProperty() throws Exception { - assertThrows(IllegalArgumentException.class, () -> { - final Properties properties = new Properties(); - properties.setProperty("enhancedWelcome", "Something"); - new PropertiesFeatureToggleVersion(properties); - }); + void testNonBooleanProperty() { + assertThrows( + IllegalArgumentException.class, + () -> { + final var properties = new Properties(); + properties.setProperty("enhancedWelcome", "Something"); + new PropertiesFeatureToggleVersion(properties); + }); } @Test - public void testFeatureTurnedOn() throws Exception { - final Properties properties = new Properties(); + void testFeatureTurnedOn() { + final var properties = new Properties(); properties.put("enhancedWelcome", true); - Service service = new PropertiesFeatureToggleVersion(properties); + var service = new PropertiesFeatureToggleVersion(properties); assertTrue(service.isEnhanced()); - final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); - assertEquals("Welcome Jamie No Code. You're using the enhanced welcome message.", welcomeMessage); + final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + assertEquals( + "Welcome Jamie No Code. You're using the enhanced welcome message.", welcomeMessage); } @Test - public void testFeatureTurnedOff() throws Exception { - final Properties properties = new Properties(); + void testFeatureTurnedOff() { + final var properties = new Properties(); properties.put("enhancedWelcome", false); - Service service = new PropertiesFeatureToggleVersion(properties); + var service = new PropertiesFeatureToggleVersion(properties); assertFalse(service.isEnhanced()); - final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); assertEquals("Welcome to the application.", welcomeMessage); } } diff --git a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java index 0ed0afea96a3..67314f4041e3 100644 --- a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java +++ b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,46 +24,44 @@ */ package com.iluwatar.featuretoggle.pattern.tieredversion; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.featuretoggle.pattern.Service; import com.iluwatar.featuretoggle.user.User; import com.iluwatar.featuretoggle.user.UserGroup; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Test Tiered Feature Toggle - */ -public class TieredFeatureToggleVersionTest { +/** Test Tiered Feature Toggle */ +class TieredFeatureToggleVersionTest { final User paidUser = new User("Jamie Coder"); final User freeUser = new User("Alan Defect"); final Service service = new TieredFeatureToggleVersion(); @BeforeEach - public void setUp() throws Exception { + void setUp() { UserGroup.addUserToPaidGroup(paidUser); UserGroup.addUserToFreeGroup(freeUser); } @Test - public void testGetWelcomeMessageForPaidUser() throws Exception { - final String welcomeMessage = service.getWelcomeMessage(paidUser); - final String expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software."; + void testGetWelcomeMessageForPaidUser() { + final var welcomeMessage = service.getWelcomeMessage(paidUser); + final var expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software."; assertEquals(expected, welcomeMessage); } @Test - public void testGetWelcomeMessageForFreeUser() throws Exception { - final String welcomeMessage = service.getWelcomeMessage(freeUser); - final String expected = "I suppose you can use this software."; + void testGetWelcomeMessageForFreeUser() { + final var welcomeMessage = service.getWelcomeMessage(freeUser); + final var expected = "I suppose you can use this software."; assertEquals(expected, welcomeMessage); } @Test - public void testIsEnhancedAlwaysTrueAsTiered() throws Exception { + void testIsEnhancedAlwaysTrueAsTiered() { assertTrue(service.isEnhanced()); } } diff --git a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java index 2771655ddefa..b9bfb0befed4 100644 --- a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java +++ b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,46 +24,40 @@ */ package com.iluwatar.featuretoggle.user; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Test User Group specific feature - */ -public class UserGroupTest { +import org.junit.jupiter.api.Test; + +/** Test User Group specific feature */ +class UserGroupTest { @Test - public void testAddUserToFreeGroup() throws Exception { - User user = new User("Free User"); + void testAddUserToFreeGroup() { + var user = new User("Free User"); UserGroup.addUserToFreeGroup(user); assertFalse(UserGroup.isPaid(user)); } @Test - public void testAddUserToPaidGroup() throws Exception { - User user = new User("Paid User"); + void testAddUserToPaidGroup() { + var user = new User("Paid User"); UserGroup.addUserToPaidGroup(user); assertTrue(UserGroup.isPaid(user)); } @Test - public void testAddUserToPaidWhenOnFree() throws Exception { - User user = new User("Paid User"); + void testAddUserToPaidWhenOnFree() { + var user = new User("Paid User"); UserGroup.addUserToFreeGroup(user); - assertThrows(IllegalArgumentException.class, () -> { - UserGroup.addUserToPaidGroup(user); - }); + assertThrows(IllegalArgumentException.class, () -> UserGroup.addUserToPaidGroup(user)); } @Test - public void testAddUserToFreeWhenOnPaid() throws Exception { - User user = new User("Free User"); + void testAddUserToFreeWhenOnPaid() { + var user = new User("Free User"); UserGroup.addUserToPaidGroup(user); - assertThrows(IllegalArgumentException.class, () -> { - UserGroup.addUserToFreeGroup(user); - }); + assertThrows(IllegalArgumentException.class, () -> UserGroup.addUserToFreeGroup(user)); } } diff --git a/filterer/README.md b/filterer/README.md new file mode 100644 index 000000000000..bfb5640f8640 --- /dev/null +++ b/filterer/README.md @@ -0,0 +1,271 @@ +--- +title: "Filterer Pattern in Java: Streamlining Data Processing with Dynamic Filters" +shortTitle: Filterer +description: "Learn about the Filterer design pattern in Java, which enhances data processing flexibility by applying a series of filters to data objects. Ideal for dynamic and scalable filtering solutions." +language: en +category: Behavioral +tag: + - Data processing + - Data transformation + - Decoupling + - Functional decomposition + - Object composition + - Performance + - Runtime +--- + +## Also known as + +* Filters +* Pipes and Filters + +## Intent of Filterer Design Pattern + +The Filterer design pattern in Java is essential for creating dynamic and scalable filtering solutions. This pattern allows the application of a series of filters to data objects, enhancing data processing flexibility and scalability. + +## Detailed Explanation of Filterer Pattern with Real-World Examples + +Real-world example + +> Imagine a library system employing the Filterer pattern to dynamically combine filter criteria such as genre, author, and availability. This Java pattern makes the system more maintainable and scalable. Instead of writing separate methods for each possible combination of criteria, the library system employs the Filterer design pattern. Each filter criterion is encapsulated as an object, and these filter objects can be combined dynamically at runtime to create complex filtering logic. For example, a user can search for books that are both available and published after 2010 by combining the availability filter and the publication year filter. This approach makes the system more flexible and easier to maintain, as new filtering criteria can be added without modifying existing code. + +In plain words + +> Filterer pattern is a design pattern that helps container-like objects return filtered versions of themselves. + +Flowchart + +![Filterer flowchart](./etc/filterer-flowchart.png) + +## Programmatic Example of Filterer Pattern in Java + +To illustrate, we use the Filterer design pattern for a malware detection system in Java. This system can filter threats based on various criteria, showcasing the pattern’s flexibility and dynamic nature. In the design we have to take into consideration that new Threat types can be added later. Additionally, there is a requirement that the threat detection system can filter the detected threats based on different criteria (the target system acts as container-like object for threats). + +To model the threat detection system, we introduce `Threat` and `ThreatAwareSystem` interfaces. + +```java +public interface Threat { + String name(); + int id(); + ThreatType type(); +} +``` + +```java +public interface ThreatAwareSystem { + String systemId(); + List threats(); + Filterer filtered(); +} +``` + +Notice the `filtered` method that returns instance of `Filterer` interface which is defined as: + +```java +@FunctionalInterface +public interface Filterer { + G by(Predicate predicate); +} +``` + +A simple implementation of `ThreatAwareSystem`: + +```java +public class SimpleThreatAwareSystem implements ThreatAwareSystem { + + private final String systemId; + private final ImmutableList issues; + + public SimpleThreatAwareSystem(final String systemId, final List issues) { + this.systemId = systemId; + this.issues = ImmutableList.copyOf(issues); + } + + @Override + public String systemId() { + return systemId; + } + + @Override + public List threats() { + return new ArrayList<>(issues); + } + + @Override + public Filterer filtered() { + return this::filteredGroup; + } + + private ThreatAwareSystem filteredGroup(Predicate predicate) { + return new SimpleThreatAwareSystem(this.systemId, filteredItems(predicate)); + } + + private List filteredItems(Predicate predicate) { + return this.issues.stream() + .filter(predicate) + .collect(Collectors.toList()); + } +} +``` + +Now if we introduce a new subtype of `Threat` interface that adds probability with which given threat can appear: + +```java +public interface ProbableThreat extends Threat { + double probability(); +} +``` + +We can also introduce a new interface that represents a system that is aware of threats with their probabilities: + +```java +public interface ProbabilisticThreatAwareSystem extends ThreatAwareSystem { + @Override + List threats(); + @Override + Filterer filtered(); +} +``` + +We will be able to filter `ProbabilisticThreatAwareSystem` by `ProbableThreat` properties: + +```java +public class SimpleProbabilisticThreatAwareSystem implements ProbabilisticThreatAwareSystem { + + private final String systemId; + private final ImmutableList threats; + + public SimpleProbabilisticThreatAwareSystem(final String systemId, final List threats) { + this.systemId = systemId; + this.threats = ImmutableList.copyOf(threats); + } + + @Override + public String systemId() { + return systemId; + } + + @Override + public List threats() { + return threats; + } + + @Override + public Filterer filtered() { + return this::filteredGroup; + } + + private ProbabilisticThreatAwareSystem filteredGroup(final Predicate predicate) { + return new SimpleProbabilisticThreatAwareSystem(this.systemId, filteredItems(predicate)); + } + + private List filteredItems(final Predicate predicate) { + return this.threats.stream() + .filter(predicate) + .collect(Collectors.toList()); + } +} +``` + +Now let's see the full example in action showing how the filterer pattern works in practice. + +```java +@Slf4j +public class App { + + public static void main(String[] args) { + filteringSimpleThreats(); + filteringSimpleProbableThreats(); + } + + private static void filteringSimpleProbableThreats() { + LOGGER.info("### Filtering ProbabilisticThreatAwareSystem by probability ###"); + + var trojanArcBomb = new SimpleProbableThreat("Trojan-ArcBomb", 1, ThreatType.TROJAN, 0.99); + var rootkit = new SimpleProbableThreat("Rootkit-Kernel", 2, ThreatType.ROOTKIT, 0.8); + + List probableThreats = List.of(trojanArcBomb, rootkit); + + var probabilisticThreatAwareSystem = + new SimpleProbabilisticThreatAwareSystem("Sys-1", probableThreats); + + LOGGER.info("Filtering ProbabilisticThreatAwareSystem. Initial : " + + probabilisticThreatAwareSystem); + + //Filtering using filterer + var filteredThreatAwareSystem = probabilisticThreatAwareSystem.filtered() + .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); + + LOGGER.info("Filtered by probability = 0.99 : " + filteredThreatAwareSystem); + } + + private static void filteringSimpleThreats() { + LOGGER.info("### Filtering ThreatAwareSystem by ThreatType ###"); + + var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit"); + var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan"); + List threats = List.of(rootkit, trojan); + + var threatAwareSystem = new SimpleThreatAwareSystem("Sys-1", threats); + + LOGGER.info("Filtering ThreatAwareSystem. Initial : " + threatAwareSystem); + + //Filtering using Filterer + var rootkitThreatAwareSystem = threatAwareSystem.filtered() + .by(threat -> threat.type() == ThreatType.ROOTKIT); + + LOGGER.info("Filtered by threatType = ROOTKIT : " + rootkitThreatAwareSystem); + } +} +``` + +Running the example produces the following console output. + +``` +08:33:23.568 [main] INFO com.iluwatar.filterer.App -- ### Filtering ThreatAwareSystem by ThreatType ### +08:33:23.574 [main] INFO com.iluwatar.filterer.App -- Filtering ThreatAwareSystem. Initial : SimpleThreatAwareSystem(systemId=Sys-1, issues=[SimpleThreat(threatType=ROOTKIT, id=1, name=Simple-Rootkit), SimpleThreat(threatType=TROJAN, id=2, name=Simple-Trojan)]) +08:33:23.576 [main] INFO com.iluwatar.filterer.App -- Filtered by threatType = ROOTKIT : SimpleThreatAwareSystem(systemId=Sys-1, issues=[SimpleThreat(threatType=ROOTKIT, id=1, name=Simple-Rootkit)]) +08:33:23.576 [main] INFO com.iluwatar.filterer.App -- ### Filtering ProbabilisticThreatAwareSystem by probability ### +08:33:23.581 [main] INFO com.iluwatar.filterer.App -- Filtering ProbabilisticThreatAwareSystem. Initial : SimpleProbabilisticThreatAwareSystem(systemId=Sys-1, threats=[SimpleProbableThreat{probability=0.99} SimpleThreat(threatType=TROJAN, id=1, name=Trojan-ArcBomb), SimpleProbableThreat{probability=0.8} SimpleThreat(threatType=ROOTKIT, id=2, name=Rootkit-Kernel)]) +08:33:23.581 [main] INFO com.iluwatar.filterer.App -- Filtered by probability = 0.99 : SimpleProbabilisticThreatAwareSystem(systemId=Sys-1, threats=[SimpleProbableThreat{probability=0.99} SimpleThreat(threatType=TROJAN, id=1, name=Trojan-ArcBomb)]) +``` + +## When to Use the Filterer Pattern in Java + +* Use the Filterer pattern when dynamic and flexible filtering of a collection of objects is needed. +* This Java design pattern is ideal for applications where filtering logic frequently changes or requires combination in various ways. +* Ideal for scenarios requiring separation of filtering logic from the core business logic. + +## Filterer Pattern Java Tutorials + +* [Filterer Pattern (Tomasz Linkowski)](https://blog.tlinkowski.pl/2018/filterer-pattern/) +* [Filterer Pattern in 10 Steps (Java Code Geeks)](https://www.javacodegeeks.com/2019/02/filterer-pattern-10-steps.html) + +## Real-World Applications of Filterer Pattern in Java + +* Stream processing libraries in Java, such as Apache Kafka Streams, utilize this pattern to build complex data processing pipelines. +* Image processing software often uses filters to apply effects or transformations to images sequentially. + +## Benefits and Trade-offs of Filterer Pattern + +Benefits: + +* Increases flexibility by allowing different filters to be added or reorganized without affecting other parts of the system. +* Enhances testability, as filters can be tested independently. +* Promotes loose coupling between the stages of data processing. + +Trade-offs: + +* Potential performance overhead from continuous data passing between filters. +* Complexity can increase with the number of filters, potentially affecting maintainability. + +## Related Java Design Patterns + +* [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Filters can be seen as a specialized form of the Chain of Responsibility, where each filter decides if and how to process the input data and whether to pass it along the chain. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar to Decorator in that both modify behavior dynamically; however, filters focus more on data transformation than on adding responsibilities. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3W8sn2W) +* [Kafka: The Definitive Guide: Real-Time Data and Stream Processing at Scale](https://amzn.to/49N3nRU) +* [Java Performance: The Definitive Guide](https://amzn.to/3vRW3qj) diff --git a/filterer/etc/filterer-flowchart.png b/filterer/etc/filterer-flowchart.png new file mode 100644 index 000000000000..7870f2e57e18 Binary files /dev/null and b/filterer/etc/filterer-flowchart.png differ diff --git a/filterer/etc/filterer.png b/filterer/etc/filterer.png new file mode 100644 index 000000000000..6a6eb059b92d Binary files /dev/null and b/filterer/etc/filterer.png differ diff --git a/filterer/etc/filterer.urm.puml b/filterer/etc/filterer.urm.puml new file mode 100644 index 000000000000..c0bb0b54d0ec --- /dev/null +++ b/filterer/etc/filterer.urm.puml @@ -0,0 +1,96 @@ +@startuml +package com.iluwatar.filterer.domain { + interface Filterer { + + by(Predicate) : G {abstract} + } +} +package com.iluwatar.filterer { + class App { + - LOGGER : Logger {static} + + App() + - filteringSimpleProbableThreats() {static} + - filteringSimpleThreats() {static} + + main(args : String[]) {static} + } +} +package com.iluwatar.filterer.threat { + interface ProbabilisticThreatAwareSystem { + + filtered() : Filterer {abstract} + + threats() : List {abstract} + } + interface ProbableThreat { + + probability() : double {abstract} + } + class SimpleProbabilisticThreatAwareSystem { + - systemId : String + - threats : ImmutableList + + SimpleProbabilisticThreatAwareSystem(systemId : String, threats : List) + + equals(o : Object) : boolean + + filtered() : Filterer + - filteredGroup(predicate : Predicate) : ProbabilisticThreatAwareSystem + - filteredItems(predicate : Predicate) : List + + hashCode() : int + + systemId() : String + + threats() : List + + toString() : String + } + class SimpleProbableThreat { + - probability : double + + SimpleProbableThreat(name : String, id : int, threatType : ThreatType, probability : double) + + equals(o : Object) : boolean + + hashCode() : int + + probability() : double + + toString() : String + } + class SimpleThreat { + - id : int + - name : String + - threatType : ThreatType + + SimpleThreat(threatType : ThreatType, id : int, name : String) + + id() : int + + name() : String + + toString() : String + + type() : ThreatType + } + class SimpleThreatAwareSystem { + - issues : ImmutableList + - systemId : String + + SimpleThreatAwareSystem(systemId : String, issues : List) + + equals(o : Object) : boolean + + filtered() : Filterer + - filteredGroup(predicate : Predicate) : ThreatAwareSystem + - filteredItems(predicate : Predicate) : List + + hashCode() : int + + systemId() : String + + threats() : List + + toString() : String + } + interface Threat { + + id() : int {abstract} + + name() : String {abstract} + + type() : ThreatType {abstract} + } + interface ThreatAwareSystem { + + filtered() : Filterer {abstract} + + systemId() : String {abstract} + + threats() : List {abstract} + } + enum ThreatType { + + ROOTKIT {static} + + TROJAN {static} + + WORM {static} + + valueOf(name : String) : ThreatType {static} + + values() : ThreatType[] {static} + } +} +SimpleThreatAwareSystem --> "-issues" Threat +SimpleThreat --> "-threatType" ThreatType +SimpleProbabilisticThreatAwareSystem --> "-threats" ProbableThreat +ProbabilisticThreatAwareSystem --|> ThreatAwareSystem +ProbableThreat --|> Threat +SimpleProbabilisticThreatAwareSystem ..|> ProbabilisticThreatAwareSystem +SimpleProbableThreat ..|> ProbableThreat +SimpleProbableThreat --|> SimpleThreat +SimpleThreat ..|> Threat +SimpleThreatAwareSystem ..|> ThreatAwareSystem +@enduml \ No newline at end of file diff --git a/filterer/pom.xml b/filterer/pom.xml new file mode 100644 index 000000000000..a0d438394cb5 --- /dev/null +++ b/filterer/pom.xml @@ -0,0 +1,75 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + filterer + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.filterer.App + + + + + + + + + diff --git a/filterer/src/main/java/com/iluwatar/filterer/App.java b/filterer/src/main/java/com/iluwatar/filterer/App.java new file mode 100644 index 000000000000..c64dce891fb6 --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/App.java @@ -0,0 +1,106 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer; + +import com.iluwatar.filterer.threat.ProbableThreat; +import com.iluwatar.filterer.threat.SimpleProbabilisticThreatAwareSystem; +import com.iluwatar.filterer.threat.SimpleProbableThreat; +import com.iluwatar.filterer.threat.SimpleThreat; +import com.iluwatar.filterer.threat.SimpleThreatAwareSystem; +import com.iluwatar.filterer.threat.Threat; +import com.iluwatar.filterer.threat.ThreatAwareSystem; +import com.iluwatar.filterer.threat.ThreatType; +import java.util.List; +import java.util.function.Predicate; +import lombok.extern.slf4j.Slf4j; + +/** + * This demo class represent how {@link com.iluwatar.filterer.domain.Filterer} pattern is used to + * filter container-like objects to return filtered versions of themselves. The container like + * objects are systems that are aware of threats that they can be vulnerable to. We would like to + * have a way to create copy of different system objects but with filtered threats. The thing is to + * keep it simple if we add new subtype of {@link Threat} (for example {@link ProbableThreat}) - we + * still need to be able to filter by its properties. + */ +@Slf4j +public class App { + + public static void main(String[] args) { + filteringSimpleThreats(); + filteringSimpleProbableThreats(); + } + + /** + * Demonstrates how to filter {@link com.iluwatar.filterer.threat.ProbabilisticThreatAwareSystem} + * based on probability property. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)} + * method is able to use {@link com.iluwatar.filterer.threat.ProbableThreat} as predicate + * argument. + */ + private static void filteringSimpleProbableThreats() { + LOGGER.info("### Filtering ProbabilisticThreatAwareSystem by probability ###"); + + var trojanArcBomb = new SimpleProbableThreat("Trojan-ArcBomb", 1, ThreatType.TROJAN, 0.99); + var rootkit = new SimpleProbableThreat("Rootkit-Kernel", 2, ThreatType.ROOTKIT, 0.8); + + List probableThreats = List.of(trojanArcBomb, rootkit); + + var probabilisticThreatAwareSystem = + new SimpleProbabilisticThreatAwareSystem("Sys-1", probableThreats); + + LOGGER.info( + "Filtering ProbabilisticThreatAwareSystem. Initial : " + probabilisticThreatAwareSystem); + + // Filtering using filterer + var filteredThreatAwareSystem = + probabilisticThreatAwareSystem + .filtered() + .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); + + LOGGER.info("Filtered by probability = 0.99 : " + filteredThreatAwareSystem); + } + + /** + * Demonstrates how to filter {@link ThreatAwareSystem} based on startingOffset property of {@link + * SimpleThreat}. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)} method is able + * to use {@link Threat} as predicate argument. + */ + private static void filteringSimpleThreats() { + LOGGER.info("### Filtering ThreatAwareSystem by ThreatType ###"); + + var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit"); + var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan"); + List threats = List.of(rootkit, trojan); + + var threatAwareSystem = new SimpleThreatAwareSystem("Sys-1", threats); + + LOGGER.info("Filtering ThreatAwareSystem. Initial : " + threatAwareSystem); + + // Filtering using Filterer + var rootkitThreatAwareSystem = + threatAwareSystem.filtered().by(threat -> threat.type() == ThreatType.ROOTKIT); + + LOGGER.info("Filtered by threatType = ROOTKIT : " + rootkitThreatAwareSystem); + } +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java b/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java new file mode 100644 index 000000000000..58da1a7e563b --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.domain; + +import java.util.function.Predicate; + +/** + * Filterer helper interface. + * + * @param type of the container-like object. + * @param type of the elements contained within this container-like object. + */ +@FunctionalInterface +public interface Filterer { + G by(Predicate predicate); +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java new file mode 100644 index 000000000000..a63728d74360 --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +import com.iluwatar.filterer.domain.Filterer; +import java.util.List; + +/** Represents system that is aware of its threats with given probability of their occurrence. */ +public interface ProbabilisticThreatAwareSystem extends ThreatAwareSystem { + + /** + * {@inheritDoc} + * + * @return {@link ProbableThreat} + */ + @Override + List threats(); + + /** + * {@inheritDoc} + * + * @return {@link Filterer} + */ + @Override + Filterer filtered(); +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java new file mode 100644 index 000000000000..8562136b50dd --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java @@ -0,0 +1,35 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +/** Represents threat that might be a threat with given probability. */ +public interface ProbableThreat extends Threat { + /** + * Returns probability of occurrence of given threat. + * + * @return probability of occurrence of given threat. + */ + double probability(); +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java new file mode 100644 index 000000000000..0584a031be7f --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java @@ -0,0 +1,69 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +import com.iluwatar.filterer.domain.Filterer; +import java.util.List; +import java.util.function.Predicate; +import lombok.EqualsAndHashCode; +import lombok.RequiredArgsConstructor; +import lombok.ToString; + +/** {@inheritDoc} */ +@ToString +@EqualsAndHashCode +@RequiredArgsConstructor +public class SimpleProbabilisticThreatAwareSystem implements ProbabilisticThreatAwareSystem { + + private final String systemId; + private final List threats; + + /** {@inheritDoc} */ + @Override + public String systemId() { + return systemId; + } + + /** {@inheritDoc} */ + @Override + public List threats() { + return threats; + } + + /** {@inheritDoc} */ + @Override + public Filterer filtered() { + return this::filteredGroup; + } + + private ProbabilisticThreatAwareSystem filteredGroup( + final Predicate predicate) { + return new SimpleProbabilisticThreatAwareSystem(this.systemId, filteredItems(predicate)); + } + + private List filteredItems(final Predicate predicate) { + return this.threats.stream().filter(predicate).toList(); + } +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java new file mode 100644 index 000000000000..044e02471755 --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +import lombok.EqualsAndHashCode; + +/** {@inheritDoc} */ +@EqualsAndHashCode(callSuper = false) +public class SimpleProbableThreat extends SimpleThreat implements ProbableThreat { + + private final double probability; + + public SimpleProbableThreat( + final String name, final int id, final ThreatType threatType, final double probability) { + super(threatType, id, name); + this.probability = probability; + } + + /** {@inheritDoc} */ + @Override + public double probability() { + return probability; + } + + @Override + public String toString() { + return "SimpleProbableThreat{" + "probability=" + probability + "} " + super.toString(); + } +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java new file mode 100644 index 000000000000..034c6970be48 --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java @@ -0,0 +1,58 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +import lombok.EqualsAndHashCode; +import lombok.RequiredArgsConstructor; +import lombok.ToString; + +/** Represents a simple threat. */ +@ToString +@EqualsAndHashCode +@RequiredArgsConstructor +public class SimpleThreat implements Threat { + + private final ThreatType threatType; + private final int id; + private final String name; + + /** {@inheritDoc} */ + @Override + public String name() { + return name; + } + + /** {@inheritDoc} */ + @Override + public int id() { + return id; + } + + /** {@inheritDoc} */ + @Override + public ThreatType type() { + return threatType; + } +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java new file mode 100644 index 000000000000..c547afe8f5df --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java @@ -0,0 +1,69 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +import com.iluwatar.filterer.domain.Filterer; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; +import lombok.EqualsAndHashCode; +import lombok.RequiredArgsConstructor; +import lombok.ToString; + +/** {@inheritDoc} */ +@ToString +@EqualsAndHashCode +@RequiredArgsConstructor +public class SimpleThreatAwareSystem implements ThreatAwareSystem { + + private final String systemId; + private final List issues; + + /** {@inheritDoc} */ + @Override + public String systemId() { + return systemId; + } + + /** {@inheritDoc} */ + @Override + public List threats() { + return new ArrayList<>(issues); + } + + /** {@inheritDoc} */ + @Override + public Filterer filtered() { + return this::filteredGroup; + } + + private ThreatAwareSystem filteredGroup(Predicate predicate) { + return new SimpleThreatAwareSystem(this.systemId, filteredItems(predicate)); + } + + private List filteredItems(Predicate predicate) { + return this.issues.stream().filter(predicate).toList(); + } +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java new file mode 100644 index 000000000000..1a138956d9cd --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java @@ -0,0 +1,49 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +/** Represents a threat that can be detected in given system. */ +public interface Threat { + /** + * Returns name of the threat. + * + * @return value representing name of the threat. + */ + String name(); + + /** + * Returns unique id of the threat. + * + * @return value representing threat id. + */ + int id(); + + /** + * Returns threat type. + * + * @return {@link ThreatType} + */ + ThreatType type(); +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java new file mode 100644 index 000000000000..49ef8560fb68 --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +import com.iluwatar.filterer.domain.Filterer; +import java.util.List; + +/** Represents system that is aware of threats that are present in it. */ +public interface ThreatAwareSystem { + + /** + * Returns the system id. + * + * @return system id. + */ + String systemId(); + + /** + * Returns list of threats for this system. + * + * @return list of threats for this system. + */ + List threats(); + + /** + * Returns the instance of {@link Filterer} helper interface that allows to covariantly specify + * lower bound for predicate that we want to filter by. + * + * @return an instance of {@link Filterer} helper interface. + */ + Filterer, T> filtered(); +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java new file mode 100644 index 000000000000..30dcaefa18b1 --- /dev/null +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +/** Enum class representing Threat types. */ +public enum ThreatType { + TROJAN, + WORM, + ROOTKIT +} diff --git a/filterer/src/test/java/com/iluwatar/filterer/AppTest.java b/filterer/src/test/java/com/iluwatar/filterer/AppTest.java new file mode 100644 index 000000000000..a35f03ea5cf0 --- /dev/null +++ b/filterer/src/test/java/com/iluwatar/filterer/AppTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void shouldLaunchApp() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java new file mode 100644 index 000000000000..3705009f170f --- /dev/null +++ b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class SimpleProbabilisticThreatAwareSystemTest { + + @Test + void shouldFilterByProbability() { + // given + var trojan = new SimpleProbableThreat("Troyan-ArcBomb", 1, ThreatType.TROJAN, 0.99); + var rootkit = new SimpleProbableThreat("Rootkit-System", 2, ThreatType.ROOTKIT, 0.8); + List probableThreats = List.of(trojan, rootkit); + + var simpleProbabilisticThreatAwareSystem = + new SimpleProbabilisticThreatAwareSystem("System-1", probableThreats); + + // when + var filtered = + simpleProbabilisticThreatAwareSystem + .filtered() + .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); + + // then + assertEquals(filtered.threats().size(), 1); + assertEquals(filtered.threats().get(0), trojan); + } +} diff --git a/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java new file mode 100644 index 000000000000..d763edbf3e1c --- /dev/null +++ b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.filterer.threat; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class SimpleThreatAwareSystemTest { + @Test + void shouldFilterByThreatType() { + // given + var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit"); + var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan"); + List threats = List.of(rootkit, trojan); + + var threatAwareSystem = new SimpleThreatAwareSystem("System-1", threats); + + // when + var rootkitThreatAwareSystem = + threatAwareSystem.filtered().by(threat -> threat.type() == ThreatType.ROOTKIT); + + // then + assertEquals(rootkitThreatAwareSystem.threats().size(), 1); + assertEquals(rootkitThreatAwareSystem.threats().get(0), rootkit); + } +} diff --git a/fluent-interface/README.md b/fluent-interface/README.md new file mode 100644 index 000000000000..3ae18f69ac13 --- /dev/null +++ b/fluent-interface/README.md @@ -0,0 +1,205 @@ +--- +title: "Fluent Interface Pattern in Java: Enhancing Code Expressiveness with Fluent APIs" +shortTitle: Fluent Interface +description: "Learn how to implement the Fluent Interface design pattern in Java. Explore method chaining and Fluent API with practical examples and improve your code readability and maintainability." +category: Behavioral +language: en +tag: + - API design + - Code simplification + - Decoupling + - Object composition + - Reactive +--- + +## Also known as + +* Fluent API +* Method Chaining + +## Intent of Fluent Interface Design Pattern + +The primary goal of the Fluent Interface pattern is to provide an easily readable and flowing API by chaining method calls, often referred to as method chaining. This approach is ideal for building complex objects step-by-step and improving the overall developer experience. + +## Detailed Explanation of Fluent Interface Pattern with Real-World Examples + +Real-world example + +> Imagine you are at a coffee shop customizing your order step-by-step. This approach is similar to how the Fluent Interface design pattern works in Java, allowing you to chain method calls to build and configure objects sequentially. Instead of telling the barista everything at once, you specify each customization step-by-step in a way that flows naturally. For instance, you might say, "I'd like a large coffee, add two shots of espresso, no sugar, and top it with almond milk." This approach is similar to the Fluent Interface design pattern, where you chain together method calls to configure an object in a readable and intuitive manner. Just as you specify each part of your coffee order sequentially, a Fluent Interface allows you to chain method calls to build and configure objects step-by-step in code. + +In plain words + +> Fluent Interface pattern provides easily readable flowing interface to code. + +Wikipedia says + +> In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). + +Sequence diagram + +![Fluent Interface sequence diagram](./etc/fluent-interface-sequence-diagram.png) + +## Programmatic Example of Fluent Interface Pattern in Java + +We need to select numbers based on different criteria from the list. It's a great chance to utilize fluent interface pattern to provide readable easy-to-use developer experience. + +In this example two implementations of a `FluentIterable` interface are given. + +```java +public interface FluentIterable extends Iterable { + + FluentIterable filter(Predicate predicate); + + Optional first(); + + FluentIterable first(int count); + + Optional last(); + + FluentIterable last(int count); + + FluentIterable map(Function function); + + List asList(); + + static List copyToList(Iterable iterable) { + var copy = new ArrayList(); + iterable.forEach(copy::add); + return copy; + } +} +``` + +The `SimpleFluentIterable` evaluates eagerly and would be too costly for real world applications. + +```java +public class SimpleFluentIterable implements FluentIterable { + // ... +} +``` + +The `LazyFluentIterable` is evaluated on termination. + +```java +public class LazyFluentIterable implements FluentIterable { + // ... +} +``` + +Their usage is demonstrated with a simple number list that is filtered, transformed and collected. The result is printed afterward. + +```java +public static void main(String[] args) { + + var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68); + + prettyPrint("The initial list contains: ", integerList); + + var firstFiveNegatives = SimpleFluentIterable + .fromCopyOf(integerList) + .filter(negatives()) + .first(3) + .asList(); + prettyPrint("The first three negative values are: ", firstFiveNegatives); + + + var lastTwoPositives = SimpleFluentIterable + .fromCopyOf(integerList) + .filter(positives()) + .last(2) + .asList(); + prettyPrint("The last two positive values are: ", lastTwoPositives); + + SimpleFluentIterable + .fromCopyOf(integerList) + .filter(number -> number % 2 == 0) + .first() + .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber)); + + + var transformedList = SimpleFluentIterable + .fromCopyOf(integerList) + .filter(negatives()) + .map(transformToString()) + .asList(); + prettyPrint("A string-mapped list of negative numbers contains: ", transformedList); + + + var lastTwoOfFirstFourStringMapped = LazyFluentIterable + .from(integerList) + .filter(positives()) + .first(4) + .last(2) + .map(number -> "String[" + number + "]") + .asList(); + prettyPrint("The lazy list contains the last two of the first four positive numbers " + + "mapped to Strings: ", lastTwoOfFirstFourStringMapped); + + LazyFluentIterable + .from(integerList) + .filter(negatives()) + .first(2) + .last() + .ifPresent(number -> LOGGER.info("Last amongst first two negatives: {}", number)); +} +``` + +Program output: + +``` +08:50:08.260 [main] INFO com.iluwatar.fluentinterface.app.App -- The initial list contains: 1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68. +08:50:08.265 [main] INFO com.iluwatar.fluentinterface.app.App -- The first three negative values are: -61, -22, -87. +08:50:08.265 [main] INFO com.iluwatar.fluentinterface.app.App -- The last two positive values are: 23, 2. +08:50:08.266 [main] INFO com.iluwatar.fluentinterface.app.App -- The first even number is: 14 +08:50:08.267 [main] INFO com.iluwatar.fluentinterface.app.App -- A string-mapped list of negative numbers contains: String[-61], String[-22], String[-87], String[-82], String[-98], String[-68]. +08:50:08.270 [main] INFO com.iluwatar.fluentinterface.app.App -- The lazy list contains the last two of the first four positive numbers mapped to Strings: String[18], String[6]. +08:50:08.270 [main] INFO com.iluwatar.fluentinterface.app.App -- Last amongst first two negatives: -22 +``` + +## When to Use the Fluent Interface Pattern in Java + +Use the Fluent Interface Pattern in Java when + +* Designing APIs that are heavily used and where readability of client code is of high importance. +* Building complex objects step-by-step, and there is a need to make the code more intuitive and less error-prone. +* Enhancing code clarity and reducing the boilerplate code, especially in configurations and object-building scenarios. + +## Fluent Interface Pattern Java Tutorials + +* [An Approach to Internal Domain-Specific Languages in Java (InfoQ)](http://www.infoq.com/articles/internal-dsls-java) + +## Real-World Applications of Fluent Interface Pattern in Java + +* [Java 8 Stream API](http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html) +* [Google Guava FluentIterable](https://github.com/google/guava/wiki/FunctionalExplained) +* [JOOQ](http://www.jooq.org/doc/3.0/manual/getting-started/use-cases/jooq-as-a-standalone-sql-builder/) +* [Mockito](http://mockito.org/) +* [Java Hamcrest](http://code.google.com/p/hamcrest/wiki/Tutorial) +* Builders in libraries like Apache Camel for integration workflows. + +## Benefits and Trade-offs of Fluent Interface Pattern + +Benefits: + +* Adopting the Fluent Interface pattern in your Java projects can significantly enhance code readability and maintainability. +* Encourages building immutable objects since methods typically return new instances. +* Reduces the need for variables as the context is maintained in the chain. + +Trade-offs: + +* Can lead to less intuitive code for those unfamiliar with the pattern. +* Debugging can be challenging due to the chaining of method calls. +* Overuse can lead to complex and hard-to-maintain code structures. + +## Related Java Design Patterns + +* [Builder](https://java-design-patterns.com/patterns/builder/): Often implemented using a Fluent Interface to construct objects step-by-step. The Builder Pattern focuses on constructing complex objects, while Fluent Interface emphasizes the method chaining mechanism. +* [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Fluent Interfaces can be seen as a specific utilization of the Chain of Responsibility, where each method in the chain handles a part of the task and then delegates to the next method. + +## References and Credits + +* [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3UrXkh2) +* [Domain Specific Languages](https://amzn.to/3R1UYDA) +* [Effective Java](https://amzn.to/4d4azvL) +* [Java Design Pattern Essentials](https://amzn.to/44bs6hG) +* [Fluent Interface (Martin Fowler)](http://www.martinfowler.com/bliki/FluentInterface.html) diff --git a/fluent-interface/etc/fluent-interface-sequence-diagram.png b/fluent-interface/etc/fluent-interface-sequence-diagram.png new file mode 100644 index 000000000000..2c72f5aa54b7 Binary files /dev/null and b/fluent-interface/etc/fluent-interface-sequence-diagram.png differ diff --git a/fluent-interface/etc/fluent-interface.urm.puml b/fluent-interface/etc/fluent-interface.urm.puml new file mode 100644 index 000000000000..d343a478bff0 --- /dev/null +++ b/fluent-interface/etc/fluent-interface.urm.puml @@ -0,0 +1,72 @@ +@startuml +package com.iluwatar.fluentinterface.fluentiterable.simple { + class SimpleFluentIterable { + - iterable : Iterable + + SimpleFluentIterable(iterable : Iterable) + + asList() : List + + filter(predicate : Predicate) : FluentIterable + + first() : Optional + + first(count : int) : FluentIterable + + forEach(action : Consumer) + + from(iterable : Iterable) : FluentIterable {static} + + fromCopyOf(iterable : Iterable) : FluentIterable {static} + + getRemainingElementsCount() : int + + iterator() : Iterator + + last() : Optional + + last(count : int) : FluentIterable + + map(function : Function) : FluentIterable + + spliterator() : Spliterator + + toList(iterator : Iterator) : List {static} + } +} +package com.iluwatar.fluentinterface.app { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + - negatives() : Predicate {static} + - positives() : Predicate {static} + - prettyPrint(delimiter : String, prefix : String, iterable : Iterable) {static} + - prettyPrint(prefix : String, iterable : Iterable) {static} + - transformToString() : Function {static} + } +} +package com.iluwatar.fluentinterface.fluentiterable.lazy { + abstract class DecoratingIterator { + # fromIterator : Iterator + - next : E + + DecoratingIterator(fromIterator : Iterator) + + computeNext() : E {abstract} + + hasNext() : boolean + + next() : E + } + class LazyFluentIterable { + - iterable : Iterable + # LazyFluentIterable() + + LazyFluentIterable(iterable : Iterable) + + asList() : List + + filter(predicate : Predicate) : FluentIterable + + first() : Optional + + first(count : int) : FluentIterable + + from(iterable : Iterable) : FluentIterable {static} + + iterator() : Iterator + + last() : Optional + + last(count : int) : FluentIterable + + map(function : Function) : FluentIterable + } +} +package com.iluwatar.fluentinterface.fluentiterable { + interface FluentIterable { + + asList() : List {abstract} + + copyToList(iterable : Iterable) : List {static} + + filter(Predicate) : FluentIterable {abstract} + + first() : Optional {abstract} + + first(int) : FluentIterable {abstract} + + last() : Optional {abstract} + + last(int) : FluentIterable {abstract} + + map(Function) : FluentIterable {abstract} + } +} +LazyFluentIterable ..|> FluentIterable +SimpleFluentIterable ..|> FluentIterable +@enduml \ No newline at end of file diff --git a/fluentinterface/etc/fluentinterface.png b/fluent-interface/etc/fluentinterface.png similarity index 100% rename from fluentinterface/etc/fluentinterface.png rename to fluent-interface/etc/fluentinterface.png diff --git a/fluentinterface/etc/fluentinterface.ucls b/fluent-interface/etc/fluentinterface.ucls similarity index 100% rename from fluentinterface/etc/fluentinterface.ucls rename to fluent-interface/etc/fluentinterface.ucls diff --git a/fluent-interface/etc/fluentinterface.urm.puml b/fluent-interface/etc/fluentinterface.urm.puml new file mode 100644 index 000000000000..ef71a0f4bace --- /dev/null +++ b/fluent-interface/etc/fluentinterface.urm.puml @@ -0,0 +1,72 @@ +@startuml +package com.iluwatar.fluentinterface.fluentiterable.simple { + class SimpleFluentIterable { + - iterable : Iterable + # SimpleFluentIterable(iterable : Iterable) + + asList() : List + + filter(predicate : Predicate) : FluentIterable + + first() : Optional + + first(count : int) : FluentIterable + + forEach(action : Consumer) + + from(iterable : Iterable) : FluentIterable {static} + + fromCopyOf(iterable : Iterable) : FluentIterable {static} + + getRemainingElementsCount() : int + + iterator() : Iterator + + last() : Optional + + last(count : int) : FluentIterable + + map(function : Function) : FluentIterable + + spliterator() : Spliterator + + toList(iterator : Iterator) : List {static} + } +} +package com.iluwatar.fluentinterface.app { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + - negatives() : Predicate {static} + - positives() : Predicate {static} + - prettyPrint(delimiter : String, prefix : String, iterable : Iterable) {static} + - prettyPrint(prefix : String, iterable : Iterable) {static} + - transformToString() : Function {static} + } +} +package com.iluwatar.fluentinterface.fluentiterable.lazy { + abstract class DecoratingIterator { + # fromIterator : Iterator + - next : E + + DecoratingIterator(fromIterator : Iterator) + + computeNext() : E {abstract} + + hasNext() : boolean + + next() : E + } + class LazyFluentIterable { + - iterable : Iterable + # LazyFluentIterable() + # LazyFluentIterable(iterable : Iterable) + + asList() : List + + filter(predicate : Predicate) : FluentIterable + + first() : Optional + + first(count : int) : FluentIterable + + from(iterable : Iterable) : FluentIterable {static} + + iterator() : Iterator + + last() : Optional + + last(count : int) : FluentIterable + + map(function : Function) : FluentIterable + } +} +package com.iluwatar.fluentinterface.fluentiterable { + interface FluentIterable { + + asList() : List {abstract} + + copyToList(iterable : Iterable) : List {static} + + filter(Predicate) : FluentIterable {abstract} + + first() : Optional {abstract} + + first(int) : FluentIterable {abstract} + + last() : Optional {abstract} + + last(int) : FluentIterable {abstract} + + map(Function) : FluentIterable {abstract} + } +} +LazyFluentIterable ..|> FluentIterable +SimpleFluentIterable ..|> FluentIterable +@enduml \ No newline at end of file diff --git a/fluent-interface/pom.xml b/fluent-interface/pom.xml new file mode 100644 index 000000000000..005fa9f7b831 --- /dev/null +++ b/fluent-interface/pom.xml @@ -0,0 +1,75 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + fluent-interface + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.fluentinterface.app.App + + + + + + + + + diff --git a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/app/App.java b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/app/App.java new file mode 100644 index 000000000000..a36bef68b645 --- /dev/null +++ b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/app/App.java @@ -0,0 +1,117 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.fluentinterface.app; + +import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; +import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable; +import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable; +import java.util.List; +import java.util.StringJoiner; +import java.util.function.Function; +import java.util.function.Predicate; +import lombok.extern.slf4j.Slf4j; + +/** + * The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API. + * Those interfaces tend to mimic domain specific languages, so they can nearly be read as human + * languages. + * + *

    In this example two implementations of a {@link FluentIterable} interface are given. The + * {@link SimpleFluentIterable} evaluates eagerly and would be too costly for real world + * applications. The {@link LazyFluentIterable} is evaluated on termination. Their usage is + * demonstrated with a simple number list that is filtered, transformed and collected. The result is + * printed afterward. + */ +@Slf4j +public class App { + + /** Program entry point. */ + public static void main(String[] args) { + + var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68); + + prettyPrint("The initial list contains: ", integerList); + + var firstFiveNegatives = + SimpleFluentIterable.fromCopyOf(integerList).filter(negatives()).first(3).asList(); + prettyPrint("The first three negative values are: ", firstFiveNegatives); + + var lastTwoPositives = + SimpleFluentIterable.fromCopyOf(integerList).filter(positives()).last(2).asList(); + prettyPrint("The last two positive values are: ", lastTwoPositives); + + SimpleFluentIterable.fromCopyOf(integerList) + .filter(number -> number % 2 == 0) + .first() + .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber)); + + var transformedList = + SimpleFluentIterable.fromCopyOf(integerList) + .filter(negatives()) + .map(transformToString()) + .asList(); + prettyPrint("A string-mapped list of negative numbers contains: ", transformedList); + + var lastTwoOfFirstFourStringMapped = + LazyFluentIterable.from(integerList) + .filter(positives()) + .first(4) + .last(2) + .map(number -> "String[" + number + "]") + .asList(); + prettyPrint( + "The lazy list contains the last two of the first four positive numbers " + + "mapped to Strings: ", + lastTwoOfFirstFourStringMapped); + + LazyFluentIterable.from(integerList) + .filter(negatives()) + .first(2) + .last() + .ifPresent(number -> LOGGER.info("Last amongst first two negatives: {}", number)); + } + + private static Function transformToString() { + return integer -> "String[" + integer + "]"; + } + + private static Predicate negatives() { + return integer -> integer < 0; + } + + private static Predicate positives() { + return integer -> integer > 0; + } + + private static void prettyPrint(String prefix, Iterable iterable) { + prettyPrint(", ", prefix, iterable); + } + + private static void prettyPrint(String delimiter, String prefix, Iterable iterable) { + var joiner = new StringJoiner(delimiter, prefix, "."); + iterable.forEach(e -> joiner.add(e.toString())); + LOGGER.info(joiner.toString()); + } +} diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java similarity index 91% rename from fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java rename to fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java index 693585962173..2ab128afa633 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java +++ b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,7 +25,6 @@ package com.iluwatar.fluentinterface.fluentiterable; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -33,7 +34,7 @@ * The FluentIterable is a more convenient implementation of the common iterable interface based on * the fluent interface design pattern. This interface defines common operations, but doesn't aim to * be complete. It was inspired by Guava's com.google.common.collect.FluentIterable. - * + * * @param is the class of objects the iterable contains */ public interface FluentIterable extends Iterable { @@ -41,9 +42,9 @@ public interface FluentIterable extends Iterable { /** * Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy * the predicate. - * + * * @param predicate the condition to test with for the filtering. If the test is negative, the - * tested object is removed by the iterator. + * tested object is removed by the iterator. * @return a filtered FluentIterable */ FluentIterable filter(Predicate predicate); @@ -51,35 +52,35 @@ public interface FluentIterable extends Iterable { /** * Returns an Optional containing the first element of this iterable if present, else returns * Optional.empty(). - * + * * @return the first element after the iteration is evaluated */ Optional first(); /** * Evaluates the iteration and leaves only the count first elements. - * + * * @return the first count elements as an Iterable */ FluentIterable first(int count); /** * Evaluates the iteration and returns the last element. This is a terminating operation. - * + * * @return the last element after the iteration is evaluated */ Optional last(); /** * Evaluates the iteration and leaves only the count last elements. - * + * * @return the last counts elements as an Iterable */ FluentIterable last(int count); /** * Transforms this FluentIterable into a new one containing objects of the type T. - * + * * @param function a function that transforms an instance of E into an instance of T * @param the target type of the transformation * @return a new FluentIterable of the new type @@ -88,24 +89,21 @@ public interface FluentIterable extends Iterable { /** * Returns the contents of this Iterable as a List. - * + * * @return a List representation of this Iterable */ List asList(); /** * Utility method that iterates over iterable and adds the contents to a list. - * + * * @param iterable the iterable to collect * @param the type of the objects to iterate * @return a list with all objects of the given iterator */ static List copyToList(Iterable iterable) { - List copy = new ArrayList<>(); - Iterator iterator = iterable.iterator(); - while (iterator.hasNext()) { - copy.add(iterator.next()); - } + var copy = new ArrayList(); + iterable.forEach(copy::add); return copy; } } diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java similarity index 89% rename from fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java rename to fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java index 389904bffc84..12a0304a8db2 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java +++ b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -27,6 +29,7 @@ /** * This class is used to realize LazyFluentIterables. It decorates a given iterator. Does not * support consecutive hasNext() calls. + * * @param Iterable Collection of Elements of Type E */ public abstract class DecoratingIterator implements Iterator { @@ -35,9 +38,7 @@ public abstract class DecoratingIterator implements Iterator { private E next; - /** - * Creates an iterator that decorates the given iterator. - */ + /** Creates an iterator that decorates the given iterator. */ public DecoratingIterator(Iterator fromIterator) { this.fromIterator = fromIterator; } @@ -63,7 +64,7 @@ public final E next() { if (next == null) { return fromIterator.next(); } else { - final E result = next; + final var result = next; next = null; return result; } diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java similarity index 79% rename from fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java rename to fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java index 1a4c88ed7c48..971ac9a02207 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java +++ b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,37 +24,27 @@ */ package com.iluwatar.fluentinterface.fluentiterable.lazy; +import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; - -import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; +import lombok.RequiredArgsConstructor; /** * This is a lazy implementation of the FluentIterable interface. It evaluates all chained * operations when a terminating operation is applied. - * + * * @param the type of the objects the iteration is about */ +@RequiredArgsConstructor public class LazyFluentIterable implements FluentIterable { private final Iterable iterable; - /** - * This constructor creates a new LazyFluentIterable. It wraps the given iterable. - * - * @param iterable the iterable this FluentIterable works on. - */ - protected LazyFluentIterable(Iterable iterable) { - this.iterable = iterable; - } - - /** - * This constructor can be used to implement anonymous subclasses of the LazyFluentIterable. - */ + /** This constructor can be used to implement anonymous subclasses of the LazyFluentIterable. */ protected LazyFluentIterable() { iterable = this; } @@ -60,21 +52,21 @@ protected LazyFluentIterable() { /** * Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy * the predicate. - * + * * @param predicate the condition to test with for the filtering. If the test is negative, the - * tested object is removed by the iterator. + * tested object is removed by the iterator. * @return a new FluentIterable object that decorates the source iterable */ @Override public FluentIterable filter(Predicate predicate) { - return new LazyFluentIterable() { + return new LazyFluentIterable<>() { @Override public Iterator iterator() { - return new DecoratingIterator(iterable.iterator()) { + return new DecoratingIterator<>(iterable.iterator()) { @Override public E computeNext() { while (fromIterator.hasNext()) { - E candidate = fromIterator.next(); + var candidate = fromIterator.next(); if (predicate.test(candidate)) { return candidate; } @@ -89,34 +81,34 @@ public E computeNext() { /** * Can be used to collect objects from the iteration. Is a terminating operation. - * + * * @return an Optional containing the first object of this Iterable */ @Override public Optional first() { - Iterator resultIterator = first(1).iterator(); + var resultIterator = first(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } /** * Can be used to collect objects from the iteration. - * + * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' first - * objects. + * objects. */ @Override public FluentIterable first(int count) { - return new LazyFluentIterable() { + return new LazyFluentIterable<>() { @Override public Iterator iterator() { - return new DecoratingIterator(iterable.iterator()) { + return new DecoratingIterator<>(iterable.iterator()) { int currentIndex; @Override public E computeNext() { if (currentIndex < count && fromIterator.hasNext()) { - E candidate = fromIterator.next(); + var candidate = fromIterator.next(); currentIndex++; return candidate; } @@ -129,12 +121,12 @@ public E computeNext() { /** * Can be used to collect objects from the iteration. Is a terminating operation. - * + * * @return an Optional containing the last object of this Iterable */ @Override public Optional last() { - Iterator resultIterator = last(1).iterator(); + var resultIterator = last(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } @@ -142,17 +134,17 @@ public Optional last() { * Can be used to collect objects from the Iterable. Is a terminating operation. This operation is * memory intensive, because the contents of this Iterable are collected into a List, when the * next object is requested. - * + * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' last - * objects + * objects */ @Override public FluentIterable last(int count) { - return new LazyFluentIterable() { + return new LazyFluentIterable<>() { @Override public Iterator iterator() { - return new DecoratingIterator(iterable.iterator()) { + return new DecoratingIterator<>(iterable.iterator()) { private int stopIndex; private int totalElementsCount; private List list; @@ -162,25 +154,20 @@ public Iterator iterator() { public E computeNext() { initialize(); - E candidate = null; while (currentIndex < stopIndex && fromIterator.hasNext()) { currentIndex++; fromIterator.next(); } if (currentIndex >= stopIndex && fromIterator.hasNext()) { - candidate = fromIterator.next(); + return fromIterator.next(); } - return candidate; + return null; } private void initialize() { if (list == null) { list = new ArrayList<>(); - Iterator newIterator = iterable.iterator(); - while (newIterator.hasNext()) { - list.add(newIterator.next()); - } - + iterable.forEach(list::add); totalElementsCount = list.size(); stopIndex = totalElementsCount - count; } @@ -192,18 +179,18 @@ private void initialize() { /** * Transforms this FluentIterable into a new one containing objects of the type T. - * + * * @param function a function that transforms an instance of E into an instance of T * @param the target type of the transformation * @return a new FluentIterable of the new type */ @Override public FluentIterable map(Function function) { - return new LazyFluentIterable() { + return new LazyFluentIterable<>() { @Override public Iterator iterator() { - return new DecoratingIterator(null) { - Iterator oldTypeIterator = iterable.iterator(); + return new DecoratingIterator<>(null) { + final Iterator oldTypeIterator = iterable.iterator(); @Override public T computeNext() { @@ -221,7 +208,7 @@ public T computeNext() { /** * Collects all remaining objects of this iteration into a list. - * + * * @return a list with all remaining objects of this iteration */ @Override @@ -231,7 +218,7 @@ public List asList() { @Override public Iterator iterator() { - return new DecoratingIterator(iterable.iterator()) { + return new DecoratingIterator<>(iterable.iterator()) { @Override public E computeNext() { return fromIterator.hasNext() ? fromIterator.next() : null; @@ -240,10 +227,11 @@ public E computeNext() { } /** + * Constructors FluentIterable from given iterable. + * * @return a FluentIterable from a given iterable. Calls the LazyFluentIterable constructor. */ - public static final FluentIterable from(Iterable iterable) { + public static FluentIterable from(Iterable iterable) { return new LazyFluentIterable<>(iterable); } - } diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java similarity index 79% rename from fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java rename to fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java index fde259f9b03c..a44cfb44cbfe 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java +++ b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,6 +24,7 @@ */ package com.iluwatar.fluentinterface.fluentiterable.simple; +import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -30,41 +33,32 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; - -import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; +import lombok.RequiredArgsConstructor; /** * This is a simple implementation of the FluentIterable interface. It evaluates all chained * operations eagerly. This implementation would be costly to be utilized in real applications. - * + * * @param the type of the objects the iteration is about */ +@RequiredArgsConstructor public class SimpleFluentIterable implements FluentIterable { private final Iterable iterable; - /** - * This constructor creates a copy of a given iterable's contents. - * - * @param iterable the iterable this interface copies to work on. - */ - protected SimpleFluentIterable(Iterable iterable) { - this.iterable = iterable; - } - /** * Filters the contents of Iterable using the given predicate, leaving only the ones which satisfy * the predicate. - * + * * @param predicate the condition to test with for the filtering. If the test is negative, the - * tested object is removed by the iterator. + * tested object is removed by the iterator. * @return the same FluentIterable with a filtered collection */ @Override public final FluentIterable filter(Predicate predicate) { - Iterator iterator = iterator(); + var iterator = iterator(); while (iterator.hasNext()) { - E nextElement = iterator.next(); + var nextElement = iterator.next(); if (!predicate.test(nextElement)) { iterator.remove(); } @@ -74,26 +68,26 @@ public final FluentIterable filter(Predicate predicate) { /** * Can be used to collect objects from the Iterable. Is a terminating operation. - * + * * @return an option of the first object of the Iterable */ @Override public final Optional first() { - Iterator resultIterator = first(1).iterator(); + var resultIterator = first(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); } /** * Can be used to collect objects from the Iterable. Is a terminating operation. - * + * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' first - * objects. + * objects. */ @Override public final FluentIterable first(int count) { - Iterator iterator = iterator(); - int currentCount = 0; + var iterator = iterator(); + var currentCount = 0; while (iterator.hasNext()) { iterator.next(); if (currentCount >= count) { @@ -106,12 +100,12 @@ public final FluentIterable first(int count) { /** * Can be used to collect objects from the Iterable. Is a terminating operation. - * + * * @return an option of the last object of the Iterable */ @Override public final Optional last() { - List list = last(1).asList(); + var list = last(1).asList(); if (list.isEmpty()) { return Optional.empty(); } @@ -120,16 +114,16 @@ public final Optional last() { /** * Can be used to collect objects from the Iterable. Is a terminating operation. - * + * * @param count defines the number of objects to return * @return the same FluentIterable with a collection decimated to a maximum of 'count' last - * objects + * objects */ @Override public final FluentIterable last(int count) { - int remainingElementsCount = getRemainingElementsCount(); - Iterator iterator = iterator(); - int currentIndex = 0; + var remainingElementsCount = getRemainingElementsCount(); + var iterator = iterator(); + var currentIndex = 0; while (iterator.hasNext()) { iterator.next(); if (currentIndex < remainingElementsCount - count) { @@ -143,24 +137,21 @@ public final FluentIterable last(int count) { /** * Transforms this FluentIterable into a new one containing objects of the type T. - * + * * @param function a function that transforms an instance of E into an instance of T * @param the target type of the transformation * @return a new FluentIterable of the new type */ @Override public final FluentIterable map(Function function) { - List temporaryList = new ArrayList<>(); - Iterator iterator = iterator(); - while (iterator.hasNext()) { - temporaryList.add(function.apply(iterator.next())); - } + var temporaryList = new ArrayList(); + this.forEach(e -> temporaryList.add(function.apply(e))); return from(temporaryList); } /** * Collects all remaining objects of this Iterable into a list. - * + * * @return a list with all remaining objects of this Iterable */ @Override @@ -169,14 +160,16 @@ public List asList() { } /** + * Constructs FluentIterable from iterable. + * * @return a FluentIterable from a given iterable. Calls the SimpleFluentIterable constructor. */ - public static final FluentIterable from(Iterable iterable) { + public static FluentIterable from(Iterable iterable) { return new SimpleFluentIterable<>(iterable); } - public static final FluentIterable fromCopyOf(Iterable iterable) { - List copy = FluentIterable.copyToList(iterable); + public static FluentIterable fromCopyOf(Iterable iterable) { + var copy = FluentIterable.copyToList(iterable); return new SimpleFluentIterable<>(copy); } @@ -190,20 +183,19 @@ public void forEach(Consumer action) { iterable.forEach(action); } - @Override public Spliterator spliterator() { return iterable.spliterator(); } /** + * Find the count of remaining objects of current iterable. + * * @return the count of remaining objects of the current Iterable */ public final int getRemainingElementsCount() { - int counter = 0; - Iterator iterator = iterator(); - while (iterator.hasNext()) { - iterator.next(); + var counter = 0; + for (var ignored : this) { counter++; } return counter; @@ -211,14 +203,12 @@ public final int getRemainingElementsCount() { /** * Collects the remaining objects of the given iterator into a List. - * + * * @return a new List with the remaining objects. */ public static List toList(Iterator iterator) { - List copy = new ArrayList<>(); - while (iterator.hasNext()) { - copy.add(iterator.next()); - } + var copy = new ArrayList(); + iterator.forEachRemaining(copy::add); return copy; } } diff --git a/fluent-interface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java new file mode 100644 index 000000000000..003e4a12c950 --- /dev/null +++ b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.fluentinterface.app; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application Test Entry */ +class AppTest { + + @Test + void shouldExecuteWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java new file mode 100644 index 000000000000..d85b64109dd0 --- /dev/null +++ b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java @@ -0,0 +1,182 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.fluentinterface.fluentiterable; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; + +/** FluentIterableTest */ +public abstract class FluentIterableTest { + + /** + * Create a new {@link FluentIterable} from the given integers + * + * @param integers The integers + * @return The new iterable, use for testing + */ + protected abstract FluentIterable createFluentIterable(final Iterable integers); + + @Test + void testFirst() { + final var integers = List.of(1, 2, 3, 10, 9, 8); + final var first = createFluentIterable(integers).first(); + assertNotNull(first); + assertTrue(first.isPresent()); + assertEquals(integers.get(0), first.get()); + } + + @Test + void testFirstEmptyCollection() { + final var integers = Collections.emptyList(); + final var first = createFluentIterable(integers).first(); + assertNotNull(first); + assertFalse(first.isPresent()); + } + + @Test + void testFirstCount() { + final var integers = List.of(1, 2, 3, 10, 9, 8); + final var first4 = createFluentIterable(integers).first(4).asList(); + + assertNotNull(first4); + assertEquals(4, first4.size()); + + assertEquals(integers.get(0), first4.get(0)); + assertEquals(integers.get(1), first4.get(1)); + assertEquals(integers.get(2), first4.get(2)); + assertEquals(integers.get(3), first4.get(3)); + } + + @Test + void testFirstCountLessItems() { + final var integers = List.of(1, 2, 3); + final var first4 = createFluentIterable(integers).first(4).asList(); + + assertNotNull(first4); + assertEquals(3, first4.size()); + + assertEquals(integers.get(0), first4.get(0)); + assertEquals(integers.get(1), first4.get(1)); + assertEquals(integers.get(2), first4.get(2)); + } + + @Test + void testLast() { + final var integers = List.of(1, 2, 3, 10, 9, 8); + final var last = createFluentIterable(integers).last(); + assertNotNull(last); + assertTrue(last.isPresent()); + assertEquals(integers.get(integers.size() - 1), last.get()); + } + + @Test + void testLastEmptyCollection() { + final var integers = Collections.emptyList(); + final var last = createFluentIterable(integers).last(); + assertNotNull(last); + assertFalse(last.isPresent()); + } + + @Test + void testLastCount() { + final var integers = List.of(1, 2, 3, 10, 9, 8); + final var last4 = createFluentIterable(integers).last(4).asList(); + + assertNotNull(last4); + assertEquals(4, last4.size()); + assertEquals(Integer.valueOf(3), last4.get(0)); + assertEquals(Integer.valueOf(10), last4.get(1)); + assertEquals(Integer.valueOf(9), last4.get(2)); + assertEquals(Integer.valueOf(8), last4.get(3)); + } + + @Test + void testLastCountLessItems() { + final var integers = List.of(1, 2, 3); + final var last4 = createFluentIterable(integers).last(4).asList(); + + assertNotNull(last4); + assertEquals(3, last4.size()); + + assertEquals(Integer.valueOf(1), last4.get(0)); + assertEquals(Integer.valueOf(2), last4.get(1)); + assertEquals(Integer.valueOf(3), last4.get(2)); + } + + @Test + void testFilter() { + final var integers = List.of(1, 2, 3, 10, 9, 8); + final var evenItems = createFluentIterable(integers).filter(i -> i % 2 == 0).asList(); + + assertNotNull(evenItems); + assertEquals(3, evenItems.size()); + assertEquals(Integer.valueOf(2), evenItems.get(0)); + assertEquals(Integer.valueOf(10), evenItems.get(1)); + assertEquals(Integer.valueOf(8), evenItems.get(2)); + } + + @Test + void testMap() { + final var integers = List.of(1, 2, 3); + final var longs = createFluentIterable(integers).map(Integer::longValue).asList(); + + assertNotNull(longs); + assertEquals(integers.size(), longs.size()); + assertEquals(Long.valueOf(1), longs.get(0)); + assertEquals(Long.valueOf(2), longs.get(1)); + assertEquals(Long.valueOf(3), longs.get(2)); + } + + @Test + void testForEach() { + final var integers = List.of(1, 2, 3); + + final Consumer consumer = mock(Consumer.class); + createFluentIterable(integers).forEach(consumer); + + verify(consumer, times(1)).accept(1); + verify(consumer, times(1)).accept(2); + verify(consumer, times(1)).accept(3); + verifyNoMoreInteractions(consumer); + } + + @Test + void testSpliterator() { + final var integers = List.of(1, 2, 3); + final var split = createFluentIterable(integers).spliterator(); + assertNotNull(split); + } +} diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java similarity index 84% rename from fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java rename to fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java index 4f4a118634c6..2db7ef534d03 100644 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java +++ b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,16 +27,11 @@ import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import com.iluwatar.fluentinterface.fluentiterable.FluentIterableTest; -/** - * Date: 12/12/15 - 7:56 PM - * - * @author Jeroen Meulemeester - */ -public class LazyFluentIterableTest extends FluentIterableTest { +/** LazyFluentIterableTest */ +class LazyFluentIterableTest extends FluentIterableTest { @Override protected FluentIterable createFluentIterable(Iterable integers) { return LazyFluentIterable.from(integers); } - } diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java similarity index 84% rename from fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java rename to fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java index 23b93b0a09ff..5b1cc374d619 100644 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java +++ b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,16 +27,11 @@ import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import com.iluwatar.fluentinterface.fluentiterable.FluentIterableTest; -/** - * Date: 12/12/15 - 7:56 PM - * - * @author Jeroen Meulemeester - */ -public class SimpleFluentIterableTest extends FluentIterableTest { +/** SimpleFluentIterableTest */ +class SimpleFluentIterableTest extends FluentIterableTest { @Override protected FluentIterable createFluentIterable(Iterable integers) { return SimpleFluentIterable.fromCopyOf(integers); } - } diff --git a/fluentinterface/README.md b/fluentinterface/README.md deleted file mode 100644 index 767792da79ab..000000000000 --- a/fluentinterface/README.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -layout: pattern -title: Fluent Interface -folder: fluentinterface -permalink: /patterns/fluentinterface/ -categories: Other -tags: - - Java - - Difficulty-Intermediate - - Functional ---- - -## Intent -A fluent interface provides an easy-readable, flowing interface, that often mimics a domain specific language. Using this pattern results in code that can be read nearly as human language. - -## Implementation - -A fluent interface can be implemented using any of - - * Method Chaining - calling a method returns some object on which further methods can be called. - * Static Factory Methods and Imports - * Named parameters - can be simulated in Java using static factory methods. - -![Fluent Interface](./etc/fluentinterface.png "Fluent Interface") - -## Applicability -Use the Fluent Interface pattern when - -* you provide an API that would benefit from a DSL-like usage -* you have objects that are difficult to configure or use - -## Real world examples - -* [Java 8 Stream API](http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html) -* [Google Guava FluentInterable](https://github.com/google/guava/wiki/FunctionalExplained) -* [JOOQ](http://www.jooq.org/doc/3.0/manual/getting-started/use-cases/jooq-as-a-standalone-sql-builder/) -* [Mockito](http://mockito.org/) -* [Java Hamcrest](http://code.google.com/p/hamcrest/wiki/Tutorial) - -## Credits - -* [Fluent Interface - Martin Fowler](http://www.martinfowler.com/bliki/FluentInterface.html) -* [Evolutionary architecture and emergent design: Fluent interfaces - Neal Ford](http://www.ibm.com/developerworks/library/j-eaed14/) -* [Internal DSL](http://www.infoq.com/articles/internal-dsls-java) diff --git a/fluentinterface/pom.xml b/fluentinterface/pom.xml deleted file mode 100644 index a9183278612a..000000000000 --- a/fluentinterface/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - java-design-patterns - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - - fluentinterface - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.mockito - mockito-core - test - - - \ No newline at end of file diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java deleted file mode 100644 index fd6fc66dd7e9..000000000000 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java +++ /dev/null @@ -1,131 +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.fluentinterface.app; - -import static java.lang.String.valueOf; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.StringJoiner; -import java.util.function.Function; -import java.util.function.Predicate; - -import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; -import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable; -import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API. - * Those interfaces tend to mimic domain specific languages, so they can nearly be read as human - * languages. - *

    - * In this example two implementations of a {@link FluentIterable} interface are given. The - * {@link SimpleFluentIterable} evaluates eagerly and would be too costly for real world - * applications. The {@link LazyFluentIterable} is evaluated on termination. Their usage is - * demonstrated with a simple number list that is filtered, transformed and collected. The result is - * printed afterwards. - * - */ -public class App { - - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * Program entry point - */ - public static void main(String[] args) { - - List integerList = new ArrayList<>(); - integerList.addAll(Arrays.asList(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, - -68, 45)); - - prettyPrint("The initial list contains: ", integerList); - - List firstFiveNegatives = - SimpleFluentIterable.fromCopyOf(integerList).filter(negatives()).first(3).asList(); - prettyPrint("The first three negative values are: ", firstFiveNegatives); - - - List lastTwoPositives = - SimpleFluentIterable.fromCopyOf(integerList).filter(positives()).last(2).asList(); - prettyPrint("The last two positive values are: ", lastTwoPositives); - - SimpleFluentIterable - .fromCopyOf(integerList) - .filter(number -> number % 2 == 0) - .first() - .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber)); - - - List transformedList = - SimpleFluentIterable.fromCopyOf(integerList).filter(negatives()).map(transformToString()) - .asList(); - prettyPrint("A string-mapped list of negative numbers contains: ", transformedList); - - - List lastTwoOfFirstFourStringMapped = - LazyFluentIterable.from(integerList).filter(positives()).first(4).last(2) - .map(number -> "String[" + valueOf(number) + "]").asList(); - prettyPrint( - "The lazy list contains the last two of the first four positive numbers mapped to Strings: ", - lastTwoOfFirstFourStringMapped); - - LazyFluentIterable - .from(integerList) - .filter(negatives()) - .first(2) - .last() - .ifPresent(lastOfFirstTwo -> LOGGER.info("The last of the first two negatives is: {}", lastOfFirstTwo)); - } - - private static Function transformToString() { - return integer -> "String[" + valueOf(integer) + "]"; - } - - private static Predicate negatives() { - return integer -> integer < 0; - } - - private static Predicate positives() { - return integer -> integer > 0; - } - - private static void prettyPrint(String prefix, Iterable iterable) { - prettyPrint(", ", prefix, iterable); - } - - private static void prettyPrint(String delimiter, String prefix, - Iterable iterable) { - StringJoiner joiner = new StringJoiner(delimiter, prefix, "."); - Iterator iterator = iterable.iterator(); - while (iterator.hasNext()) { - joiner.add(iterator.next().toString()); - } - - LOGGER.info(joiner.toString()); - } -} diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java deleted file mode 100644 index 6e21bd8e41ad..000000000000 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java +++ /dev/null @@ -1,37 +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.fluentinterface.app; - -import org.junit.jupiter.api.Test; - -/** - * Application Test Entry - */ -public class AppTest { - - @Test - public void test() { - String[] args = {}; - App.main(args); - } -} diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java deleted file mode 100644 index 0eb9e003a053..000000000000 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java +++ /dev/null @@ -1,202 +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.fluentinterface.fluentiterable; - -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.Spliterator; -import java.util.function.Consumer; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -/** - * Date: 12/12/15 - 7:00 PM - * - * @author Jeroen Meulemeester - */ -public abstract class FluentIterableTest { - - /** - * Create a new {@link FluentIterable} from the given integers - * - * @param integers The integers - * @return The new iterable, use for testing - */ - protected abstract FluentIterable createFluentIterable(final Iterable integers); - - @Test - public void testFirst() throws Exception { - final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); - final Optional first = createFluentIterable(integers).first(); - assertNotNull(first); - assertTrue(first.isPresent()); - assertEquals(integers.get(0), first.get()); - } - - @Test - public void testFirstEmptyCollection() throws Exception { - final List integers = Collections.emptyList(); - final Optional first = createFluentIterable(integers).first(); - assertNotNull(first); - assertFalse(first.isPresent()); - } - - @Test - public void testFirstCount() throws Exception { - final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); - final List first4 = createFluentIterable(integers) - .first(4) - .asList(); - - assertNotNull(first4); - assertEquals(4, first4.size()); - - assertEquals(integers.get(0), first4.get(0)); - assertEquals(integers.get(1), first4.get(1)); - assertEquals(integers.get(2), first4.get(2)); - assertEquals(integers.get(3), first4.get(3)); - } - - @Test - public void testFirstCountLessItems() throws Exception { - final List integers = Arrays.asList(1, 2, 3); - final List first4 = createFluentIterable(integers) - .first(4) - .asList(); - - assertNotNull(first4); - assertEquals(3, first4.size()); - - assertEquals(integers.get(0), first4.get(0)); - assertEquals(integers.get(1), first4.get(1)); - assertEquals(integers.get(2), first4.get(2)); - } - - @Test - public void testLast() throws Exception { - final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); - final Optional last = createFluentIterable(integers).last(); - assertNotNull(last); - assertTrue(last.isPresent()); - assertEquals(integers.get(integers.size() - 1), last.get()); - } - - @Test - public void testLastEmptyCollection() throws Exception { - final List integers = Collections.emptyList(); - final Optional last = createFluentIterable(integers).last(); - assertNotNull(last); - assertFalse(last.isPresent()); - } - - @Test - public void testLastCount() throws Exception { - final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); - final List last4 = createFluentIterable(integers) - .last(4) - .asList(); - - assertNotNull(last4); - assertEquals(4, last4.size()); - assertEquals(Integer.valueOf(3), last4.get(0)); - assertEquals(Integer.valueOf(10), last4.get(1)); - assertEquals(Integer.valueOf(9), last4.get(2)); - assertEquals(Integer.valueOf(8), last4.get(3)); - } - - @Test - public void testLastCountLessItems() throws Exception { - final List integers = Arrays.asList(1, 2, 3); - final List last4 = createFluentIterable(integers) - .last(4) - .asList(); - - assertNotNull(last4); - assertEquals(3, last4.size()); - - assertEquals(Integer.valueOf(1), last4.get(0)); - assertEquals(Integer.valueOf(2), last4.get(1)); - assertEquals(Integer.valueOf(3), last4.get(2)); - } - - @Test - public void testFilter() throws Exception { - final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); - final List evenItems = createFluentIterable(integers) - .filter(i -> i % 2 == 0) - .asList(); - - assertNotNull(evenItems); - assertEquals(3, evenItems.size()); - assertEquals(Integer.valueOf(2), evenItems.get(0)); - assertEquals(Integer.valueOf(10), evenItems.get(1)); - assertEquals(Integer.valueOf(8), evenItems.get(2)); - } - - @Test - public void testMap() throws Exception { - final List integers = Arrays.asList(1, 2, 3); - final List longs = createFluentIterable(integers) - .map(Integer::longValue) - .asList(); - - assertNotNull(longs); - assertEquals(integers.size(), longs.size()); - assertEquals(Long.valueOf(1), longs.get(0)); - assertEquals(Long.valueOf(2), longs.get(1)); - assertEquals(Long.valueOf(3), longs.get(2)); - } - - @Test - public void testForEach() throws Exception { - final List integers = Arrays.asList(1, 2, 3); - - final Consumer consumer = mock(Consumer.class); - createFluentIterable(integers).forEach(consumer); - - verify(consumer, times(1)).accept(Integer.valueOf(1)); - verify(consumer, times(1)).accept(Integer.valueOf(2)); - verify(consumer, times(1)).accept(Integer.valueOf(3)); - verifyNoMoreInteractions(consumer); - - } - - @Test - public void testSpliterator() throws Exception { - final List integers = Arrays.asList(1, 2, 3); - final Spliterator split = createFluentIterable(integers).spliterator(); - assertNotNull(split); - } - -} \ No newline at end of file diff --git a/flux/README.md b/flux/README.md index 7ac312c443d2..e7702c839784 100644 --- a/flux/README.md +++ b/flux/README.md @@ -1,27 +1,121 @@ --- -layout: pattern -title: Flux -folder: flux -permalink: /patterns/flux/ -categories: Presentation Tier -tags: - - Java - - Difficulty-Intermediate +title: "Flux Pattern in Java: Streamlining Complex UIs with Unidirectional Data Flow" +shortTitle: Flux +description: "Learn how the Flux design pattern simplifies data flow in Java applications through unidirectional architecture. Explore examples, benefits, and real-world applications." +category: Architectural +language: en +tag: + - Client-server + - Decoupling + - Event-driven + - Publish/subscribe + - Reactive --- -## Intent -Flux eschews MVC in favor of a unidirectional data flow. When a -user interacts with a view, the view propagates an action through a central -dispatcher, to the various stores that hold the application's data and business -logic, which updates all of the views that are affected. +## Intent of Flux Design Pattern -![alt text](./etc/flux.png "Flux") +The Flux design pattern is intended to manage the flow of data in Java applications, particularly client-side web applications, by enforcing a unidirectional data flow. It aims to simplify the management of complex data interactions and promote a more predictable state behavior across components. -## Applicability -Use the Flux pattern when +## Detailed Explanation of Flux Pattern with Real-World Examples -* you want to focus on creating explicit and understandable update paths for your application's data, which makes tracing changes during development simpler and makes bugs easier to track down and fix. +Real-world example -## Credits +> Consider a busy restaurant kitchen as an analogy for the Flux design pattern. In this scenario, the kitchen operates based on customer orders (actions) received and processed through a single point of control (the dispatcher), which could be represented by the head chef. When an order arrives, the head chef assigns specific tasks to various sections of the kitchen (stores), such as the grill, the salad station, or the dessert team. Each section updates the progress of their tasks (state changes) back to the head chef, who ensures that all parts of the order are coordinated and completed in a synchronized manner before the dishes are sent out to the customer (the view). -* [Flux - Application architecture for building user interfaces](http://facebook.github.io/flux/) +In plain words + +> The Flux design pattern manages data flow in applications through a unidirectional architecture, coordinating actions, dispatchers, stores, and views to ensure stable and predictable state management. This pattern is particularly useful in Java design patterns for developing responsive client-side web applications. + +Wikipedia says + +> To support React's concept of unidirectional data flow (which might be contrasted with AngularJS's bidirectional flow), the Flux architecture was developed as an alternative to the popular model–view–controller architecture. Flux features actions which are sent through a central dispatcher to a store, and changes to the store are propagated back to the view. + +Architecture diagram + +![Flux Architecture Diagram](./etc/flux-architecture-diagram.png) + +## Programmatic Example of Flux Pattern in Java + +The Flux design pattern is used for building client-side web applications. It advocates for a unidirectional data flow. When a user interacts with a view, the view propagates an action through a central dispatcher, to the various stores that hold the application's data and business logic, which updates all the views that are affected. + +In the provided code, we can see an example of the Flux pattern in the `App` and `MenuStore` classes. + +The `App` class is the entry point of the application. It initializes and wires the system, registers the stores with the dispatcher, registers the views with the stores, and triggers the initial rendering of the views. When a menu item is clicked, it triggers events through the dispatcher. + +```java +public class App { + + public static void main(String[] args) { + + var menuStore = new MenuStore(); + Dispatcher.getInstance().registerStore(menuStore); + var contentStore = new ContentStore(); + Dispatcher.getInstance().registerStore(contentStore); + var menuView = new MenuView(); + menuStore.registerView(menuView); + var contentView = new ContentView(); + contentStore.registerView(contentView); + + menuView.render(); + contentView.render(); + + menuView.itemClicked(MenuItem.COMPANY); + } +} +``` + +The `MenuStore` class is a concrete store that holds the state of the menu. It updates its state and notifies the views when it receives an action from the dispatcher. + +```java +public class MenuStore extends Store { + + @Getter + private MenuItem selected = MenuItem.HOME; + + @Override + public void onAction(Action action) { + if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) { + var menuAction = (MenuAction) action; + selected = menuAction.getMenuItem(); + notifyChange(); + } + } +} +``` + +In this example, when a menu item is clicked, the `MenuView` triggers a `MENU_ITEM_SELECTED` action. The `Dispatcher` forwards this action to all registered stores. The `MenuStore` handles this action by updating its state and notifying its views, causing them to rerender with the new state. + +This is a basic example of the Flux pattern, where actions are dispatched from the views, handled by the stores, and cause the views to update. + +## When to Use the Flux Pattern in Java + +Flux is applicable in developing client-side Java applications, where maintaining consistent data across various components and managing complex state interactions are critical. It is especially suited for applications with dynamic user interfaces that react to frequent data updates. + +## Real-World Applications of Flux Pattern in Java + +* Facebook extensively uses the Flux design pattern in conjunction with React to build robust, scalable user interfaces that can handle complex data updates efficiently. +* Many modern web applications adopt Flux or its variations (like Redux) to manage state in environments that demand high responsiveness and predictability. + +## Benefits and Trade-offs of Flux Pattern + +Benefits: + +* Ensures a unidirectional data flow that simplifies debugging and testing. +* Enhances consistency across the application by centralizing the application state. +* Improves the predictability of data flow and interaction in large applications. + +Trade-offs: + +* Can introduce boilerplate and complexity in smaller applications. +* May require a learning curve to understand the pattern's architecture and its implementation nuances. + +## Related Java Design Patterns + +* [Observer](https://java-design-patterns.com/patterns/observer/): Flux's dispatcher component acts similarly to an observer, managing notifications about data changes to various stores. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Typically, the dispatcher in Flux is implemented as a singleton. +* [Mediator](https://java-design-patterns.com/patterns/mediator/): Flux can be considered a variation of the mediator pattern where the dispatcher mediates the flow of data and ensures components do not update the state directly. + +## References and Credits + +* [Learning React: Modern Patterns for Developing React Apps](https://amzn.to/3Qdn9Pg) +* [Pro React](https://amzn.to/3xNRttK) diff --git a/flux/etc/flux-architecture-diagram.png b/flux/etc/flux-architecture-diagram.png new file mode 100644 index 000000000000..a2493da64608 Binary files /dev/null and b/flux/etc/flux-architecture-diagram.png differ diff --git a/flux/etc/flux.urm.puml b/flux/etc/flux.urm.puml new file mode 100644 index 000000000000..300f179764cb --- /dev/null +++ b/flux/etc/flux.urm.puml @@ -0,0 +1,117 @@ +@startuml +package com.iluwatar.flux.view { + class ContentView { + - LOGGER : Logger {static} + - content : Content + + ContentView() + + render() + + storeChanged(store : Store) + } + class MenuView { + - LOGGER : Logger {static} + - selected : MenuItem + + MenuView() + + itemClicked(item : MenuItem) + + render() + + storeChanged(store : Store) + } + interface View { + + render() {abstract} + + storeChanged(Store) {abstract} + } +} +package com.iluwatar.flux.action { + abstract class Action { + - type : ActionType + + Action(type : ActionType) + + getType() : ActionType + } + enum ActionType { + + CONTENT_CHANGED {static} + + MENU_ITEM_SELECTED {static} + + valueOf(name : String) : ActionType {static} + + values() : ActionType[] {static} + } + enum Content { + + COMPANY {static} + + PRODUCTS {static} + - title : String + + toString() : String + + valueOf(name : String) : Content {static} + + values() : Content[] {static} + } + class ContentAction { + - content : Content + + ContentAction(content : Content) + + getContent() : Content + } + class MenuAction { + - menuItem : MenuItem + + MenuAction(menuItem : MenuItem) + + getMenuItem() : MenuItem + } + enum MenuItem { + + COMPANY {static} + + HOME {static} + + PRODUCTS {static} + - title : String + + toString() : String + + valueOf(name : String) : MenuItem {static} + + values() : MenuItem[] {static} + } +} +package com.iluwatar.flux.app { + class App { + + App() + + main(args : String[]) {static} + } +} +package com.iluwatar.flux.store { + class ContentStore { + - content : Content + + ContentStore() + + getContent() : Content + + onAction(action : Action) + } + class MenuStore { + - selected : MenuItem + + MenuStore() + + getSelected() : MenuItem + + onAction(action : Action) + } + abstract class Store { + - views : List + + Store() + # notifyChange() + + onAction(Action) {abstract} + + registerView(view : View) + } +} +package com.iluwatar.flux.dispatcher { + class Dispatcher { + - instance : Dispatcher {static} + - stores : List + - Dispatcher() + - dispatchAction(action : Action) + + getInstance() : Dispatcher {static} + + menuItemSelected(menuItem : MenuItem) + + registerStore(store : Store) + } +} +MenuAction --> "-menuItem" MenuItem +Action --> "-type" ActionType +MenuStore --> "-selected" MenuItem +Dispatcher --> "-instance" Dispatcher +ContentView --> "-content" Content +Dispatcher --> "-stores" Store +MenuView --> "-selected" MenuItem +Store --> "-views" View +ContentStore --> "-content" Content +ContentAction --> "-content" Content +ContentAction --|> Action +MenuAction --|> Action +ContentStore --|> Store +MenuStore --|> Store +ContentView ..|> View +MenuView ..|> View +@enduml \ No newline at end of file diff --git a/flux/pom.xml b/flux/pom.xml index 59d105b39123..f0259126dc2b 100644 --- a/flux/pom.xml +++ b/flux/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT flux - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.flux.app.App + + + + + + + + diff --git a/flux/src/main/java/com/iluwatar/flux/action/Action.java b/flux/src/main/java/com/iluwatar/flux/action/Action.java index 31765177a53c..cf59d5ad9446 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/Action.java +++ b/flux/src/main/java/com/iluwatar/flux/action/Action.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,13 @@ */ package com.iluwatar.flux.action; -/** - * - * Action is the data payload dispatched to the stores when something happens. - * - */ -public abstract class Action { - - private ActionType type; +import lombok.Getter; +import lombok.RequiredArgsConstructor; - public Action(ActionType type) { - this.type = type; - } +/** Action is the data payload dispatched to the stores when something happens. */ +@RequiredArgsConstructor +@Getter +public abstract class Action { - public ActionType getType() { - return type; - } + private final ActionType type; } diff --git a/flux/src/main/java/com/iluwatar/flux/action/ActionType.java b/flux/src/main/java/com/iluwatar/flux/action/ActionType.java index f5b5a2f810bb..9665959d030e 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/ActionType.java +++ b/flux/src/main/java/com/iluwatar/flux/action/ActionType.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,13 +24,8 @@ */ package com.iluwatar.flux.action; -/** - * - * Types of actions. - * - */ +/** Types of actions. */ public enum ActionType { - - MENU_ITEM_SELECTED, CONTENT_CHANGED; - + MENU_ITEM_SELECTED, + CONTENT_CHANGED } diff --git a/flux/src/main/java/com/iluwatar/flux/action/Content.java b/flux/src/main/java/com/iluwatar/flux/action/Content.java index 596b466db414..124e8f9eda99 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/Content.java +++ b/flux/src/main/java/com/iluwatar/flux/action/Content.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,15 @@ */ package com.iluwatar.flux.action; -/** - * - * Content items. - * - */ -public enum Content { +import lombok.RequiredArgsConstructor; - PRODUCTS("Products - This page lists the company's products."), COMPANY( - "Company - This page displays information about the company."); - - private String title; +/** Content items. */ +@RequiredArgsConstructor +public enum Content { + PRODUCTS("Products - This page lists the company's products."), + COMPANY("Company - This page displays information about the company."); - private Content(String title) { - this.title = title; - } + private final String title; @Override public String toString() { diff --git a/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java b/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java index f6005b8d77ad..fb3020dfa506 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java +++ b/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,15 @@ */ package com.iluwatar.flux.action; -/** - * - * ContentAction is a concrete action. - * - */ +import lombok.Getter; + +/** ContentAction is a concrete action. */ public class ContentAction extends Action { - private Content content; + @Getter private final Content content; public ContentAction(Content content) { super(ActionType.CONTENT_CHANGED); this.content = content; } - - public Content getContent() { - return content; - } } diff --git a/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java b/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java index 6dc95f5bc164..81e52213dd7e 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java +++ b/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,22 +24,15 @@ */ package com.iluwatar.flux.action; +import lombok.Getter; -/** - * - * MenuAction is a concrete action. - * - */ +/** MenuAction is a concrete action. */ public class MenuAction extends Action { - private MenuItem menuItem; + @Getter private final MenuItem menuItem; public MenuAction(MenuItem menuItem) { super(ActionType.MENU_ITEM_SELECTED); this.menuItem = menuItem; } - - public MenuItem getMenuItem() { - return menuItem; - } } diff --git a/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java b/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java index 5e0f0d6f1f8f..cc8087077e6c 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java +++ b/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,16 +24,13 @@ */ package com.iluwatar.flux.action; -/** - * - * Menu items. - * - */ +/** Menu items. */ public enum MenuItem { + HOME("Home"), + PRODUCTS("Products"), + COMPANY("Company"); - HOME("Home"), PRODUCTS("Products"), COMPANY("Company"); - - private String title; + private final String title; MenuItem(String title) { this.title = title; diff --git a/flux/src/main/java/com/iluwatar/flux/app/App.java b/flux/src/main/java/com/iluwatar/flux/app/App.java index c758652c7fb0..c47c6c888c2d 100644 --- a/flux/src/main/java/com/iluwatar/flux/app/App.java +++ b/flux/src/main/java/com/iluwatar/flux/app/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -30,38 +32,36 @@ import com.iluwatar.flux.view.MenuView; /** - * * Flux is the application architecture that Facebook uses for building client-side web * applications. Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with * a React view, the view propagates an action through a central dispatcher, to the various stores - * that hold the application's data and business logic, which updates all of the views that are + * that hold the application's data and business logic, which updates all the views that are * affected. - *

    - * This example has two views: menu and content. They represent typical main menu and content area - * of a web page. When menu item is clicked it triggers events through the dispatcher. The events - * are received and handled by the stores updating their data as needed. The stores then notify the - * views that they should rerender themselves. - *

    - * http://facebook.github.io/flux/docs/overview.html * + *

    This example has two views: menu and content. They represent typical main menu and content + * area of a web page. When menu item is clicked it triggers events through the dispatcher. The + * events are received and handled by the stores updating their data as needed. The stores then + * notify the views that they should rerender themselves. + * + *

    http://facebook.github.io/flux/docs/overview.html */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { // initialize and wire the system - MenuStore menuStore = new MenuStore(); + var menuStore = new MenuStore(); Dispatcher.getInstance().registerStore(menuStore); - ContentStore contentStore = new ContentStore(); + var contentStore = new ContentStore(); Dispatcher.getInstance().registerStore(contentStore); - MenuView menuView = new MenuView(); + var menuView = new MenuView(); menuStore.registerView(menuView); - ContentView contentView = new ContentView(); + var contentView = new ContentView(); contentStore.registerView(contentView); // render initial view diff --git a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java index 3be55dc46144..ca087dd420a2 100644 --- a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java +++ b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,55 +24,40 @@ */ package com.iluwatar.flux.dispatcher; -import java.util.LinkedList; -import java.util.List; - import com.iluwatar.flux.action.Action; import com.iluwatar.flux.action.Content; import com.iluwatar.flux.action.ContentAction; import com.iluwatar.flux.action.MenuAction; import com.iluwatar.flux.action.MenuItem; import com.iluwatar.flux.store.Store; +import java.util.LinkedList; +import java.util.List; +import lombok.Getter; -/** - * - * Dispatcher sends Actions to registered Stores. - * - */ +/** Dispatcher sends Actions to registered Stores. */ public final class Dispatcher { - private static Dispatcher instance = new Dispatcher(); + @Getter private static Dispatcher instance = new Dispatcher(); - private List stores = new LinkedList<>(); + private final List stores = new LinkedList<>(); private Dispatcher() {} - public static Dispatcher getInstance() { - return instance; - } - public void registerStore(Store store) { stores.add(store); } - /** - * Menu item selected handler - */ + /** Menu item selected handler. */ public void menuItemSelected(MenuItem menuItem) { dispatchAction(new MenuAction(menuItem)); - switch (menuItem) { - case HOME: - case PRODUCTS: - default: - dispatchAction(new ContentAction(Content.PRODUCTS)); - break; - case COMPANY: - dispatchAction(new ContentAction(Content.COMPANY)); - break; + if (menuItem == MenuItem.COMPANY) { + dispatchAction(new ContentAction(Content.COMPANY)); + } else { + dispatchAction(new ContentAction(Content.PRODUCTS)); } } private void dispatchAction(Action action) { - stores.stream().forEach(store -> store.onAction(action)); + stores.forEach(store -> store.onAction(action)); } } diff --git a/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java b/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java index b457dccbb254..b26146d52d95 100644 --- a/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java +++ b/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -26,26 +28,19 @@ import com.iluwatar.flux.action.ActionType; import com.iluwatar.flux.action.Content; import com.iluwatar.flux.action.ContentAction; +import lombok.Getter; -/** - * - * ContentStore is a concrete store. - * - */ +/** ContentStore is a concrete store. */ public class ContentStore extends Store { - private Content content = Content.PRODUCTS; + @Getter private Content content = Content.PRODUCTS; @Override public void onAction(Action action) { if (action.getType().equals(ActionType.CONTENT_CHANGED)) { - ContentAction contentAction = (ContentAction) action; + var contentAction = (ContentAction) action; content = contentAction.getContent(); notifyChange(); } } - - public Content getContent() { - return content; - } } diff --git a/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java b/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java index 124e027bdac2..c0d8d8255a16 100644 --- a/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java +++ b/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -26,26 +28,19 @@ import com.iluwatar.flux.action.ActionType; import com.iluwatar.flux.action.MenuAction; import com.iluwatar.flux.action.MenuItem; +import lombok.Getter; -/** - * - * MenuStore is a concrete store. - * - */ +/** MenuStore is a concrete store. */ public class MenuStore extends Store { - private MenuItem selected = MenuItem.HOME; + @Getter private MenuItem selected = MenuItem.HOME; @Override public void onAction(Action action) { if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) { - MenuAction menuAction = (MenuAction) action; + var menuAction = (MenuAction) action; selected = menuAction.getMenuItem(); notifyChange(); } } - - public MenuItem getSelected() { - return selected; - } } diff --git a/flux/src/main/java/com/iluwatar/flux/store/Store.java b/flux/src/main/java/com/iluwatar/flux/store/Store.java index 42a546c10982..879ae65d26c0 100644 --- a/flux/src/main/java/com/iluwatar/flux/store/Store.java +++ b/flux/src/main/java/com/iluwatar/flux/store/Store.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,15 @@ */ package com.iluwatar.flux.store; -import java.util.LinkedList; -import java.util.List; - import com.iluwatar.flux.action.Action; import com.iluwatar.flux.view.View; +import java.util.LinkedList; +import java.util.List; -/** - * - * Store is a data model. - * - */ +/** Store is a data model. */ public abstract class Store { - private List views = new LinkedList<>(); + private final List views = new LinkedList<>(); public abstract void onAction(Action action); @@ -44,6 +41,6 @@ public void registerView(View view) { } protected void notifyChange() { - views.stream().forEach(view -> view.storeChanged(this)); + views.forEach(view -> view.storeChanged(this)); } } diff --git a/flux/src/main/java/com/iluwatar/flux/view/ContentView.java b/flux/src/main/java/com/iluwatar/flux/view/ContentView.java index a501485c53df..66befdf78062 100644 --- a/flux/src/main/java/com/iluwatar/flux/view/ContentView.java +++ b/flux/src/main/java/com/iluwatar/flux/view/ContentView.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,23 +27,17 @@ import com.iluwatar.flux.action.Content; import com.iluwatar.flux.store.ContentStore; import com.iluwatar.flux.store.Store; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * ContentView is a concrete view. - * - */ +/** ContentView is a concrete view. */ +@Slf4j public class ContentView implements View { - private static final Logger LOGGER = LoggerFactory.getLogger(ContentView.class); - private Content content = Content.PRODUCTS; @Override public void storeChanged(Store store) { - ContentStore contentStore = (ContentStore) store; + var contentStore = (ContentStore) store; content = contentStore.getContent(); render(); } diff --git a/flux/src/main/java/com/iluwatar/flux/view/MenuView.java b/flux/src/main/java/com/iluwatar/flux/view/MenuView.java index 0744adce6091..74ae5192b4f7 100644 --- a/flux/src/main/java/com/iluwatar/flux/view/MenuView.java +++ b/flux/src/main/java/com/iluwatar/flux/view/MenuView.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -26,30 +28,24 @@ import com.iluwatar.flux.dispatcher.Dispatcher; import com.iluwatar.flux.store.MenuStore; import com.iluwatar.flux.store.Store; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * MenuView is a concrete view. - * - */ +/** MenuView is a concrete view. */ +@Slf4j public class MenuView implements View { - private static final Logger LOGGER = LoggerFactory.getLogger(MenuView.class); - private MenuItem selected = MenuItem.HOME; @Override public void storeChanged(Store store) { - MenuStore menuStore = (MenuStore) store; + var menuStore = (MenuStore) store; selected = menuStore.getSelected(); render(); } @Override public void render() { - for (MenuItem item : MenuItem.values()) { + for (var item : MenuItem.values()) { if (selected.equals(item)) { LOGGER.info("* {}", item); } else { diff --git a/flux/src/main/java/com/iluwatar/flux/view/View.java b/flux/src/main/java/com/iluwatar/flux/view/View.java index c7cc6036aa66..b31b20c18ffd 100644 --- a/flux/src/main/java/com/iluwatar/flux/view/View.java +++ b/flux/src/main/java/com/iluwatar/flux/view/View.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,11 +26,7 @@ import com.iluwatar.flux.store.Store; -/** - * - * Views define the representation of data. - * - */ +/** Views define the representation of data. */ public interface View { void storeChanged(Store store); diff --git a/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java b/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java index 53db61ddd0b6..8263468c9472 100644 --- a/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java +++ b/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,25 +24,20 @@ */ package com.iluwatar.flux.action; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; -/** - * Date: 12/12/15 - 10:11 PM - * - * @author Jeroen Meulemeester - */ -public class ContentTest { +import org.junit.jupiter.api.Test; + +/** ContentTest */ +class ContentTest { @Test - public void testToString() throws Exception { - for (final Content content : Content.values()) { - final String toString = content.toString(); + void testToString() { + for (final var content : Content.values()) { + final var toString = content.toString(); assertNotNull(toString); assertFalse(toString.trim().isEmpty()); } } - } diff --git a/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java b/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java index 60f19d8f3bbc..bf012abee931 100644 --- a/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java +++ b/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,25 +24,20 @@ */ package com.iluwatar.flux.action; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; -/** - * Date: 12/12/15 - 10:15 PM - * - * @author Jeroen Meulemeester - */ -public class MenuItemTest { +import org.junit.jupiter.api.Test; + +/** MenuItemTest */ +class MenuItemTest { @Test - public void testToString() throws Exception { - for (final MenuItem menuItem : MenuItem.values()) { - final String toString = menuItem.toString(); + void testToString() { + for (final var menuItem : MenuItem.values()) { + final var toString = menuItem.toString(); assertNotNull(toString); assertFalse(toString.trim().isEmpty()); } } - } diff --git a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java index 0a83759167b7..c594a1efb840 100644 --- a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java +++ b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.flux.app; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java b/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java index 54760557bf3f..b45de5992aef 100644 --- a/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java +++ b/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,6 +24,14 @@ */ package com.iluwatar.flux.dispatcher; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + import com.iluwatar.flux.action.Action; import com.iluwatar.flux.action.ActionType; import com.iluwatar.flux.action.Content; @@ -33,25 +43,8 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.util.List; -import java.util.stream.Collectors; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -/** - * Date: 12/12/15 - 8:22 PM - * - * @author Jeroen Meulemeester - */ -public class DispatcherTest { +/** DispatcherTest */ +class DispatcherTest { /** * Dispatcher is a singleton with no way to reset it's internal state back to the beginning. @@ -59,55 +52,67 @@ public class DispatcherTest { * influence on each other. */ @BeforeEach - public void setUp() throws Exception { - final Constructor constructor; - constructor = Dispatcher.class.getDeclaredConstructor(); + void setUp() throws Exception { + final var constructor = Dispatcher.class.getDeclaredConstructor(); constructor.setAccessible(true); - final Field field = Dispatcher.class.getDeclaredField("instance"); + final var field = Dispatcher.class.getDeclaredField("instance"); field.setAccessible(true); field.set(Dispatcher.getInstance(), constructor.newInstance()); } @Test - public void testGetInstance() throws Exception { + void testGetInstance() { assertNotNull(Dispatcher.getInstance()); assertSame(Dispatcher.getInstance(), Dispatcher.getInstance()); } @Test - public void testMenuItemSelected() throws Exception { - final Dispatcher dispatcher = Dispatcher.getInstance(); + void testMenuItemSelected() { + final var dispatcher = Dispatcher.getInstance(); - final Store store = mock(Store.class); + final var store = mock(Store.class); dispatcher.registerStore(store); dispatcher.menuItemSelected(MenuItem.HOME); dispatcher.menuItemSelected(MenuItem.COMPANY); // We expect 4 events, 2 menu selections and 2 content change actions - final ArgumentCaptor actionCaptor = ArgumentCaptor.forClass(Action.class); + final var actionCaptor = ArgumentCaptor.forClass(Action.class); verify(store, times(4)).onAction(actionCaptor.capture()); verifyNoMoreInteractions(store); - final List actions = actionCaptor.getAllValues(); - final List menuActions = actions.stream() + final var actions = actionCaptor.getAllValues(); + final var menuActions = + actions.stream() .filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED)) .map(a -> (MenuAction) a) - .collect(Collectors.toList()); + .toList(); - final List contentActions = actions.stream() + final var contentActions = + actions.stream() .filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED)) .map(a -> (ContentAction) a) - .collect(Collectors.toList()); + .toList(); assertEquals(2, menuActions.size()); - assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals).count()); - assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.COMPANY::equals).count()); + assertEquals( + 1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals).count()); + assertEquals( + 1, + menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.COMPANY::equals).count()); assertEquals(2, contentActions.size()); - assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.PRODUCTS::equals).count()); - assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.COMPANY::equals).count()); - + assertEquals( + 1, + contentActions.stream() + .map(ContentAction::getContent) + .filter(Content.PRODUCTS::equals) + .count()); + assertEquals( + 1, + contentActions.stream() + .map(ContentAction::getContent) + .filter(Content.COMPANY::equals) + .count()); } - } diff --git a/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java b/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java index 02a16ef33e6c..6d6270ddbd71 100644 --- a/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java +++ b/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,6 +24,13 @@ */ package com.iluwatar.flux.store; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + import com.iluwatar.flux.action.Content; import com.iluwatar.flux.action.ContentAction; import com.iluwatar.flux.action.MenuAction; @@ -29,40 +38,26 @@ import com.iluwatar.flux.view.View; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -/** - * Date: 12/12/15 - 10:18 PM - * - * @author Jeroen Meulemeester - */ -public class ContentStoreTest { +/** ContentStoreTest */ +class ContentStoreTest { @Test - public void testOnAction() throws Exception { - final ContentStore contentStore = new ContentStore(); + void testOnAction() { + final var contentStore = new ContentStore(); - final View view = mock(View.class); + final var view = mock(View.class); contentStore.registerView(view); - verifyZeroInteractions(view); + verifyNoMoreInteractions(view); // Content should not react on menu action ... contentStore.onAction(new MenuAction(MenuItem.PRODUCTS)); - verifyZeroInteractions(view); + verifyNoMoreInteractions(view); // ... but it should react on a content action contentStore.onAction(new ContentAction(Content.COMPANY)); verify(view, times(1)).storeChanged(eq(contentStore)); verifyNoMoreInteractions(view); assertEquals(Content.COMPANY, contentStore.getContent()); - } - } diff --git a/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java b/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java index aa432e1ff7f3..368307602596 100644 --- a/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java +++ b/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,6 +24,13 @@ */ package com.iluwatar.flux.store; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + import com.iluwatar.flux.action.Content; import com.iluwatar.flux.action.ContentAction; import com.iluwatar.flux.action.MenuAction; @@ -29,40 +38,26 @@ import com.iluwatar.flux.view.View; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -/** - * Date: 12/12/15 - 10:18 PM - * - * @author Jeroen Meulemeester - */ -public class MenuStoreTest { +/** MenuStoreTest */ +class MenuStoreTest { @Test - public void testOnAction() throws Exception { - final MenuStore menuStore = new MenuStore(); + void testOnAction() { + final var menuStore = new MenuStore(); - final View view = mock(View.class); + final var view = mock(View.class); menuStore.registerView(view); - verifyZeroInteractions(view); + verifyNoMoreInteractions(view); // Menu should not react on content action ... menuStore.onAction(new ContentAction(Content.COMPANY)); - verifyZeroInteractions(view); + verifyNoMoreInteractions(view); // ... but it should react on a menu action menuStore.onAction(new MenuAction(MenuItem.PRODUCTS)); verify(view, times(1)).storeChanged(eq(menuStore)); verifyNoMoreInteractions(view); assertEquals(MenuItem.PRODUCTS, menuStore.getSelected()); - } - } diff --git a/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java b/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java index c4498bacf318..a6b91a95b244 100644 --- a/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java +++ b/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,33 +24,28 @@ */ package com.iluwatar.flux.view; -import com.iluwatar.flux.action.Content; -import com.iluwatar.flux.store.ContentStore; -import org.junit.jupiter.api.Test; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; -/** - * Date: 12/12/15 - 10:31 PM - * - * @author Jeroen Meulemeester - */ -public class ContentViewTest { +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.store.ContentStore; +import org.junit.jupiter.api.Test; + +/** ContentViewTest */ +class ContentViewTest { @Test - public void testStoreChanged() throws Exception { - final ContentStore store = mock(ContentStore.class); + void testStoreChanged() { + final var store = mock(ContentStore.class); when(store.getContent()).thenReturn(Content.PRODUCTS); - final ContentView view = new ContentView(); + final var view = new ContentView(); view.storeChanged(store); verify(store, times(1)).getContent(); verifyNoMoreInteractions(store); } - } diff --git a/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java b/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java index 0967d51a888a..8fda7e47a57d 100644 --- a/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java +++ b/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,6 +24,13 @@ */ package com.iluwatar.flux.view; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + import com.iluwatar.flux.action.Action; import com.iluwatar.flux.action.MenuItem; import com.iluwatar.flux.dispatcher.Dispatcher; @@ -29,26 +38,15 @@ import com.iluwatar.flux.store.Store; import org.junit.jupiter.api.Test; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -/** - * Date: 12/12/15 - 10:31 PM - * - * @author Jeroen Meulemeester - */ -public class MenuViewTest { +/** MenuViewTest */ +class MenuViewTest { @Test - public void testStoreChanged() throws Exception { - final MenuStore store = mock(MenuStore.class); + void testStoreChanged() { + final var store = mock(MenuStore.class); when(store.getSelected()).thenReturn(MenuItem.HOME); - final MenuView view = new MenuView(); + final var view = new MenuView(); view.storeChanged(store); verify(store, times(1)).getSelected(); @@ -56,16 +54,14 @@ public void testStoreChanged() throws Exception { } @Test - public void testItemClicked() throws Exception { - final Store store = mock(Store.class); + void testItemClicked() { + final var store = mock(Store.class); Dispatcher.getInstance().registerStore(store); - final MenuView view = new MenuView(); + final var view = new MenuView(); view.itemClicked(MenuItem.PRODUCTS); // We should receive a menu click action and a content changed action verify(store, times(2)).onAction(any(Action.class)); - } - } diff --git a/flyweight/README.md b/flyweight/README.md index e008fc3465a4..04d29c712f7c 100644 --- a/flyweight/README.md +++ b/flyweight/README.md @@ -1,24 +1,26 @@ --- -layout: pattern -title: Flyweight -folder: flyweight -permalink: /patterns/flyweight/ -categories: Structural -tags: - - Java - - Gang Of Four - - Difficulty-Intermediate - - Performance +title: "Flyweight Pattern in Java: Maximizing Memory Efficiency with Shared Object Instances" +shortTitle: Flyweight +description: "Learn how the Flyweight design pattern optimizes memory usage in Java applications by sharing data among similar objects. Enhance performance and reduce memory footprint with practical examples and detailed explanations." +category: Structural +language: en +tag: + - Gang of Four + - Memory management + - Object composition + - Optimization + - Performance --- -## Intent -Use sharing to support large numbers of fine-grained objects -efficiently. +## Intent of Flyweight Design Pattern -## Explanation -Real world example +The Flyweight design pattern in Java is crucial for optimizing memory usage and enhancing application performance. By minimizing the number of objects created, it significantly reduces the memory footprint. The primary goal of the Flyweight pattern is to share as much data as possible among similar objects, thereby improving efficiency and performance. -> Alchemist's shop has shelves full of magic potions. Many of the potions are the same so there is no need to create new object for each of them. Instead one object instance can represent multiple shelf items so memory footprint remains small. +## Detailed Explanation of Flyweight Pattern with Real-World Examples + +Real-world example + +> A real-world application of the Flyweight pattern in Java can be seen in text editors like Microsoft Word or Google Docs. These applications use Flyweight to efficiently manage memory by sharing character objects, reducing the memory footprint significantly. In such applications, each character in a document could potentially be a separate object, which would be highly inefficient in terms of memory usage. Instead, the Flyweight pattern can be used to share character objects. For instance, all instances of the letter 'A' can share a single 'A' object with its intrinsic state (e.g., the shape of the character). The extrinsic state, such as the position, font, and color, can be stored separately and applied as needed. This way, the application efficiently manages memory by reusing existing objects for characters that appear multiple times. In plain words @@ -28,33 +30,45 @@ Wikipedia says > In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. -**Programmatic example** +Sequence diagram + +![Flyweight sequence diagram](./etc/flyweight-sequence-diagram.png) + +## Programmatic Example of Flyweight Pattern in Java + +Alchemist's shop has shelves full of magic potions. Many of the potions are the same so there is no need to create a new object for each of them. Instead, one object instance can represent multiple shelf items so the memory footprint remains small. -Translating our alchemist shop example from above. First of all we have different potion types +First of all, we have different `Potion` types: ```java public interface Potion { void drink(); } +``` +```java +@Slf4j public class HealingPotion implements Potion { - private static final Logger LOGGER = LoggerFactory.getLogger(HealingPotion.class); @Override public void drink() { LOGGER.info("You feel healed. (Potion={})", System.identityHashCode(this)); } } +``` +```java +@Slf4j public class HolyWaterPotion implements Potion { - private static final Logger LOGGER = LoggerFactory.getLogger(HolyWaterPotion.class); @Override public void drink() { LOGGER.info("You feel blessed. (Potion={})", System.identityHashCode(this)); } } +``` +```java +@Slf4j public class InvisibilityPotion implements Potion { - private static final Logger LOGGER = LoggerFactory.getLogger(InvisibilityPotion.class); @Override public void drink() { LOGGER.info("You become invisible. (Potion={})", System.identityHashCode(this)); @@ -62,7 +76,7 @@ public class InvisibilityPotion implements Potion { } ``` -Then the actual Flyweight object which is the factory for creating potions +Then the actual Flyweight class `PotionFactory`, which is the factory for creating potions. ```java public class PotionFactory { @@ -74,57 +88,134 @@ public class PotionFactory { } Potion createPotion(PotionType type) { - Potion potion = potions.get(type); + var potion = potions.get(type); if (potion == null) { switch (type) { - case HEALING: - potion = new HealingPotion(); - potions.put(type, potion); - break; - case HOLY_WATER: - potion = new HolyWaterPotion(); - potions.put(type, potion); - break; - case INVISIBILITY: - potion = new InvisibilityPotion(); - potions.put(type, potion); - break; - default: - break; + case HEALING -> potion = new HealingPotion(); + case HOLY_WATER -> potion = new HolyWaterPotion(); + case INVISIBILITY -> potion = new InvisibilityPotion(); + default -> { + } } + potions.put(type, potion); } return potion; } } ``` -And it can be used as below +`AlchemistShop` contains two shelves of magic potions. The potions are created using the aforementioned `PotionFactory`. + +```java +@Slf4j +public class AlchemistShop { + + private final List topShelf; + private final List bottomShelf; + + public AlchemistShop() { + var factory = new PotionFactory(); + topShelf = List.of( + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.STRENGTH), + factory.createPotion(PotionType.HEALING), + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.STRENGTH), + factory.createPotion(PotionType.HEALING), + factory.createPotion(PotionType.HEALING) + ); + bottomShelf = List.of( + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.HOLY_WATER), + factory.createPotion(PotionType.HOLY_WATER) + ); + } + + public final List getTopShelf() { + return List.copyOf(this.topShelf); + } + + public final List getBottomShelf() { + return List.copyOf(this.bottomShelf); + } + + public void drinkPotions() { + LOGGER.info("Drinking top shelf potions\n"); + topShelf.forEach(Potion::drink); + LOGGER.info("Drinking bottom shelf potions\n"); + bottomShelf.forEach(Potion::drink); + } +} +``` + +In our scenario, a brave visitor enters the alchemist shop and drinks all the potions. ```java -PotionFactory factory = new PotionFactory(); -factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818) -factory.createPotion(PotionType.HEALING).drink(); // You feel healed. (Potion=648129364) -factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818) -factory.createPotion(PotionType.HOLY_WATER).drink(); // You feel blessed. (Potion=1104106489) -factory.createPotion(PotionType.HOLY_WATER).drink(); // You feel blessed. (Potion=1104106489) -factory.createPotion(PotionType.HEALING).drink(); // You feel healed. (Potion=648129364) +public static void main(String[] args) { + // create the alchemist shop with the potions + var alchemistShop = new AlchemistShop(); + // a brave visitor enters the alchemist shop and drinks all the potions + alchemistShop.drinkPotions(); +} +``` + +Program output: + ``` +09:02:52.731 [main] INFO com.iluwatar.flyweight.AlchemistShop -- Drinking top shelf potions +09:02:52.733 [main] INFO com.iluwatar.flyweight.InvisibilityPotion -- You become invisible. (Potion=1395089624) +09:02:52.733 [main] INFO com.iluwatar.flyweight.InvisibilityPotion -- You become invisible. (Potion=1395089624) +09:02:52.733 [main] INFO com.iluwatar.flyweight.StrengthPotion -- You feel strong. (Potion=1450821318) +09:02:52.733 [main] INFO com.iluwatar.flyweight.HealingPotion -- You feel healed. (Potion=668849042) +09:02:52.733 [main] INFO com.iluwatar.flyweight.InvisibilityPotion -- You become invisible. (Potion=1395089624) +09:02:52.733 [main] INFO com.iluwatar.flyweight.StrengthPotion -- You feel strong. (Potion=1450821318) +09:02:52.733 [main] INFO com.iluwatar.flyweight.HealingPotion -- You feel healed. (Potion=668849042) +09:02:52.733 [main] INFO com.iluwatar.flyweight.HealingPotion -- You feel healed. (Potion=668849042) +09:02:52.733 [main] INFO com.iluwatar.flyweight.AlchemistShop -- Drinking bottom shelf potions +09:02:52.734 [main] INFO com.iluwatar.flyweight.PoisonPotion -- Urgh! This is poisonous. (Potion=2096057945) +09:02:52.734 [main] INFO com.iluwatar.flyweight.PoisonPotion -- Urgh! This is poisonous. (Potion=2096057945) +09:02:52.734 [main] INFO com.iluwatar.flyweight.PoisonPotion -- Urgh! This is poisonous. (Potion=2096057945) +09:02:52.734 [main] INFO com.iluwatar.flyweight.HolyWaterPotion -- You feel blessed. (Potion=1689843956) +09:02:52.734 [main] INFO com.iluwatar.flyweight.HolyWaterPotion -- You feel blessed. (Potion=1689843956) +``` + +## When to Use the Flyweight Pattern in Java -## Applicability -The Flyweight pattern's effectiveness depends heavily on how -and where it's used. Apply the Flyweight pattern when all of the following are -true +The Flyweight pattern's effectiveness depends heavily on how and where it's used. Apply the Flyweight pattern when all the following are true: -* an application uses a large number of objects -* storage costs are high because of the sheer quantity of objects -* most object state can be made extrinsic -* many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed -* the application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects. +* The Flyweight pattern is particularly effective in Java applications that use a large number of objects. +* When storage costs are high due to the quantity of objects, Flyweight helps by sharing intrinsic data and managing extrinsic state separately. +* Most of the object state can be made extrinsic. +* Many groups of objects may be replaced by relatively few shared objects once the extrinsic state is removed. +* The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects. -## Real world examples +## Real-World Applications of Flyweight Pattern in Java * [java.lang.Integer#valueOf(int)](http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#valueOf%28int%29) and similarly for Byte, Character and other wrapped types. +* Java’s String class utilizes the Flyweight pattern to manage string literals efficiently. +* GUI applications often use Flyweight for sharing objects like fonts or graphical components, thereby conserving memory and improving performance. + +## Benefits and Trade-offs of Flyweight Pattern + +Benefits: + +* Reduces the number of instances of an object, conserving memory. +* Centralizes state management, reducing the risk of inconsistent state. + +Trade-offs: + +* Increases complexity by adding the management layer for shared objects. +* Potential overhead in accessing shared objects if not well implemented. + +## Related Java Design Patterns + +* [Composite](https://java-design-patterns.com/patterns/composite/): Often combined with Flyweight when the composites are shareable. Both are used to manage hierarchies and structures of objects. +* [State](https://java-design-patterns.com/patterns/state/): Can be used to manage state in a shared Flyweight object, distinguishing internal state (invariant) from external state (context-specific). -## Credits +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/flyweight/etc/flyweight-sequence-diagram.png b/flyweight/etc/flyweight-sequence-diagram.png new file mode 100644 index 000000000000..bcf1f3489715 Binary files /dev/null and b/flyweight/etc/flyweight-sequence-diagram.png differ diff --git a/flyweight/etc/flyweight.urm.png b/flyweight/etc/flyweight.urm.png new file mode 100644 index 000000000000..299cdb7bdf86 Binary files /dev/null and b/flyweight/etc/flyweight.urm.png differ diff --git a/flyweight/etc/flyweight.urm.puml b/flyweight/etc/flyweight.urm.puml new file mode 100644 index 000000000000..61f2aa696eaf --- /dev/null +++ b/flyweight/etc/flyweight.urm.puml @@ -0,0 +1,65 @@ +@startuml +package com.iluwatar.flyweight { + class AlchemistShop { + - LOGGER : Logger {static} + - bottomShelf : List + - topShelf : List + + AlchemistShop() + + enumerate() + + getBottomShelf() : List + + getTopShelf() : List + } + class App { + + App() + + main(args : String[]) {static} + } + class HealingPotion { + - LOGGER : Logger {static} + + HealingPotion() + + drink() + } + class HolyWaterPotion { + - LOGGER : Logger {static} + + HolyWaterPotion() + + drink() + } + class InvisibilityPotion { + - LOGGER : Logger {static} + + InvisibilityPotion() + + drink() + } + class PoisonPotion { + - LOGGER : Logger {static} + + PoisonPotion() + + drink() + } + interface Potion { + + drink() {abstract} + } + class PotionFactory { + - potions : Map + + PotionFactory() + ~ createPotion(type : PotionType) : Potion + } + enum PotionType { + + HEALING {static} + + HOLY_WATER {static} + + INVISIBILITY {static} + + POISON {static} + + STRENGTH {static} + + valueOf(name : String) : PotionType {static} + + values() : PotionType[] {static} + } + class StrengthPotion { + - LOGGER : Logger {static} + + StrengthPotion() + + drink() + } +} +AlchemistShop --> "-topShelf" Potion +HealingPotion ..|> Potion +HolyWaterPotion ..|> Potion +InvisibilityPotion ..|> Potion +PoisonPotion ..|> Potion +StrengthPotion ..|> Potion +@enduml \ No newline at end of file diff --git a/flyweight/pom.xml b/flyweight/pom.xml index adf675b57093..26bc01369fd9 100644 --- a/flyweight/pom.xml +++ b/flyweight/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT flyweight - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.flyweight.App + + + + + + + + diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java index 01320e082961..42ce63c8efe8 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,87 +24,61 @@ */ package com.iluwatar.flyweight; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Collections; import java.util.List; +import lombok.extern.slf4j.Slf4j; -/** - * - * AlchemistShop holds potions on its shelves. It uses PotionFactory to provide the potions. - * - */ +/** AlchemistShop holds potions on its shelves. It uses PotionFactory to provide the potions. */ +@Slf4j public class AlchemistShop { - private static final Logger LOGGER = LoggerFactory.getLogger(AlchemistShop.class); + private final List topShelf; + private final List bottomShelf; - private List topShelf; - private List bottomShelf; - - /** - * Constructor - */ + /** Constructor. */ public AlchemistShop() { - topShelf = new ArrayList<>(); - bottomShelf = new ArrayList<>(); - fillShelves(); - } - - private void fillShelves() { - - PotionFactory factory = new PotionFactory(); - - topShelf.add(factory.createPotion(PotionType.INVISIBILITY)); - topShelf.add(factory.createPotion(PotionType.INVISIBILITY)); - topShelf.add(factory.createPotion(PotionType.STRENGTH)); - topShelf.add(factory.createPotion(PotionType.HEALING)); - topShelf.add(factory.createPotion(PotionType.INVISIBILITY)); - topShelf.add(factory.createPotion(PotionType.STRENGTH)); - topShelf.add(factory.createPotion(PotionType.HEALING)); - topShelf.add(factory.createPotion(PotionType.HEALING)); - - bottomShelf.add(factory.createPotion(PotionType.POISON)); - bottomShelf.add(factory.createPotion(PotionType.POISON)); - bottomShelf.add(factory.createPotion(PotionType.POISON)); - bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER)); - bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER)); + var factory = new PotionFactory(); + topShelf = + List.of( + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.STRENGTH), + factory.createPotion(PotionType.HEALING), + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.STRENGTH), + factory.createPotion(PotionType.HEALING), + factory.createPotion(PotionType.HEALING)); + bottomShelf = + List.of( + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.HOLY_WATER), + factory.createPotion(PotionType.HOLY_WATER)); } /** - * Get a read-only list of all the items on the top shelf + * Get a read-only list of all the items on the top shelf. * * @return The top shelf potions */ public final List getTopShelf() { - return Collections.unmodifiableList(this.topShelf); + return List.copyOf(this.topShelf); } /** - * Get a read-only list of all the items on the bottom shelf + * Get a read-only list of all the items on the bottom shelf. * * @return The bottom shelf potions */ public final List getBottomShelf() { - return Collections.unmodifiableList(this.bottomShelf); + return List.copyOf(this.bottomShelf); } - /** - * Enumerate potions - */ - public void enumerate() { - - LOGGER.info("Enumerating top shelf potions\n"); - - for (Potion p : topShelf) { - p.drink(); - } - - LOGGER.info("Enumerating bottom shelf potions\n"); - - for (Potion p : bottomShelf) { - p.drink(); - } + /** Drink all the potions. */ + public void drinkPotions() { + LOGGER.info("Drinking top shelf potions"); + topShelf.forEach(Potion::drink); + LOGGER.info("Drinking bottom shelf potions"); + bottomShelf.forEach(Potion::drink); } } diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/App.java b/flyweight/src/main/java/com/iluwatar/flyweight/App.java index 043321b5f84a..bd6523e676ee 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/App.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,28 +25,28 @@ package com.iluwatar.flyweight; /** - * * Flyweight pattern is useful when the program needs a huge amount of objects. It provides means to * decrease resource usage by sharing object instances. - *

    - * In this example {@link AlchemistShop} has great amount of potions on its shelves. To fill the + * + *

    In this example {@link AlchemistShop} has great amount of potions on its shelves. To fill the * shelves {@link AlchemistShop} uses {@link PotionFactory} (which represents the Flyweight in this * example). Internally {@link PotionFactory} holds a map of the potions and lazily creates new ones * when requested. - *

    - * To enable safe sharing, between clients and threads, Flyweight objects must be immutable. + * + *

    To enable safe sharing, between clients and threads, Flyweight objects must be immutable. * Flyweight objects are by definition value objects. - * */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - AlchemistShop alchemistShop = new AlchemistShop(); - alchemistShop.enumerate(); + // create the alchemist shop with the potions + var alchemistShop = new AlchemistShop(); + // a brave visitor enters the alchemist shop and drinks all the potions + alchemistShop.drinkPotions(); } } diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java index 060aaea4ab05..9fb66df96155 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.flyweight; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * HealingPotion - * - */ +/** HealingPotion. */ +@Slf4j public class HealingPotion implements Potion { - private static final Logger LOGGER = LoggerFactory.getLogger(HealingPotion.class); - @Override public void drink() { LOGGER.info("You feel healed. (Potion={})", System.identityHashCode(this)); diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java index 1b14f56be7d1..73822c8bff2e 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.flyweight; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * HolyWaterPotion - * - */ +/** HolyWaterPotion. */ +@Slf4j public class HolyWaterPotion implements Potion { - private static final Logger LOGGER = LoggerFactory.getLogger(HolyWaterPotion.class); - @Override public void drink() { LOGGER.info("You feel blessed. (Potion={})", System.identityHashCode(this)); diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java index 8baec7c13c4e..1e5ada3cc2f4 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.flyweight; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * InvisibilityPotion - * - */ +/** InvisibilityPotion. */ +@Slf4j public class InvisibilityPotion implements Potion { - private static final Logger LOGGER = LoggerFactory.getLogger(InvisibilityPotion.class); - @Override public void drink() { LOGGER.info("You become invisible. (Potion={})", System.identityHashCode(this)); diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java index 8f6bc113f72b..a25bfc6fcee9 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.flyweight; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * PoisonPotion - * - */ +/** PoisonPotion. */ +@Slf4j public class PoisonPotion implements Potion { - private static final Logger LOGGER = LoggerFactory.getLogger(PoisonPotion.class); - @Override public void drink() { LOGGER.info("Urgh! This is poisonous. (Potion={})", System.identityHashCode(this)); diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java b/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java index c6ce38760a5d..fa1af252b9af 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java @@ -1,33 +1,31 @@ -/** - * 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.flyweight; - -/** - * - * Interface for Potions. - * - */ -public interface Potion { - - void drink(); -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.flyweight; + +/** Interface for Potions. */ +public interface Potion { + + void drink(); +} diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java index c93707000547..2ac4e58a1bee 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java @@ -1,73 +1,60 @@ -/** - * 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.flyweight; - -import java.util.EnumMap; -import java.util.Map; - -/** - * - * PotionFactory is the Flyweight in this example. It minimizes memory use by sharing object - * instances. It holds a map of potion instances and new potions are created only when none of the - * type already exists. - * - */ -public class PotionFactory { - - private final Map potions; - - public PotionFactory() { - potions = new EnumMap<>(PotionType.class); - } - - Potion createPotion(PotionType type) { - Potion potion = potions.get(type); - if (potion == null) { - switch (type) { - case HEALING: - potion = new HealingPotion(); - potions.put(type, potion); - break; - case HOLY_WATER: - potion = new HolyWaterPotion(); - potions.put(type, potion); - break; - case INVISIBILITY: - potion = new InvisibilityPotion(); - potions.put(type, potion); - break; - case POISON: - potion = new PoisonPotion(); - potions.put(type, potion); - break; - case STRENGTH: - potion = new StrengthPotion(); - potions.put(type, potion); - break; - default: - break; - } - } - return potion; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.flyweight; + +import java.util.EnumMap; +import java.util.Map; + +/** + * PotionFactory is the Flyweight in this example. It minimizes memory use by sharing object + * instances. It holds a map of potion instances and new potions are created only when none of the + * type already exists. + */ +public class PotionFactory { + + private final Map potions; + + public PotionFactory() { + potions = new EnumMap<>(PotionType.class); + } + + Potion createPotion(PotionType type) { + var potion = potions.get(type); + if (potion == null) { + switch (type) { + case HEALING -> potion = new HealingPotion(); + case HOLY_WATER -> potion = new HolyWaterPotion(); + case INVISIBILITY -> potion = new InvisibilityPotion(); + case POISON -> potion = new PoisonPotion(); + case STRENGTH -> potion = new StrengthPotion(); + default -> {} + } + if (potion != null) { + potions.put(type, potion); + } + } + return potion; + } +} diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java b/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java index 3ee938838b06..da73c1f1caa1 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java @@ -1,33 +1,34 @@ -/** - * 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.flyweight; - -/** - * - * Enumeration for potion types. - * - */ -public enum PotionType { - - HEALING, INVISIBILITY, STRENGTH, HOLY_WATER, POISON -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.flyweight; + +/** Enumeration for potion types. */ +public enum PotionType { + HEALING, + INVISIBILITY, + STRENGTH, + HOLY_WATER, + POISON +} diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java index 787e717fce62..57a880b9f0e9 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.flyweight; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * StrengthPotion - * - */ +/** StrengthPotion. */ +@Slf4j public class StrengthPotion implements Potion { - private static final Logger LOGGER = LoggerFactory.getLogger(StrengthPotion.class); - @Override public void drink() { LOGGER.info("You feel strong. (Potion={})", System.identityHashCode(this)); diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java index 86d231e22a7c..b5aff254afb3 100644 --- a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java +++ b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,41 +24,34 @@ */ package com.iluwatar.flyweight; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -/** - * Date: 12/12/15 - 10:54 PM - * - * @author Jeroen Meulemeester - */ -public class AlchemistShopTest { +import java.util.ArrayList; +import java.util.HashSet; +import org.junit.jupiter.api.Test; + +/** AlchemistShopTest */ +class AlchemistShopTest { @Test - public void testShop() throws Exception { - final AlchemistShop shop = new AlchemistShop(); + void testShop() { + final var shop = new AlchemistShop(); - final List bottomShelf = shop.getBottomShelf(); + final var bottomShelf = shop.getBottomShelf(); assertNotNull(bottomShelf); assertEquals(5, bottomShelf.size()); - final List topShelf = shop.getTopShelf(); + final var topShelf = shop.getTopShelf(); assertNotNull(topShelf); assertEquals(8, topShelf.size()); - final List allPotions = new ArrayList<>(); + final var allPotions = new ArrayList(); allPotions.addAll(topShelf); allPotions.addAll(bottomShelf); // There are 13 potion instances, but only 5 unique instance types assertEquals(13, allPotions.size()); - assertEquals(5, allPotions.stream().map(System::identityHashCode).distinct().count()); - + assertEquals(5, new HashSet<>(allPotions).size()); } - } diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java index f7a33f0505d7..d2960fb15a79 100644 --- a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java +++ b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.flyweight; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/front-controller/README.md b/front-controller/README.md index a462a08e0ab6..4bf3f2e4100b 100644 --- a/front-controller/README.md +++ b/front-controller/README.md @@ -1,34 +1,143 @@ --- -layout: pattern -title: Front Controller -folder: front-controller -permalink: /patterns/front-controller/ -categories: Presentation Tier -tags: - - Java - - Difficulty-Intermediate +title: "Front Controller Pattern in Java: Centralizing Web Request Handling" +shortTitle: Front Controller +description: "Explore the Front Controller design pattern in Java for centralized request handling. Learn how to improve web application efficiency and consistency with this architectural pattern." +category: Architectural +language: en +tag: + - Architecture + - Decoupling + - Enterprise patterns + - Layered architecture + - Web development --- -## Intent -Introduce a common handler for all requests for a web site. This -way we can encapsulate common functionality such as security, -internationalization, routing and logging in a single place. +## Also known as -![alt text](./etc/front-controller.png "Front Controller") +* Centralized Request Handling -## Applicability -Use the Front Controller pattern when +## Intent of Front Controller Design Pattern -* you want to encapsulate common request handling functionality in single place -* you want to implements dynamic request handling i.e. change routing without modifying code -* make web server configuration portable, you only need to register the handler web server specific way +The Front Controller design pattern aims to provide a centralized entry point for handling all incoming web requests. This pattern ensures consistent and efficient request routing and management across a Java web application. -## Real world examples +## Detailed Explanation of Front Controller Pattern with Real-World Examples + +Real-world example + +> In a real-world scenario, a front desk in a hotel serves as the centralized request handling point, similar to how the Front Controller design pattern functions in web application architecture. This desk acts as the "front controller" of the hotel, responsible for receiving all inquiries, from room service orders to maintenance requests. The receptionist assesses each request and routes it to the appropriate department—housekeeping, the kitchen, or maintenance. This system centralizes request handling, ensuring that guest needs are addressed efficiently and consistently, similar to how a Front Controller in a software application manages all incoming requests and delegates them to specific handlers. + +In plain words + +> The Front Controller design pattern centralizes incoming web requests into a single handling point, allowing consistent processing and delegation across an application. + +Wikipedia says + +> The front controller software design pattern is listed in several pattern catalogs and is related to the design of web applications. It is "a controller that handles all requests for a website", which is a useful structure for web application developers to achieve flexibility and reuse without code redundancy. + +Architecture diagram + +![Front Controller Architecture Diagram](./etc/front-controller-architecture-diagram.png) + +## Programmatic Example of Front Controller Pattern in Java + +The Front Controller design pattern is a pattern that provides a centralized entry point for handling all requests in a web application. It ensures that request handling is managed consistently and efficiently across an application. + +In the provided code, we can see an example of the Front Controller pattern in the `App`, `FrontController` and `Dispatcher` classes. + +The `App` class is the entry point of the application. It creates an instance of `FrontController` and uses it to handle various requests. + +```java +public class App { + + public static void main(String[] args) { + var controller = new FrontController(); + controller.handleRequest("Archer"); + controller.handleRequest("Catapult"); + controller.handleRequest("foobar"); + } +} +``` + +The `FrontController` class is the front controller in this example. It handles all requests and delegates them to the `Dispatcher`. + +```java +public class FrontController { + + private final Dispatcher dispatcher; + + public FrontController() { + this.dispatcher = new Dispatcher(); + } + + public void handleRequest(String request) { + dispatcher.dispatch(request); + } +} +``` + +The `Dispatcher` class is responsible for handling the dispatching of requests to the appropriate command. It retrieves the corresponding command based on the request and invokes the command's process method to handle the business logic. + +```java +public class Dispatcher { + + public void dispatch(String request) { + var command = getCommand(request); + command.process(); + } + + Command getCommand(String request) { + var commandClass = getCommandClass(request); + try { + return (Command) commandClass.getDeclaredConstructor().newInstance(); + } catch (Exception e) { + throw new ApplicationException(e); + } + } + + static Class getCommandClass(String request) { + try { + return Class.forName("com.iluwatar.front.controller." + request + "Command"); + } catch (ClassNotFoundException e) { + return UnknownCommand.class; + } + } +} +``` + +In this example, when a request is received, the `FrontController` delegates the request to the `Dispatcher`, which creates a command object based on the request and calls its `process` method. The command object is responsible for handling the request and rendering the appropriate view. + +This is a basic example of the Front Controller pattern, where all requests are handled by a single controller and dispatcher, ensuring consistent and efficient request handling. + +## When to Use the Front Controller Pattern in Java + +* The Front Controller design pattern is particularly useful for Java web applications that require a centralized mechanism for request handling. +* Systems that need a common processing point for all requests to perform tasks such as authentication, logging, and routing. + +## Real-World Applications of Front Controller Pattern in Java * [Apache Struts](https://struts.apache.org/) +* Java web frameworks like Spring MVC and JavaServer Faces (JSF) implement the Front Controller pattern through their central dispatcher servlet, which manages web requests and delegates responsibilities. + +## Benefits and Trade-offs of Front Controller Pattern + +Benefits: + +* The main benefit of the Front Controller design pattern is the centralization of request handling, which simplifies maintenance and ensures consistent behavior across the application. +* Eases the integration of services like security and user session management. +* Facilitates common behavior like routing, logging, and authentication across requests. + +Trade-offs: + +* Can become a bottleneck if not properly managed. +* Increases complexity in the dispatcher controller, requiring careful design to avoid tight coupling. + +## Related Java Design Patterns + +* [Page Controller](https://java-design-patterns.com/patterns/page-controller/): Front Controller can delegate requests to Page Controllers, which handle specific page requests. This division supports the Single Responsibility Principle. +* [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): Front Controller acts as the controller, managing the flow between model and view. +* [Command](https://java-design-patterns.com/patterns/command/): Can be used to encapsulate a request as an object, which the Front Controller can manipulate and delegate. -## Credits +## References and Credits -* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2) -* [Presentation Tier Patterns](http://www.javagyan.com/tutorials/corej2eepatterns/presentation-tier-patterns) -* [Patterns of Enterprise Application Architecture](http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/front-controller/etc/front-controller-architecture-diagram.png b/front-controller/etc/front-controller-architecture-diagram.png new file mode 100644 index 000000000000..1caa0dc3b45d Binary files /dev/null and b/front-controller/etc/front-controller-architecture-diagram.png differ diff --git a/front-controller/etc/front-controller.urm.puml b/front-controller/etc/front-controller.urm.puml new file mode 100644 index 000000000000..d2c21fc015a0 --- /dev/null +++ b/front-controller/etc/front-controller.urm.puml @@ -0,0 +1,53 @@ +@startuml +package com.iluwatar.front.controller { + class App { + + App() + + main(args : String[]) {static} + } + class ArcherCommand { + + ArcherCommand() + + process() + } + class ArcherView { + - LOGGER : Logger {static} + + ArcherView() + + display() + } + class CatapultCommand { + + CatapultCommand() + + process() + } + class CatapultView { + - LOGGER : Logger {static} + + CatapultView() + + display() + } + interface Command { + + process() {abstract} + } + class ErrorView { + - LOGGER : Logger {static} + + ErrorView() + + display() + } + class FrontController { + + FrontController() + - getCommand(request : String) : Command + - getCommandClass(request : String) : Class {static} + + handleRequest(request : String) + } + class UnknownCommand { + + UnknownCommand() + + process() + } + interface View { + + display() {abstract} + } +} +ArcherCommand ..|> Command +ArcherView ..|> View +CatapultCommand ..|> Command +CatapultView ..|> View +ErrorView ..|> View +UnknownCommand ..|> Command +@enduml \ No newline at end of file diff --git a/front-controller/pom.xml b/front-controller/pom.xml index b76852e022ed..ba29e314bcc6 100644 --- a/front-controller/pom.xml +++ b/front-controller/pom.xml @@ -1,8 +1,10 @@ - + - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - front-controller - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.jupiter - junit-jupiter-params - test - - - org.mockito - mockito-core - test - - + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + front-controller + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.front.controller.App + + + + + + + + diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/App.java b/front-controller/src/main/java/com/iluwatar/front/controller/App.java index 92f43e363d9c..88f24360930a 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/App.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,33 +25,30 @@ package com.iluwatar.front.controller; /** - * - * The Front Controller is a presentation tier pattern. Essentially it defines a controller that - * handles all requests for a web site. - *

    - * The Front Controller pattern consolidates request handling through a single handler object ( - * {@link FrontController}). This object can carry out the common the behavior such as - * authorization, request logging and routing requests to corresponding views. - *

    - * Typically the requests are mapped to command objects ({@link Command}) which then display the + * The Front Controller is a presentation tier pattern. Essentially, it defines a controller that + * handles all requests for a website. + * + *

    The Front Controller pattern consolidates request handling through a single handler object ( + * {@link FrontController}). This object can carry out common behavior such as authorization, + * request logging and routing requests to corresponding views. + * + *

    Typically, the requests are mapped to command objects ({@link Command}) which then display the * correct view ({@link View}). - *

    - * In this example we have implemented two views: {@link ArcherView} and {@link CatapultView}. These - * are displayed by sending correct request to the {@link FrontController} object. For example, the - * {@link ArcherView} gets displayed when {@link FrontController} receives request "Archer". When - * the request is unknown, we display the error view ({@link ErrorView}). * + *

    In this example we have implemented two views: {@link ArcherView} and {@link CatapultView}. + * These are displayed by sending correct request to the {@link FrontController} object. For + * example, the {@link ArcherView} gets displayed when {@link FrontController} receives request + * "Archer". When the request is unknown, we display the error view ({@link ErrorView}). */ public class App { /** - * Program entry point - * - * @param args - * command line args + * Program entry point. + * + * @param args command line args */ public static void main(String[] args) { - FrontController controller = new FrontController(); + var controller = new FrontController(); controller.handleRequest("Archer"); controller.handleRequest("Catapult"); controller.handleRequest("foobar"); diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java b/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java index 882784bbfe4f..2016c9d4d593 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,12 @@ */ package com.iluwatar.front.controller; -/** - * - * Custom exception type - * - */ +import java.io.Serial; + +/** Custom exception type. */ public class ApplicationException extends RuntimeException { - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; public ApplicationException(Throwable cause) { super(cause); diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java b/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java index b1bb77d3cd4b..a062e340577a 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.front.controller; -/** - * - * Command for archers. - * - */ +/** Command for archers. */ public class ArcherCommand implements Command { @Override diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/ArcherView.java b/front-controller/src/main/java/com/iluwatar/front/controller/ArcherView.java index af6c72d0d962..794ecccb3991 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/ArcherView.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/ArcherView.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,11 @@ */ package com.iluwatar.front.controller; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * View for archers. - * - */ +/** View for archers. */ +@Slf4j public class ArcherView implements View { - - private static final Logger LOGGER = LoggerFactory.getLogger(ArcherView.class); @Override public void display() { diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java b/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java index e5cc47043819..6d032f99929f 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.front.controller; -/** - * - * Command for catapults. - * - */ +/** Command for catapults. */ public class CatapultCommand implements Command { @Override diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/CatapultView.java b/front-controller/src/main/java/com/iluwatar/front/controller/CatapultView.java index 2191fcaa6d03..68a02460a6c1 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/CatapultView.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/CatapultView.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.front.controller; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * View for catapults. - * - */ +/** View for catapults. */ +@Slf4j public class CatapultView implements View { - private static final Logger LOGGER = LoggerFactory.getLogger(CatapultView.class); - @Override public void display() { LOGGER.info("Displaying catapults"); diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/Command.java b/front-controller/src/main/java/com/iluwatar/front/controller/Command.java index 998d7dea87f7..a55b978485ef 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/Command.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/Command.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.front.controller; -/** - * - * Commands are the intermediary between requests and views. - * - */ +/** Commands are the intermediary between requests and views. */ public interface Command { void process(); diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/Dispatcher.java b/front-controller/src/main/java/com/iluwatar/front/controller/Dispatcher.java new file mode 100644 index 000000000000..5b9da51b0abe --- /dev/null +++ b/front-controller/src/main/java/com/iluwatar/front/controller/Dispatcher.java @@ -0,0 +1,72 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.front.controller; + +/** + * The Dispatcher class is responsible for handling the dispatching of requests to the appropriate + * command. It retrieves the corresponding command based on the request and invokes the command's + * process method to handle the business logic. + */ +public class Dispatcher { + + /** + * Dispatches the request to the appropriate command. + * + * @param request the request to be handled + */ + public void dispatch(String request) { + var command = getCommand(request); + command.process(); + } + + /** + * Retrieves the appropriate command instance for the given request. + * + * @param request the request to be handled + * @return the command instance corresponding to the request + */ + Command getCommand(String request) { + var commandClass = getCommandClass(request); + try { + return (Command) commandClass.getDeclaredConstructor().newInstance(); + } catch (Exception e) { + throw new ApplicationException(e); + } + } + + /** + * Retrieves the Class object for the command corresponding to the given request. + * + * @param request the request to be handled + * @return the Class object of the command corresponding to the request + */ + static Class getCommandClass(String request) { + try { + return Class.forName("com.iluwatar.front.controller." + request + "Command"); + } catch (ClassNotFoundException e) { + return UnknownCommand.class; + } + } +} diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/ErrorView.java b/front-controller/src/main/java/com/iluwatar/front/controller/ErrorView.java index 22961ef7b880..3e1a1d1b88b1 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/ErrorView.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/ErrorView.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.front.controller; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * View for errors. - * - */ +/** View for errors. */ +@Slf4j public class ErrorView implements View { - private static final Logger LOGGER = LoggerFactory.getLogger(ErrorView.class); - @Override public void display() { LOGGER.error("Error 500"); diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java b/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java index 19f4a39f1812..293cedba4e39 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,34 +25,19 @@ package com.iluwatar.front.controller; /** - * - * FrontController is the handler class that takes in all the requests and renders the correct - * response. - * + * The FrontController is responsible for handling all incoming requests. It delegates the + * processing of requests to the Dispatcher, which then determines the appropriate command and view + * to render the correct response. */ public class FrontController { - public void handleRequest(String request) { - Command command = getCommand(request); - command.process(); - } + private final Dispatcher dispatcher; - private Command getCommand(String request) { - Class commandClass = getCommandClass(request); - try { - return (Command) commandClass.newInstance(); - } catch (Exception e) { - throw new ApplicationException(e); - } + public FrontController() { + this.dispatcher = new Dispatcher(); } - private static Class getCommandClass(String request) { - Class result; - try { - result = Class.forName("com.iluwatar.front.controller." + request + "Command"); - } catch (ClassNotFoundException e) { - result = UnknownCommand.class; - } - return result; + public void handleRequest(String request) { + dispatcher.dispatch(request); } } diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java b/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java index ad888bf9ebc6..56d2b60a16f9 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.front.controller; -/** - * - * Default command in case the mapping is not successful. - * - */ +/** Default command in case the mapping is not successful. */ public class UnknownCommand implements Command { @Override diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/View.java b/front-controller/src/main/java/com/iluwatar/front/controller/View.java index ad43d0b026f0..cc741b9e6db0 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/View.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/View.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.front.controller; -/** - * - * Views are the representations rendered for the user. - * - */ +/** Views are the representations rendered for the user. */ public interface View { void display(); diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java index f7fe59cf1fd4..287398cc5763 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.front.controller; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java index ee13d47d706f..91e071f8be4e 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,16 @@ */ package com.iluwatar.front.controller; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertSame; -/** - * Date: 12/13/15 - 1:35 PM - * - * @author Jeroen Meulemeester - */ -public class ApplicationExceptionTest { +import org.junit.jupiter.api.Test; + +/** ApplicationExceptionTest */ +class ApplicationExceptionTest { @Test - public void testCause() throws Exception { - final Exception cause = new Exception(); + void testCause() { + final var cause = new Exception(); assertSame(cause, new ApplicationException(cause).getCause()); } - -} \ No newline at end of file +} diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java index 9e8f986e20a6..7f7a3d39062c 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,56 +24,48 @@ */ package com.iluwatar.front.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.front.controller.utils.InMemoryAppender; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Date: 12/13/15 - 1:39 PM - * - * @author Jeroen Meulemeester - */ -public class CommandTest { +/** CommandTest */ +class CommandTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } static List dataProvider() { - final List parameters = new ArrayList<>(); - parameters.add(new Object[]{"Archer", "Displaying archers"}); - parameters.add(new Object[]{"Catapult", "Displaying catapults"}); - parameters.add(new Object[]{"NonExistentCommand", "Error 500"}); - return parameters; + return List.of( + new Object[] {"Archer", "Displaying archers"}, + new Object[] {"Catapult", "Displaying catapults"}, + new Object[] {"NonExistentCommand", "Error 500"}); } /** - * @param request The request that's been tested + * @param request The request that's been tested * @param displayMessage The expected display message */ @ParameterizedTest @MethodSource("dataProvider") - public void testDisplay(String request, String displayMessage) { - final FrontController frontController = new FrontController(); + void testDisplay(String request, String displayMessage) { + final var frontController = new FrontController(); assertEquals(0, appender.getLogSize()); frontController.handleRequest(request); assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/DispatcherTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/DispatcherTest.java new file mode 100644 index 000000000000..64c611c49442 --- /dev/null +++ b/front-controller/src/test/java/com/iluwatar/front/controller/DispatcherTest.java @@ -0,0 +1,91 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.front.controller; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class DispatcherTest { + + private Dispatcher dispatcher; + + @BeforeEach + public void setUp() { + dispatcher = new Dispatcher(); + } + + @Test + void testDispatchKnownCommand() { + Command mockCommand = mock(ArcherCommand.class); + dispatcher = spy(dispatcher); + doReturn(mockCommand).when(dispatcher).getCommand("Archer"); + + dispatcher.dispatch("Archer"); + + verify(mockCommand, times(1)).process(); + } + + @Test + void testDispatchUnknownCommand() { + Command mockCommand = mock(UnknownCommand.class); + dispatcher = spy(dispatcher); + doReturn(mockCommand).when(dispatcher).getCommand("Unknown"); + + dispatcher.dispatch("Unknown"); + + verify(mockCommand, times(1)).process(); + } + + @Test + void testGetCommandKnown() { + Command command = dispatcher.getCommand("Archer"); + assertNotNull(command); + assertTrue(command instanceof ArcherCommand); + } + + @Test + void testGetCommandUnknown() { + Command command = dispatcher.getCommand("Unknown"); + assertNotNull(command); + assertTrue(command instanceof UnknownCommand); + } + + @Test + void testGetCommandClassKnown() { + Class commandClass = Dispatcher.getCommandClass("Archer"); + assertNotNull(commandClass); + assertEquals(ArcherCommand.class, commandClass); + } + + @Test + void testGetCommandClassUnknown() { + Class commandClass = Dispatcher.getCommandClass("Unknown"); + assertNotNull(commandClass); + assertEquals(UnknownCommand.class, commandClass); + } +} diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java index 4b4eb6fdd896..b4163aef4c5a 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,55 +24,47 @@ */ package com.iluwatar.front.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.front.controller.utils.InMemoryAppender; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Date: 12/13/15 - 1:39 PM - * - * @author Jeroen Meulemeester - */ -public class FrontControllerTest { +/** FrontControllerTest */ +class FrontControllerTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } static List dataProvider() { - final List parameters = new ArrayList<>(); - parameters.add(new Object[]{new ArcherCommand(), "Displaying archers"}); - parameters.add(new Object[]{new CatapultCommand(), "Displaying catapults"}); - parameters.add(new Object[]{new UnknownCommand(), "Error 500"}); - return parameters; + return List.of( + new Object[] {new ArcherCommand(), "Displaying archers"}, + new Object[] {new CatapultCommand(), "Displaying catapults"}, + new Object[] {new UnknownCommand(), "Error 500"}); } /** - * @param command The command that's been tested + * @param command The command that's been tested * @param displayMessage The expected display message */ @ParameterizedTest @MethodSource("dataProvider") - public void testDisplay(Command command, String displayMessage) { + void testDisplay(Command command, String displayMessage) { assertEquals(0, appender.getLogSize()); command.process(); assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java index a0c3032359ce..09cd1e21e617 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,55 +24,47 @@ */ package com.iluwatar.front.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.front.controller.utils.InMemoryAppender; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Date: 12/13/15 - 1:39 PM - * - * @author Jeroen Meulemeester - */ -public class ViewTest { +/** ViewTest */ +class ViewTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } static List dataProvider() { - final List parameters = new ArrayList<>(); - parameters.add(new Object[]{new ArcherView(), "Displaying archers"}); - parameters.add(new Object[]{new CatapultView(), "Displaying catapults"}); - parameters.add(new Object[]{new ErrorView(), "Error 500"}); - return parameters; + return List.of( + new Object[] {new ArcherView(), "Displaying archers"}, + new Object[] {new CatapultView(), "Displaying catapults"}, + new Object[] {new ErrorView(), "Error 500"}); } /** - * @param view The view that's been tested + * @param view The view that's been tested * @param displayMessage The expected display message */ @ParameterizedTest @MethodSource("dataProvider") - public void testDisplay(View view, String displayMessage) { + void testDisplay(View view, String displayMessage) { assertEquals(0, appender.getLogSize()); view.display(); assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java b/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java index 2e6f26c0c668..86268d4c38c8 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,17 +27,14 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.slf4j.LoggerFactory; - import java.util.LinkedList; import java.util.List; +import org.slf4j.LoggerFactory; -/** - * InMemory Log Appender Util. - */ +/** InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); + private final List log = new LinkedList<>(); public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); diff --git a/function-composition/.gitignore b/function-composition/.gitignore new file mode 100644 index 000000000000..431eba612aae --- /dev/null +++ b/function-composition/.gitignore @@ -0,0 +1,59 @@ +################## Eclipse ###################### +target +.metadata +.settings +.classpath +.project +*.class +tmp/ +*.tmp +*.bak +*~.nib +local.properties +.loadpath +.recommenders +.DS_Store + +####### Java annotation processor (APT) ######## +.factorypath + +################ Package Files ################## +*.jar +*.war +*.ear +*.swp +datanucleus.log +/bin/ +*.log +event-sourcing/Journal.json + +################## Checkstyle ################### +.checkstyle + +##################### STS ####################### +.apt_generated +.springBeans +.sts4-cache + +################# IntelliJ IDEA ################# +.idea +*.iws +*.iml +*.ipr + +################### NetBeans #################### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +#################### VS Code #################### +.vscode/ + +#################### Java Design Patterns ####### +etc/Java Design Patterns.urm.puml +serialized-entity/output.txt diff --git a/function-composition/README.md b/function-composition/README.md new file mode 100644 index 000000000000..961aaa6504c1 --- /dev/null +++ b/function-composition/README.md @@ -0,0 +1,127 @@ +--- +title: "Function Composition Pattern in Java: Crafting Elegant Functional Pipelines" +shortTitle: Function Composition +description: "Learn about the Function Composition design pattern in Java. Discover how to create complex functions by combining simpler ones, enhancing code modularity and reusability. Explore real-world examples, benefits, and applications." +category: Functional +language: en +tag: + - Code simplification + - Composition + - Functional decomposition + - Reusability +--- + +## Also known as + +* Function Chaining +* Higher-Order Function Wrapping + +## Intent of Function Composition Design Pattern + +Combine multiple small functions into a single operation that executes them in a sequence, producing a new function as the result. + +## Detailed Explanation of Function Composition Pattern with Real-World Examples + +Real-world example + +> Imagine a fast-food restaurant where the process of making a burger is broken down into several steps: grilling the patty, toasting the bun, adding condiments, and assembling the burger. Each of these steps can be seen as a function. +> +> In the Functional Composition design pattern, these individual steps (functions) can be composed into a complete burger-making process. Each step remains simple and reusable. For instance, the grilling function could be reused for making sandwiches or other dishes that require a grilled patty. This modular approach allows the restaurant to efficiently create various menu items by reusing and combining simple, predefined steps. + +In plain words + +> The Function Composition pattern allows building complex functions by combining simpler ones, making it easier to manage, test, and reuse individual pieces of functionality. + +Wikipedia says + +> Function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next, and the result of the last one is the result of the whole. + +Sequence diagram + +![Function Composition sequence diagram](./etc/function-composition-sequence-diagram.png) + +## Programmatic Example of Function Composition Pattern in Java + +In the functional programming paradigm, function composition is a powerful technique. For instance, in Java, you can use higher-order functions to combine operations like multiplying and squaring numbers. + +Using Java's functional interfaces, we can define simple functions and compose them. Here's how function composition works in Java. + +Let's start with defining two simple functions. In this case, we have a function `timesTwo` that multiplies its input by 2, and a function `square` that squares its input: + +```java +Function timesTwo = x -> x * 2; +Function square = x -> x * x; +``` + +Next, we use the `FunctionComposer` class to compose these two functions into a new function. The `composeFunctions` method takes two functions as arguments and returns a new function that is the composition of the input functions: + +```java +Function composedFunction = FunctionComposer.composeFunctions(timesTwo, square); +``` + +Finally, we apply the composed function to an input value. In this case, we apply it to the number 3. The result is the square of the number 3 multiplied by 2, which is 36: + +```java +public static void main(String[] args) { + final var logger = LoggerFactory.getLogger(App.class); + Function timesTwo = x -> x * 2; + Function square = x -> x * x; + + Function composedFunction = FunctionComposer.composeFunctions(timesTwo, square); + + int result = composedFunction.apply(3); + logger.info("Result of composing 'timesTwo' and 'square' functions applied to 3 is: " + result); +} +``` + +This will output: + +``` +Result of composing 'timesTwo' and 'square' functions applied to 3 is: 36 +``` + +This example demonstrates how the Function Composition pattern can be used to create complex functions by composing simpler ones, enhancing modularity and reusability of function-based logic. + +## When to Use the Function Composition Pattern in Java + +Use the Function Composition pattern when: + +* When you want to build complex transformations by chaining smaller, reusable functions in Java. +* When the logic is best expressed through a series of operations that naturally feed one into another. +* When you want to reduce code duplication and improve readability by isolating each operation in its own function. + +## Function Composition Pattern Java Tutorials + +* [Function Composition in Java (Medium)](https://functionalprogramming.medium.com/function-composition-in-java-beaf39426f52) +* [Functional Programming in Java (Baeldung)](https://www.baeldung.com/java-functional-programming) + +## Real-World Applications of Function Composition Pattern in Java + +* Java’s Stream API, where map and filter are composed for data transformations. +* Google Guava’s Function utilities. +* Apache Commons libraries that provide utilities for chaining functions. + +## Benefits and Trade-offs of Function Composition Pattern + +Benefits: + +* Encourages highly modular and reusable code. +* Simplifies complex logic by breaking it down into smaller, testable units. +* Makes the code more expressive and easier to maintain. + +Trade-offs: + +* Excessive chaining can reduce readability if taken too far. +* May introduce performance overhead due to multiple function calls. +* Errors can be harder to trace in a deeply composed function pipeline. + +## Related Java Design Patterns + +* [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/) - Both patterns allow processing to be broken down into a series of steps, but Functional Composition focuses on function composition rather than responsibility delegation. +* [Composite](https://java-design-patterns.com/patterns/composite/): Also deals with combining smaller components, though it is typically about object structure rather than function operations. + +## References and Credits + +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Functional Programming in Java](https://amzn.to/3JUIc5Q) +* [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3QCmGXs) diff --git a/function-composition/etc/function-composition-sequence-diagram.png b/function-composition/etc/function-composition-sequence-diagram.png new file mode 100644 index 000000000000..4d8410d2635d Binary files /dev/null and b/function-composition/etc/function-composition-sequence-diagram.png differ diff --git a/function-composition/etc/function-composition.urm.puml b/function-composition/etc/function-composition.urm.puml new file mode 100644 index 000000000000..79b2a898fd12 --- /dev/null +++ b/function-composition/etc/function-composition.urm.puml @@ -0,0 +1,12 @@ +@startuml +package com.iluwatar.function.composition { + class App { + + App() + + main(args : String[]) {static} + } + class FunctionComposer { + + FunctionComposer() + + composeFunctions(f1 : Function, f2 : Function) : Function {static} + } +} +@enduml \ No newline at end of file diff --git a/function-composition/etc/function.composition.urm.png b/function-composition/etc/function.composition.urm.png new file mode 100644 index 000000000000..53e64608631e Binary files /dev/null and b/function-composition/etc/function.composition.urm.png differ diff --git a/function-composition/etc/function.composition.urm.puml b/function-composition/etc/function.composition.urm.puml new file mode 100644 index 000000000000..5fc3b5c6da37 --- /dev/null +++ b/function-composition/etc/function.composition.urm.puml @@ -0,0 +1,21 @@ +@startuml +skinparam monochrome true + +participant "App" as App +participant "FunctionComposer" as Composer +participant "Function" as F1 + +create F1 +App -> F1 : func1 = x -> x * 2 +create F1 +App -> F1 : func2 = x -> x * x + +App -> Composer : func1, func2 +activate Composer +Composer -> F1 : func1.andThen(func2) +deactivate Composer +activate F1 +F1 -> App : composedFunction +deactivate F1 + +@enduml \ No newline at end of file diff --git a/function-composition/pom.xml b/function-composition/pom.xml new file mode 100644 index 000000000000..abf504b2979d --- /dev/null +++ b/function-composition/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + function-composition + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + App + + + + + + + + + \ No newline at end of file diff --git a/function-composition/src/main/java/com/iluwatar/function/composition/App.java b/function-composition/src/main/java/com/iluwatar/function/composition/App.java new file mode 100644 index 000000000000..c5551f4f9575 --- /dev/null +++ b/function-composition/src/main/java/com/iluwatar/function/composition/App.java @@ -0,0 +1,49 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.function.composition; + +import java.util.function.Function; +import lombok.extern.slf4j.Slf4j; + +/** Main application class to demonstrate the use of function composition. */ +@Slf4j +public class App { + + /** + * Main method to demonstrate function composition using FunctionComposer. + * + * @param args command line arguments (not used) + */ + public static void main(String[] args) { + Function timesTwo = x -> x * 2; + Function square = x -> x * x; + + Function composedFunction = + FunctionComposer.composeFunctions(timesTwo, square); + + int result = composedFunction.apply(3); + LOGGER.info("Result of composing 'timesTwo' and 'square' functions applied to 3 is: " + result); + } +} diff --git a/function-composition/src/main/java/com/iluwatar/function/composition/FunctionComposer.java b/function-composition/src/main/java/com/iluwatar/function/composition/FunctionComposer.java new file mode 100644 index 000000000000..c440ae759a20 --- /dev/null +++ b/function-composition/src/main/java/com/iluwatar/function/composition/FunctionComposer.java @@ -0,0 +1,49 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.function.composition; + +import java.util.function.Function; + +/** + * Class for composing functions using the Function Composition pattern. Provides a static method to + * compose two functions using the 'andThen' method. + */ +public class FunctionComposer { + + private FunctionComposer() {} + + /** + * Composes two functions where the output of the first function becomes the input of the second + * function. + * + * @param f1 the first function to apply + * @param f2 the second function to apply after the first + * @return a composed function that applies f1 and then f2 + */ + public static Function composeFunctions( + Function f1, Function f2) { + return f1.andThen(f2); + } +} diff --git a/function-composition/src/test/java/com/iluwatar/function/composition/AppTest.java b/function-composition/src/test/java/com/iluwatar/function/composition/AppTest.java new file mode 100644 index 000000000000..f1640675c761 --- /dev/null +++ b/function-composition/src/test/java/com/iluwatar/function/composition/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.function.composition; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application test */ +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/function-composition/src/test/java/com/iluwatar/function/composition/FunctionComposerTest.java b/function-composition/src/test/java/com/iluwatar/function/composition/FunctionComposerTest.java new file mode 100644 index 000000000000..dbc4f0903236 --- /dev/null +++ b/function-composition/src/test/java/com/iluwatar/function/composition/FunctionComposerTest.java @@ -0,0 +1,96 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.function.composition; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.function.Function; +import org.junit.jupiter.api.Test; + +/** Test class for FunctionComposer. */ +class FunctionComposerTest { + + /** Tests the composition of two functions. */ + @Test + void testComposeFunctions() { + Function timesTwo = x -> x * 2; + Function square = x -> x * x; + + Function composed = FunctionComposer.composeFunctions(timesTwo, square); + + assertEquals(36, composed.apply(3), "Expected output of composed functions is 36"); + } + + /** Tests function composition with identity function. */ + @Test + void testComposeWithIdentity() { + Function identity = Function.identity(); + Function timesThree = x -> x * 3; + + Function composedLeft = + FunctionComposer.composeFunctions(identity, timesThree); + Function composedRight = + FunctionComposer.composeFunctions(timesThree, identity); + + assertEquals( + 9, composedLeft.apply(3), "Composition with identity on the left should be the same"); + assertEquals( + 9, composedRight.apply(3), "Composition with identity on the right should be the same"); + } + + /** Tests function composition resulting in zero. */ + @Test + void testComposeToZero() { + Function multiply = x -> x * 10; + Function toZero = x -> 0; + + Function composed = FunctionComposer.composeFunctions(multiply, toZero); + + assertEquals( + 0, composed.apply(5), "Expected output of function composition leading to zero is 0"); + } + + /** Tests the composition with a negative function. */ + @Test + void testComposeNegative() { + Function negate = x -> -x; + Function square = x -> x * x; + + Function composed = FunctionComposer.composeFunctions(negate, square); + + assertEquals(9, composed.apply(3), "Expected square of negative number to be positive"); + } + + /** Tests the composition of functions that cancel each other out. */ + @Test + void testComposeInverseFunctions() { + Function timesTwo = x -> x * 2; + Function half = x -> x / 2; + + Function composed = FunctionComposer.composeFunctions(timesTwo, half); + + assertEquals(5, composed.apply(5), "Expect the functions to cancel each other out"); + } +} diff --git a/game-loop/README.md b/game-loop/README.md new file mode 100644 index 000000000000..3de2804a8dc7 --- /dev/null +++ b/game-loop/README.md @@ -0,0 +1,342 @@ +--- +title: "Game Loop Pattern in Java: Mastering Smooth Game Mechanics" +shortTitle: Game Loop +description: "Learn about the Game Loop design pattern, its implementation in Java, and how it ensures smooth gameplay by continuously updating game state, processing inputs, and rendering. Ideal for real-time simulations and gaming." +category: Behavioral +language: en +tag: + - Concurrency + - Event-driven + - Game programming + - Performance +--- + +## Also known as + +* Game Cycle +* Main Game Loop + +## Intent of Game Loop Design Pattern + +The Game Loop design pattern is essential for creating smooth and interactive gaming experiences by facilitating continuous game execution. Each loop cycle processes input, updates the game state, and renders the game state to the screen, ensuring consistent performance across all hardware setups. + +## Detailed Explanation of Game Loop Pattern with Real-World Examples + +Real-world example + +> A practical analogy of the Game Loop can be seen in an amusement park ride, like a roller coaster. Similar to how the ride operates in a loop, updating its state and ensuring smooth operation, the Game Loop continuously processes inputs and updates the game state for a seamless gaming experience. The roller coaster operates in a continuous loop, where the state of the ride (the position and speed of the coaster) is continuously updated while the ride is running. The control system of the roller coaster ensures that the cars move smoothly along the track, adjusting speeds, and handling the ride's safety systems in real-time. Just like the game loop, this control system repeatedly processes inputs (such as the current speed and position), updates the state, and triggers outputs (like adjusting the brakes or accelerating the cars) to maintain the desired operation throughout the duration of the ride. + +In plain words + +> Game Loop pattern ensures that game time progresses in equal speed in all different hardware setups. + +Wikipedia says + +> The central component of any game, from a programming standpoint, is the game loop. The game loop allows the game to run smoothly regardless of a user's input, or lack thereof. + +Flowchart + +![Game Loop flowchart](./etc/game-loop-flowchart.png) + +## Programmatic Example of Game Loop Pattern in Java + +In our Java example, we illustrate a simple game loop controlling a bullet's movement, updating its position, ensuring smooth rendering, and responding to user inputs. The Game Loop is the main process driving all game rendering threads, present in all modern games. It handles input processing, internal status updates, rendering, AI, and other processes. Starting with a simple `Bullet` class, we demonstrate the movement of bullets in our game, focusing on their 1-dimensional position for demonstration purposes. + +```java +public class Bullet { + + private float position; + + public Bullet() { + position = 0.0f; + } + + public float getPosition() { + return position; + } + + public void setPosition(float position) { + this.position = position; + } +} +``` + +`GameController` is responsible for moving objects in the game, including the aforementioned bullet. + +```java +public class GameController { + + protected final Bullet bullet; + + public GameController() { + bullet = new Bullet(); + } + + public void moveBullet(float offset) { + var currentPosition = bullet.getPosition(); + bullet.setPosition(currentPosition + offset); + } + + public float getBulletPosition() { + return bullet.getPosition(); + } +} +``` + +Now we introduce the game loop. Actually, in this demo we have 3 different game loops. Let's see the base class `GameLoop` first. + +```java +public enum GameStatus { + + RUNNING, STOPPED +} + +public abstract class GameLoop { + + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + + protected volatile GameStatus status; + + protected GameController controller; + + private Thread gameThread; + + public GameLoop() { + controller = new GameController(); + status = GameStatus.STOPPED; + } + + public void run() { + status = GameStatus.RUNNING; + gameThread = new Thread(this::processGameLoop); + gameThread.start(); + } + + public void stop() { + status = GameStatus.STOPPED; + } + + public boolean isGameRunning() { + return status == GameStatus.RUNNING; + } + + protected void processInput() { + try { + var lag = new Random().nextInt(200) + 50; + Thread.sleep(lag); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + + protected void render() { + var position = controller.getBulletPosition(); + logger.info("Current bullet position: " + position); + } + + protected abstract void processGameLoop(); +} +``` + +Here's the first game loop implementation, `FrameBasedGameLoop`: + +```java +public class FrameBasedGameLoop extends GameLoop { + + @Override + protected void processGameLoop() { + while (isGameRunning()) { + processInput(); + update(); + render(); + } + } + + protected void update() { + controller.moveBullet(0.5f); + } +} +``` + +Here's the second game loop implementation, `FixedStepGameLoop`: + +```java +public class FixedStepGameLoop extends GameLoop { + + /** + * 20 ms per frame = 50 FPS. + */ + private static final long MS_PER_FRAME = 20; + + @Override + protected void processGameLoop() { + var previousTime = System.currentTimeMillis(); + var lag = 0L; + while (isGameRunning()) { + var currentTime = System.currentTimeMillis(); + var elapsedTime = currentTime - previousTime; + previousTime = currentTime; + lag += elapsedTime; + + processInput(); + + while (lag >= MS_PER_FRAME) { + update(); + lag -= MS_PER_FRAME; + } + + render(); + } + } + + protected void update() { + controller.moveBullet(0.5f * MS_PER_FRAME / 1000); + } +} +``` + +And the third game loop implementation, `VariableStepGameLoop`: + +```java +public class VariableStepGameLoop extends GameLoop { + + @Override + protected void processGameLoop() { + var lastFrameTime = System.currentTimeMillis(); + while (isGameRunning()) { + processInput(); + var currentFrameTime = System.currentTimeMillis(); + var elapsedTime = currentFrameTime - lastFrameTime; + update(elapsedTime); + lastFrameTime = currentFrameTime; + render(); + } + } + + protected void update(Long elapsedTime) { + controller.moveBullet(0.5f * elapsedTime / 1000); + } + +} +``` + +Finally, we show all the game loops in action. + +```java +public static void main(String[] args) { + + try { + LOGGER.info("Start frame-based game loop:"); + var frameBasedGameLoop = new FrameBasedGameLoop(); + frameBasedGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + frameBasedGameLoop.stop(); + LOGGER.info("Stop frame-based game loop."); + + LOGGER.info("Start variable-step game loop:"); + var variableStepGameLoop = new VariableStepGameLoop(); + variableStepGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + variableStepGameLoop.stop(); + LOGGER.info("Stop variable-step game loop."); + + LOGGER.info("Start fixed-step game loop:"); + var fixedStepGameLoop = new FixedStepGameLoop(); + fixedStepGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + fixedStepGameLoop.stop(); + LOGGER.info("Stop variable-step game loop."); + + } catch (InterruptedException e) { + LOGGER.error(e.getMessage()); + } +} +``` + +Program output: + +```java +Start frame-based game loop: +Current bullet position: 0.5 +Current bullet position: 1.0 +Current bullet position: 1.5 +Current bullet position: 2.0 +Current bullet position: 2.5 +Current bullet position: 3.0 +Current bullet position: 3.5 +Current bullet position: 4.0 +Current bullet position: 4.5 +Current bullet position: 5.0 +Current bullet position: 5.5 +Current bullet position: 6.0 +Stop frame-based game loop. +Start variable-step game loop: +Current bullet position: 6.5 +Current bullet position: 0.038 +Current bullet position: 0.084 +Current bullet position: 0.145 +Current bullet position: 0.1805 +Current bullet position: 0.28 +Current bullet position: 0.32 +Current bullet position: 0.42549998 +Current bullet position: 0.52849996 +Current bullet position: 0.57799995 +Current bullet position: 0.63199997 +Current bullet position: 0.672 +Current bullet position: 0.778 +Current bullet position: 0.848 +Current bullet position: 0.8955 +Current bullet position: 0.9635 +Stop variable-step game loop. +Start fixed-step game loop: +Current bullet position: 0.0 +Current bullet position: 1.086 +Current bullet position: 0.059999995 +Current bullet position: 0.12999998 +Current bullet position: 0.24000004 +Current bullet position: 0.33999994 +Current bullet position: 0.36999992 +Current bullet position: 0.43999985 +Current bullet position: 0.5399998 +Current bullet position: 0.65999967 +Current bullet position: 0.68999964 +Current bullet position: 0.7299996 +Current bullet position: 0.79999954 +Current bullet position: 0.89999944 +Current bullet position: 0.98999935 +Stop variable-step game loop. +``` + +## When to Use the Game Loop Pattern in Java + +The Game Loop pattern is perfect for real-time simulations and gaming where continuous state updates and smooth frame rates are critical. + +## Real-World Applications of Game Loop Pattern in Java + +* Video games, both 2D and 3D, across various platforms. +* Real-time simulations that require a steady frame rate for updating logic and rendering. + +## Benefits and Trade-offs of Game Loop Pattern + +Benefits: + +* Ensures the game progresses smoothly and deterministically. +* Facilitates synchronization between the game state, user input, and screen rendering. +* Provides a clear structure for the game developers to manage game dynamics and timing. + +Trade-offs: + +* Can lead to performance issues if the loop is not well-managed, especially in resource-intensive updates or rendering. +* Difficulty in managing varying frame rates across different hardware. + +## Related Java Design Patterns + +* [State](https://java-design-patterns.com/patterns/state/): Often used within a game loop to manage different states of the game (e.g., menu, playing, paused). The relationship lies in managing the state-specific behavior and transitions smoothly within the game loop. +* [Observer](https://java-design-patterns.com/patterns/observer/): Useful in a game loop for event handling, where game entities can subscribe to and react to events (e.g., collision, scoring). + +## References and Credits + +* [Game Programming Patterns](https://amzn.to/3K96fOn) +* [Game Engine Architecture, Third Edition](https://amzn.to/3VgB4av) +* [Real-Time Collision Detection](https://amzn.to/3W9Jj8T) +* [Game Programming Patterns - Game Loop](http://gameprogrammingpatterns.com/game-loop.html) diff --git a/game-loop/etc/game-loop-flowchart.png b/game-loop/etc/game-loop-flowchart.png new file mode 100644 index 000000000000..a3e73f75ed8b Binary files /dev/null and b/game-loop/etc/game-loop-flowchart.png differ diff --git a/game-loop/etc/game-loop.urm.png b/game-loop/etc/game-loop.urm.png new file mode 100644 index 000000000000..b7ffc11d2659 Binary files /dev/null and b/game-loop/etc/game-loop.urm.png differ diff --git a/game-loop/etc/game-loop.urm.puml b/game-loop/etc/game-loop.urm.puml new file mode 100644 index 000000000000..d0704096f11e --- /dev/null +++ b/game-loop/etc/game-loop.urm.puml @@ -0,0 +1,63 @@ +@startuml +package com.iluwatar.gameloop { + class App { + - GAME_LOOP_DURATION_TIME : int {static} + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Bullet { + - position : float + + Bullet() + + getPosition() : float + + setPosition(position : float) + } + class FixedStepGameLoop { + - MS_PER_FRAME : long {static} + + FixedStepGameLoop() + # processGameLoop() + # update() + } + class FrameBasedGameLoop { + + FrameBasedGameLoop() + # processGameLoop() + # update() + } + class GameController { + # bullet : Bullet + + GameController() + + getBulletPosition() : float + + moveBullet(offset : float) + } + abstract class GameLoop { + # controller : GameController + - gameThread : Thread + # logger : Logger + # status : GameStatus + + GameLoop() + + isGameRunning() : boolean + # processGameLoop() {abstract} + # processInput() + # render() + + run() + + stop() + } + enum GameStatus { + + RUNNING {static} + + STOPPED {static} + + valueOf(name : String) : GameStatus {static} + + values() : GameStatus[] {static} + } + class VariableStepGameLoop { + + VariableStepGameLoop() + # processGameLoop() + # update(elapsedTime : Long) + } +} +GameLoop --> "-status" GameStatus +GameController --> "-bullet" Bullet +GameLoop --> "-controller" GameController +FixedStepGameLoop --|> GameLoop +FrameBasedGameLoop --|> GameLoop +VariableStepGameLoop --|> GameLoop +@enduml \ No newline at end of file diff --git a/game-loop/pom.xml b/game-loop/pom.xml new file mode 100644 index 000000000000..1ef70a6509b9 --- /dev/null +++ b/game-loop/pom.xml @@ -0,0 +1,70 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + game-loop + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.gameloop.App + + + + + + + + + diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/App.java b/game-loop/src/main/java/com/iluwatar/gameloop/App.java new file mode 100644 index 000000000000..76ed426e6a3c --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/App.java @@ -0,0 +1,73 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +import lombok.extern.slf4j.Slf4j; + +/** + * A game loop runs continuously during gameplay. Each turn of the loop, it processes user input + * without blocking, updates the game state, and renders the game. It tracks the passage of time to + * control the rate of gameplay. + */ +@Slf4j +public class App { + + /** Each type of game loop will run for 2 seconds. */ + private static final int GAME_LOOP_DURATION_TIME = 2000; + + /** + * Program entry point. + * + * @param args runtime arguments + */ + public static void main(String[] args) { + + try { + LOGGER.info("Start frame-based game loop:"); + var frameBasedGameLoop = new FrameBasedGameLoop(); + frameBasedGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + frameBasedGameLoop.stop(); + LOGGER.info("Stop frame-based game loop."); + + LOGGER.info("Start variable-step game loop:"); + var variableStepGameLoop = new VariableStepGameLoop(); + variableStepGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + variableStepGameLoop.stop(); + LOGGER.info("Stop variable-step game loop."); + + LOGGER.info("Start fixed-step game loop:"); + var fixedStepGameLoop = new FixedStepGameLoop(); + fixedStepGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + fixedStepGameLoop.stop(); + LOGGER.info("Stop variable-step game loop."); + + } catch (InterruptedException e) { + LOGGER.error(e.getMessage()); + } + } +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.java b/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.java new file mode 100644 index 000000000000..00b1a8b773b7 --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +import lombok.Getter; +import lombok.Setter; + +/** Bullet object class. */ +public class Bullet { + + @Getter @Setter private float position; + + public Bullet() { + position = 0.0f; + } +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java new file mode 100644 index 000000000000..58c4e0dfdca2 --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +/** + * For fixed-step game loop, a certain amount of real time has elapsed since the last turn of the + * game loop. This is how much game time need to be simulated for the game’s “now” to catch up with + * the player’s. + */ +public class FixedStepGameLoop extends GameLoop { + + /** 20 ms per frame = 50 FPS. */ + private static final long MS_PER_FRAME = 20; + + @Override + protected void processGameLoop() { + var previousTime = System.currentTimeMillis(); + var lag = 0L; + while (isGameRunning()) { + var currentTime = System.currentTimeMillis(); + var elapsedTime = currentTime - previousTime; + previousTime = currentTime; + lag += elapsedTime; + + processInput(); + + while (lag >= MS_PER_FRAME) { + update(); + lag -= MS_PER_FRAME; + } + + render(); + } + } + + protected void update() { + controller.moveBullet(0.5f * MS_PER_FRAME / 1000); + } +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.java new file mode 100644 index 000000000000..a60eaf547066 --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +/** + * Frame-based game loop is the easiest implementation. The loop always keeps spinning for the + * following three processes: processInput, update and render. The problem with it is you have no + * control over how fast the game runs. On a fast machine, that loop will spin so fast users won’t + * be able to see what’s going on. On a slow machine, the game will crawl. If you have a part of the + * game that’s content-heavy or does more AI or physics, the game will actually play slower there. + */ +public class FrameBasedGameLoop extends GameLoop { + + @Override + protected void processGameLoop() { + while (isGameRunning()) { + processInput(); + update(); + render(); + } + } + + /** + * Each time when update() is invoked, a new frame is created, and the bullet will be moved 0.5f + * away from the current position. + */ + protected void update() { + controller.moveBullet(0.5f); + } +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/GameController.java b/game-loop/src/main/java/com/iluwatar/gameloop/GameController.java new file mode 100644 index 000000000000..872aa8e8ce50 --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/GameController.java @@ -0,0 +1,58 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +/** + * Update and render objects in the game. Here we add a Bullet object to the game system to show how + * the game loop works. + */ +public class GameController { + + protected final Bullet bullet; + + /** Initialize Bullet instance. */ + public GameController() { + bullet = new Bullet(); + } + + /** + * Move bullet position by the provided offset. + * + * @param offset moving offset + */ + public void moveBullet(float offset) { + var currentPosition = bullet.getPosition(); + bullet.setPosition(currentPosition + offset); + } + + /** + * Get current position of the bullet. + * + * @return position of bullet + */ + public float getBulletPosition() { + return bullet.getPosition(); + } +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java new file mode 100644 index 000000000000..0dcdb21f28ea --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java @@ -0,0 +1,90 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +import java.security.SecureRandom; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Abstract class for GameLoop implementation class. */ +public abstract class GameLoop { + + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + + protected volatile GameStatus status; + + protected final GameController controller; + + /** Initialize game status to be stopped. */ + protected GameLoop() { + controller = new GameController(); + status = GameStatus.STOPPED; + } + + /** Run game loop. */ + public void run() { + status = GameStatus.RUNNING; + Thread gameThread = new Thread(this::processGameLoop); + gameThread.start(); + } + + /** Stop game loop. */ + public void stop() { + status = GameStatus.STOPPED; + } + + /** + * Check if game is running or not. + * + * @return {@code true} if the game is running. + */ + public boolean isGameRunning() { + return status == GameStatus.RUNNING; + } + + /** + * Handle any user input that has happened since the last call. In order to simulate the situation + * in real-life game, here we add a random time lag. The time lag ranges from 50 ms to 250 ms. + */ + protected void processInput() { + try { + var lag = new SecureRandom().nextInt(200) + 50; + Thread.sleep(lag); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + /* Clean up whatever needs to be handled before interrupting */ + Thread.currentThread().interrupt(); + } + } + + /** Render game frames to screen. Here we print bullet position to simulate this process. */ + protected void render() { + var position = controller.getBulletPosition(); + logger.info("Current bullet position: {}", position); + } + + /** execute game loop logic. */ + protected abstract void processGameLoop(); +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java b/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java new file mode 100644 index 000000000000..316bb83d95d3 --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java @@ -0,0 +1,31 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +/** Enum class for game status. */ +public enum GameStatus { + RUNNING, + STOPPED +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java new file mode 100644 index 000000000000..9c7c0f348c9c --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +/** + * The variable-step game loop chooses a time step to advance based on how much real time passed + * since the last frame. The longer the frame takes, the bigger steps the game takes. It always + * keeps up with real time because it will take bigger and bigger steps to get there. + */ +public class VariableStepGameLoop extends GameLoop { + + @Override + protected void processGameLoop() { + var lastFrameTime = System.currentTimeMillis(); + while (isGameRunning()) { + processInput(); + var currentFrameTime = System.currentTimeMillis(); + var elapsedTime = currentFrameTime - lastFrameTime; + update(elapsedTime); + lastFrameTime = currentFrameTime; + render(); + } + } + + protected void update(Long elapsedTime) { + controller.moveBullet(0.5f * elapsedTime / 1000); + } +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java new file mode 100644 index 000000000000..9565030373bc --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** App unit test class. */ +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.java new file mode 100644 index 000000000000..fdcd8a1e3cd8 --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** FixedStepGameLoop unit test class. */ +class FixedStepGameLoopTest { + + private FixedStepGameLoop gameLoop; + + @BeforeEach + void setup() { + gameLoop = new FixedStepGameLoop(); + } + + @AfterEach + void tearDown() { + gameLoop = null; + } + + @Test + void testUpdate() { + gameLoop.update(); + assertEquals(0.01f, gameLoop.controller.getBulletPosition(), 0); + } +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.java new file mode 100644 index 000000000000..ea2f80646dfe --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** FrameBasedGameLoop unit test class. */ +class FrameBasedGameLoopTest { + + private FrameBasedGameLoop gameLoop; + + @BeforeEach + void setup() { + gameLoop = new FrameBasedGameLoop(); + } + + @AfterEach + void tearDown() { + gameLoop = null; + } + + @Test + void testUpdate() { + gameLoop.update(); + assertEquals(0.5f, gameLoop.controller.getBulletPosition(), 0); + } +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.java new file mode 100644 index 000000000000..c5855a88ea12 --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class GameControllerTest { + + private GameController controller; + + @BeforeEach + void setup() { + controller = new GameController(); + } + + @AfterEach + void tearDown() { + controller = null; + } + + @Test + void testMoveBullet() { + controller.moveBullet(1.5f); + assertEquals(1.5f, controller.bullet.getPosition(), 0); + } + + @Test + void testGetBulletPosition() { + assertEquals(controller.bullet.getPosition(), controller.getBulletPosition(), 0); + } +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java new file mode 100644 index 000000000000..c7dddd372bd5 --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java @@ -0,0 +1,72 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** GameLoop unit test class. */ +class GameLoopTest { + + private GameLoop gameLoop; + + /** Create mock implementation of GameLoop. */ + @BeforeEach + void setup() { + gameLoop = + new GameLoop() { + @Override + protected void processGameLoop() { + throw new UnsupportedOperationException("Not supported yet."); + } + }; + } + + @AfterEach + void tearDown() { + gameLoop = null; + } + + @Test + void testRun() { + gameLoop.run(); + Assertions.assertEquals(GameStatus.RUNNING, gameLoop.status); + } + + @Test + void testStop() { + gameLoop.stop(); + Assertions.assertEquals(GameStatus.STOPPED, gameLoop.status); + } + + @Test + void testIsGameRunning() { + assertFalse(gameLoop.isGameRunning()); + } +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.java new file mode 100644 index 000000000000..b528c145c9b0 --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gameloop; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** VariableStepGameLoop unit test class. */ +class VariableStepGameLoopTest { + + private VariableStepGameLoop gameLoop; + + @BeforeEach + void setup() { + gameLoop = new VariableStepGameLoop(); + } + + @AfterEach + void tearDown() { + gameLoop = null; + } + + @Test + void testUpdate() { + gameLoop.update(20L); + Assertions.assertEquals(0.01f, gameLoop.controller.getBulletPosition(), 0); + } +} diff --git a/gateway/README.md b/gateway/README.md new file mode 100644 index 000000000000..79c1a24f1992 --- /dev/null +++ b/gateway/README.md @@ -0,0 +1,170 @@ +--- +title: "Gateway Pattern in Java: Simplifying External System Integration" +shortTitle: Gateway +description: "Discover the Gateway design pattern in Java, a powerful technique for integrating remote services and APIs. Learn how to encapsulate interactions and simplify your application architecture with practical examples and real-world use cases." +category: Integration +language: en +tag: + - API design + - Data access + - Decoupling + - Enterprise patterns +--- + +## Also known as + +* Service Gateway + +## Intent of Gateway Design Pattern + +The Gateway design pattern is a crucial concept in Java design patterns for simplifying API integration and interactions with remote services. It provides a unified and simplified interface to external systems, enhancing the maintainability and architecture of applications. By encapsulating these interactions, the Gateway pattern ensures loose coupling and promotes a more modular and scalable software design, making it essential for robust and efficient application development. + +## Detailed Explanation of Gateway Pattern with Real-World Examples + +Real-world example + +> In real-world applications, companies often need to interact with multiple external systems. The Gateway design pattern provides a unified interface for such interactions, handling protocol translation and data transformation, thereby ensuring loose coupling between the internal and external components. ' +> +> Consider a logistics company that uses multiple third-party services for various operations, such as shipping, inventory management, and customer notifications. Each of these services has its own API with different protocols and data formats. To simplify the interaction, the company implements a Gateway design pattern. This gateway acts as a unified interface for all third-party service interactions, allowing the company's internal systems to communicate with these services seamlessly. The gateway handles the translation of protocols, data transformation, and routing of requests, ensuring that the internal systems remain decoupled from the specifics of each external service. This setup improves maintainability and scalability while providing a single point of control for external communications. + +In plain words + +> Gateway can provide an interface which lets internal system to utilize external service. + +Wikipedia says + +> A server that acts as an API front-end, receives API requests, enforces throttling and security policies, passes requests to the back-end service and then passes the response back to the requester. + +Sequence diagram + +![Gateway sequence diagram](./etc/gateway-sequence-diagram.png) + +## Programmatic Example of Gateway Pattern in Java + +First, we define a `Gateway` interface. This interface represents the contract for our external services. Each service that we want to interact with will implement this interface. + +```java +public interface Gateway { + void execute(); +} +``` + +Next, we create our external services. These are the services that our application needs to interact with. Each service implements the `Gateway` interface and provides its own implementation of the `execute` method. + +```java +public class ExternalServiceA implements Gateway { + @Override + public void execute() { + // Implementation for ExternalServiceA + } +} +``` + +```java +public class ExternalServiceB implements Gateway { + @Override + public void execute() { + // Implementation for ExternalServiceB + } +} +``` + +```java +public class ExternalServiceC implements Gateway { + @Override + public void execute() { + // Implementation for ExternalServiceC + } +} +``` + +We then create a `GatewayFactory` class. This class maintains a registry of all available gateways. It provides methods to register a new gateway and to retrieve a gateway by its key. + +```java +public class GatewayFactory { + private Map gateways = new HashMap<>(); + + public void registerGateway(String key, Gateway gateway) { + gateways.put(key, gateway); + } + + public Gateway getGateway(String key) { + return gateways.get(key); + } +} +``` + +Finally, we have our main application. The application uses the `GatewayFactory` to register and retrieve gateways. It then uses these gateways to interact with the external services. + +```java +public class App { + public static void main(String[] args) throws Exception { + GatewayFactory gatewayFactory = new GatewayFactory(); + + // Register different gateways + gatewayFactory.registerGateway("ServiceA", new ExternalServiceA()); + gatewayFactory.registerGateway("ServiceB", new ExternalServiceB()); + gatewayFactory.registerGateway("ServiceC", new ExternalServiceC()); + + // Use an executor service for execution + Gateway serviceA = gatewayFactory.getGateway("ServiceA"); + Gateway serviceB = gatewayFactory.getGateway("ServiceB"); + Gateway serviceC = gatewayFactory.getGateway("ServiceC"); + + // Execute external services + try { + serviceA.execute(); + serviceB.execute(); + serviceC.execute(); + } catch (ThreadDeath e) { + LOGGER.info("Interrupted!" + e); + throw e; + } + } +} +``` + +Running the example produces the following output. + +``` +09:24:44.030 [main] INFO com.iluwatar.gateway.ExternalServiceA -- Executing Service A +09:24:45.038 [main] INFO com.iluwatar.gateway.ExternalServiceB -- Executing Service B +09:24:46.043 [main] INFO com.iluwatar.gateway.ExternalServiceC -- Executing Service C +``` + +This example demonstrates how the Gateway design pattern can be used to simplify the interaction with multiple external services. Each service is encapsulated behind a common interface, and the application interacts with this interface rather than directly with the services. This reduces coupling and makes the application easier to maintain and extend. + +## When to Use the Gateway Pattern in Java + +Use the Gateway pattern when integrating with remote services or APIs. It is particularly beneficial in microservices architecture to manage communication through well-defined interfaces. + +## Real-World Applications of Gateway Pattern in Java + +* API Gateways in Microservices: Acts as an intermediary that processes incoming requests from clients, directing them to appropriate services within a microservices architecture. +* Database Gateways: Provides a unified interface to access data from various database systems, hiding the specifics of database querying and data retrieval. + +## Benefits and Trade-offs of Gateway Pattern + +Benefits: + +* The Gateway design pattern reduces complexity by abstracting the details of external APIs and services behind a simpler interface. +* Promotes loose coupling between the application and its dependencies on external systems. +* Makes the system easier to test and maintain. + +Trade-offs: + +* Introduces an additional layer that could potentially impact performance. +* Requires careful design to avoid creating a monolithic gateway that becomes a bottleneck. + +## Related Java Design Patterns + +* [Facade](https://java-design-patterns.com/patterns/facade/): Similar to Gateway in abstracting complex subsystems, but Gateway specifically targets external or remote interfaces. +* [Adapter](https://java-design-patterns.com/patterns/adapter/): While both patterns provide a different interface to a subsystem, Gateway focuses more on networked data sources and services. +* [Proxy](https://java-design-patterns.com/patterns/proxy/): Often used together, as both can control and manage access to another object, but Gateway specifically deals with external services. +* [API Gateway](https://java-design-patterns.com/patterns/microservices-api-gateway/): Often considered a specialization of the Gateway pattern, it specifically manages API requests and routes them to the appropriate services within a backend system. + +## References and Credits + +* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) +* [Gateway (Martin Fowler)](https://martinfowler.com/articles/gateway-pattern.html) diff --git a/gateway/etc/gateway-sequence-diagram.png b/gateway/etc/gateway-sequence-diagram.png new file mode 100644 index 000000000000..167dff8ec690 Binary files /dev/null and b/gateway/etc/gateway-sequence-diagram.png differ diff --git a/gateway/etc/gateway.urm.png b/gateway/etc/gateway.urm.png new file mode 100644 index 000000000000..2d8ad6c9a8f8 Binary files /dev/null and b/gateway/etc/gateway.urm.png differ diff --git a/gateway/etc/gateway.urm.puml b/gateway/etc/gateway.urm.puml new file mode 100644 index 000000000000..3439ca17f6ae --- /dev/null +++ b/gateway/etc/gateway.urm.puml @@ -0,0 +1,43 @@ +@startuml GatewayPattern +package com.iluwatar.gateway{ +class App { + +main(args: String[]): void +} + +class GatewayFactory { + -gateways: Map + +registerGateway(key: String, gateway: Gateway): void + +getGateway(key: String): Gateway +} + +interface Gateway { + {abstract} +execute(): void +} + +class ExternalServiceA { + +execute(): void +} + +class ExternalServiceB { + +execute(): void +} + +class ExternalServiceC { + +execute(): void + +error(): void +} + +App --> GatewayFactory : Uses + + +GatewayFactory --> Gateway : Creates + +GatewayFactory --> ExternalServiceA : Registers +GatewayFactory --> ExternalServiceB : Registers +GatewayFactory --> ExternalServiceC : Registers + +ExternalServiceA --> Gateway : Implements +ExternalServiceB --> Gateway : Implements +ExternalServiceC --> Gateway : Implements + +@enduml diff --git a/gateway/pom.xml b/gateway/pom.xml new file mode 100644 index 000000000000..4fbde9cce9aa --- /dev/null +++ b/gateway/pom.xml @@ -0,0 +1,71 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + jar + gateway + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.gateway.App + + + + + + + + + diff --git a/gateway/src/main/java/com/iluwatar/gateway/App.java b/gateway/src/main/java/com/iluwatar/gateway/App.java new file mode 100644 index 000000000000..5034748b20ec --- /dev/null +++ b/gateway/src/main/java/com/iluwatar/gateway/App.java @@ -0,0 +1,68 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gateway; + +import lombok.extern.slf4j.Slf4j; + +/** + * the Gateway design pattern is a structural design pattern that provides a unified interface to a + * set of interfaces in a subsystem. It involves creating a Gateway interface that serves as a + * common entry point for interacting with various services, and concrete implementations of this + * interface for different external services. + * + *

    In this example, GateFactory is the factory class, and it provides a method to create + * different kinds of external services. ExternalServiceA, B, and C are virtual implementations of + * the external services. Each service provides its own implementation of the execute() method. The + * Gateway interface is the common interface for all external services. The App class serves as the + * main entry point for the application implementing the Gateway design pattern. Through the Gateway + * interface, the App class could call each service with much less complexity. + */ +@Slf4j +public class App { + /** Simulate an application calling external services. */ + public static void main(String[] args) throws Exception { + GatewayFactory gatewayFactory = new GatewayFactory(); + + // Register different gateways + gatewayFactory.registerGateway("ServiceA", new ExternalServiceA()); + gatewayFactory.registerGateway("ServiceB", new ExternalServiceB()); + gatewayFactory.registerGateway("ServiceC", new ExternalServiceC()); + + // Use an executor service for execution + Gateway serviceA = gatewayFactory.getGateway("ServiceA"); + Gateway serviceB = gatewayFactory.getGateway("ServiceB"); + Gateway serviceC = gatewayFactory.getGateway("ServiceC"); + + // Execute external services + try { + serviceA.execute(); + serviceB.execute(); + serviceC.execute(); + } catch (ThreadDeath e) { + LOGGER.info("Interrupted!" + e); + throw e; + } + } +} diff --git a/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java new file mode 100644 index 000000000000..892dc5d7b755 --- /dev/null +++ b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gateway; + +import lombok.extern.slf4j.Slf4j; + +/** ExternalServiceA is one of external services. */ +@Slf4j +class ExternalServiceA implements Gateway { + @Override + public void execute() throws Exception { + LOGGER.info("Executing Service A"); + // Simulate a time-consuming task + Thread.sleep(1000); + } +} diff --git a/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceB.java b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceB.java new file mode 100644 index 000000000000..dcd931ffb1f2 --- /dev/null +++ b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceB.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gateway; + +import lombok.extern.slf4j.Slf4j; + +/** ExternalServiceB is one of external services. */ +@Slf4j +class ExternalServiceB implements Gateway { + @Override + public void execute() throws Exception { + LOGGER.info("Executing Service B"); + // Simulate a time-consuming task + Thread.sleep(1000); + } +} diff --git a/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceC.java b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceC.java new file mode 100644 index 000000000000..b01d79e37968 --- /dev/null +++ b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceC.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gateway; + +import lombok.extern.slf4j.Slf4j; + +/** ExternalServiceC is one of external services. */ +@Slf4j +class ExternalServiceC implements Gateway { + @Override + public void execute() throws Exception { + LOGGER.info("Executing Service C"); + // Simulate a time-consuming task + Thread.sleep(1000); + } + + public void error() { + // Simulate an exception + throw new RuntimeException("Service C encountered an error"); + } +} diff --git a/gateway/src/main/java/com/iluwatar/gateway/Gateway.java b/gateway/src/main/java/com/iluwatar/gateway/Gateway.java new file mode 100644 index 000000000000..36627681c859 --- /dev/null +++ b/gateway/src/main/java/com/iluwatar/gateway/Gateway.java @@ -0,0 +1,30 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gateway; + +/** Service interface. */ +interface Gateway { + void execute() throws Exception; +} diff --git a/gateway/src/main/java/com/iluwatar/gateway/GatewayFactory.java b/gateway/src/main/java/com/iluwatar/gateway/GatewayFactory.java new file mode 100644 index 000000000000..2501e5f72183 --- /dev/null +++ b/gateway/src/main/java/com/iluwatar/gateway/GatewayFactory.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gateway; + +import java.util.HashMap; +import java.util.Map; + +/** + * The "GatewayFactory" class is responsible for providing different external services in this + * Gateway design pattern example. It allows clients to register and retrieve specific gateways + * based on unique keys. + */ +public class GatewayFactory { + private Map gateways = new HashMap<>(); + + public void registerGateway(String key, Gateway gateway) { + gateways.put(key, gateway); + } + + public Gateway getGateway(String key) { + return gateways.get(key); + } +} diff --git a/gateway/src/test/java/com/iluwatar/gateway/AppTest.java b/gateway/src/test/java/com/iluwatar/gateway/AppTest.java new file mode 100644 index 000000000000..0776926edd38 --- /dev/null +++ b/gateway/src/test/java/com/iluwatar/gateway/AppTest.java @@ -0,0 +1,111 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gateway; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.concurrent.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class AppTest { + + private GatewayFactory gatewayFactory; + private ExecutorService executorService; + + @BeforeEach + void setUp() { + gatewayFactory = new GatewayFactory(); + executorService = Executors.newFixedThreadPool(2); + gatewayFactory.registerGateway("ServiceA", new ExternalServiceA()); + gatewayFactory.registerGateway("ServiceB", new ExternalServiceB()); + gatewayFactory.registerGateway("ServiceC", new ExternalServiceC()); + } + + @Test + void testServiceAExecution() throws InterruptedException, ExecutionException { + // Test Service A execution + Future serviceAFuture = + executorService.submit( + () -> { + try { + Gateway serviceA = gatewayFactory.getGateway("ServiceA"); + serviceA.execute(); + } catch (Exception e) { + fail("Service A should not throw an exception."); + } + }); + + // Wait for Service A to complete + serviceAFuture.get(); + } + + @Test + void testServiceCExecutionWithException() throws InterruptedException, ExecutionException { + // Test Service B execution with an exception + Future serviceBFuture = + executorService.submit( + () -> { + try { + Gateway serviceB = gatewayFactory.getGateway("ServiceB"); + serviceB.execute(); + } catch (Exception e) { + fail("Service B should not throw an exception."); + } + }); + + // Wait for Service B to complete + serviceBFuture.get(); + } + + @Test + void testServiceCExecution() throws InterruptedException, ExecutionException { + // Test Service C execution + Future serviceCFuture = + executorService.submit( + () -> { + try { + Gateway serviceC = gatewayFactory.getGateway("ServiceC"); + serviceC.execute(); + } catch (Exception e) { + fail("Service C should not throw an exception."); + } + }); + + // Wait for Service C to complete + serviceCFuture.get(); + } + + @Test + void testServiceCError() { + try { + ExternalServiceC serviceC = (ExternalServiceC) gatewayFactory.getGateway("ServiceC"); + serviceC.error(); + fail("Service C should throw an exception."); + } catch (Exception e) { + assertEquals("Service C encountered an error", e.getMessage()); + } + } +} diff --git a/gateway/src/test/java/com/iluwatar/gateway/ServiceFactoryTest.java b/gateway/src/test/java/com/iluwatar/gateway/ServiceFactoryTest.java new file mode 100644 index 000000000000..f5e216cb2781 --- /dev/null +++ b/gateway/src/test/java/com/iluwatar/gateway/ServiceFactoryTest.java @@ -0,0 +1,92 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.gateway; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ServiceFactoryTest { + + private GatewayFactory gatewayFactory; + private ExecutorService executorService; + + @BeforeEach + void setUp() { + gatewayFactory = new GatewayFactory(); + executorService = Executors.newFixedThreadPool(2); + gatewayFactory.registerGateway("ServiceA", new ExternalServiceA()); + gatewayFactory.registerGateway("ServiceB", new ExternalServiceB()); + gatewayFactory.registerGateway("ServiceC", new ExternalServiceC()); + } + + @Test + void testGatewayFactoryRegistrationAndRetrieval() { + Gateway serviceA = gatewayFactory.getGateway("ServiceA"); + Gateway serviceB = gatewayFactory.getGateway("ServiceB"); + Gateway serviceC = gatewayFactory.getGateway("ServiceC"); + + // Check if the retrieved instances match their expected types + assertTrue( + serviceA instanceof ExternalServiceA, "ServiceA should be an instance of ExternalServiceA"); + assertTrue( + serviceB instanceof ExternalServiceB, "ServiceB should be an instance of ExternalServiceB"); + assertTrue( + serviceC instanceof ExternalServiceC, "ServiceC should be an instance of ExternalServiceC"); + } + + @Test + void testGatewayFactoryRegistrationWithNonExistingKey() { + Gateway nonExistingService = gatewayFactory.getGateway("NonExistingService"); + assertNull(nonExistingService); + } + + @Test + void testGatewayFactoryConcurrency() throws InterruptedException { + int numThreads = 10; + CountDownLatch latch = new CountDownLatch(numThreads); + AtomicBoolean failed = new AtomicBoolean(false); + + for (int i = 0; i < numThreads; i++) { + executorService.submit( + () -> { + try { + Gateway serviceA = gatewayFactory.getGateway("ServiceA"); + serviceA.execute(); + } catch (Exception e) { + failed.set(true); + } finally { + latch.countDown(); + } + }); + } + + latch.await(); + assertFalse(failed.get(), "This should not fail"); + } +} diff --git a/guarded-suspension/README.md b/guarded-suspension/README.md index 35044f9b2491..af0ec85d06f1 100644 --- a/guarded-suspension/README.md +++ b/guarded-suspension/README.md @@ -1,21 +1,162 @@ --- -layout: pattern -title: Guarded Suspension -folder: guarded-suspension -permalink: /patterns/guarded-suspension/ -categories: Concurrency -tags: - - Java - - Difficulty-Beginner +title: "Guarded Suspension Pattern in Java: Ensuring Safe Concurrency in Critical Sections" +shortTitle: Guarded Suspension +description: "Learn about the Guarded Suspension design pattern in Java. Understand its implementation for efficient concurrency control, with real-world examples and code snippets." +category: Concurrency +language: en +tag: + - Asynchronous + - Decoupling + - Resource management + - Synchronization + - Thread management --- -## Intent -Use Guarded suspension pattern to handle a situation when you want to execute a method on object which is not in a proper state. +## Also known as -![Guarded Suspension diagram](./etc/guarded-suspension.png) +* Conditional Block +* Suspended Execution -## Applicability -Use Guarded Suspension pattern when the developer knows that the method execution will be blocked for a finite period of time +## Intent of Guarded Suspension Design Pattern -## Related patterns -* Balking +The Guarded Suspension pattern is crucial in Java design patterns for managing operations that require both a lock and a condition to proceed. It optimizes concurrency control by allowing a thread to wait for the right condition efficiently. + +## Detailed Explanation of Guarded Suspension Pattern with Real-World Examples + +Real-world example + +> A practical example of the Guarded Suspension pattern can be seen in a ride-sharing service. In this system, passengers wait for a car to become available, ensuring efficient resource use without continuous checking. When a passenger requests a ride, the request is suspended until a driver becomes available. The system monitors the availability of drivers, and once a driver is ready to take a new passenger, the system notifies the waiting passenger and resumes the ride request process. This ensures that passengers are not continuously checking for available drivers and that drivers are efficiently matched with passengers based on their availability. + +In plain words + +> Guarded Suspension pattern is used when one thread waits for the result of another thread's execution. + +Wikipedia says + +> In concurrent programming, Guarded Suspension manages operations requiring a lock and a precondition, delaying execution until the precondition is met. + +Sequence diagram + +![Guarded Suspension sequence diagram](./etc/guarded-suspension-sequence-diagram.png) + +## Programmatic Example of Guarded Suspension Pattern in Java + +The `GuardedQueue` class in Java showcases concurrent programming using the Guarded Suspension pattern. It includes synchronized methods that manage thread management and synchronization, demonstrating how threads wait for the right conditions to execute. + +The `GuardedQueue` class demonstrates the Guarded Suspension pattern by encapsulating a queue and providing two synchronized methods, `get` and `put`. The `get` method waits if the queue is empty, while the `put` method adds an item to the queue and notifies any waiting threads. + +```java +@Slf4j +public class GuardedQueue { + private final Queue sourceList = new LinkedList<>(); + + // Synchronized get method waits until the queue is not empty + public synchronized Integer get() { + while (sourceList.isEmpty()) { + try { + wait(); + } catch (InterruptedException e) { + LOGGER.error("Error occurred: ", e); + } + } + return sourceList.poll(); + } + + // Synchronized put method adds an item to the queue and notifies waiting threads + public synchronized void put(Integer e) { + sourceList.add(e); + notify(); + } +} +``` + +* `get`: This method waits while the `sourceList` is empty. When an item is added and `notify` is called, the waiting thread is awakened to continue execution and retrieve the item. +* `put`: This method adds an item to the queue and calls `notify` to wake up any waiting thread that is suspended in the `get` method. + +Here is the `App` class driving the example: + +```java +public class App { + public static void main(String[] args) { + GuardedQueue guardedQueue = new GuardedQueue(); + ExecutorService executorService = Executors.newFixedThreadPool(3); + + // Thread to get from the guardedQueue + executorService.execute(() -> { + Integer item = guardedQueue.get(); + LOGGER.info("Retrieved: " + item); + }); + + // Simulating some delay before putting an item + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + LOGGER.error("Error occurred: ", e); + } + + // Thread to put an item into the guardedQueue + executorService.execute(() -> { + guardedQueue.put(20); + LOGGER.info("Item added to queue"); + }); + + executorService.shutdown(); + try { + executorService.awaitTermination(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Error occurred: ", e); + } + } +} +``` + +* `ExecutorService` is used to manage a pool of threads. +* The first thread attempts to retrieve an item from the `GuardedQueue` and waits since the queue is initially empty. +* After a 2-second delay, the second thread adds an item to the queue, waking up the first thread. +* The first thread then retrieves the item and logs it. + +Execution yields: + +``` +19:22:58.984 [pool-1-thread-1] INFO com.iluwatar.guarded.suspension.GuardedQueue -- waiting +19:23:00.993 [pool-1-thread-2] INFO com.iluwatar.guarded.suspension.GuardedQueue -- putting +19:23:00.994 [pool-1-thread-2] INFO com.iluwatar.guarded.suspension.GuardedQueue -- notifying +19:23:00.994 [pool-1-thread-1] INFO com.iluwatar.guarded.suspension.GuardedQueue -- getting +19:23:00.994 [pool-1-thread-1] INFO com.iluwatar.guarded.suspension.GuardedQueue -- Retrieved: 20 +``` + +* The log output shows the sequence of events: the first thread waits, the second thread puts an item, and the first thread then retrieves the item. This demonstrates the Guarded Suspension pattern in action. + +## When to Use the Guarded Suspension Pattern in Java + +This pattern is ideal for scenarios requiring a thread to wait for specific conditions, promoting efficient concurrency control and reducing busy waiting overhead. + +## Real-World Applications of Guarded Suspension Pattern in Java + +* Network servers waiting for client requests. +* Producer-consumer scenarios where the consumer must wait for the producer to provide data. +* Event-driven applications where actions are triggered only after specific events have occurred. + +## Benefits and Trade-offs of Guarded Suspension Pattern + +Benefits: + +* Reduces CPU consumption by preventing busy waiting. +* Increases system responsiveness by synchronizing actions to the availability of necessary conditions or resources. + +Trade-offs: + +* Complexity in implementation, especially when multiple conditions need to be managed. +* Potential for deadlocks if not carefully managed. + +## Related Java Design Patterns + +* [Monitor](https://java-design-patterns.com/patterns/monitor/): Both patterns manage the synchronization of threads based on conditions. Guarded Suspension specifically deals with suspending threads until conditions are met, while Monitor Object encapsulates condition and mutual exclusion handling. +* [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Often implemented using Guarded Suspension to handle waiting consumers and producers efficiently. +* [Balking](https://java-design-patterns.com/patterns/balking/): Similar to Guarded Suspension, Balking is used when a thread checks a condition and only proceeds if the condition is favorable; if not, it immediately returns or bails out. This pattern complements Guarded Suspension by managing actions based on immediate condition checks without waiting. + +## References and Credits + +* [Concurrent Programming in Java : Design Principles and Patterns](https://amzn.to/4dIBqxL) +* [Java Concurrency in Practice](https://amzn.to/3JxnXek) +* [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/49Ke1c9) diff --git a/guarded-suspension/etc/guarded-suspension-sequence-diagram.png b/guarded-suspension/etc/guarded-suspension-sequence-diagram.png new file mode 100644 index 000000000000..ee7752815c7b Binary files /dev/null and b/guarded-suspension/etc/guarded-suspension-sequence-diagram.png differ diff --git a/guarded-suspension/etc/guarded-suspension.urm.puml b/guarded-suspension/etc/guarded-suspension.urm.puml new file mode 100644 index 000000000000..45a7d37904cb --- /dev/null +++ b/guarded-suspension/etc/guarded-suspension.urm.puml @@ -0,0 +1,15 @@ +@startuml +package com.iluwatar.guarded.suspension { + class App { + + App() + + main(args : String[]) {static} + } + class GuardedQueue { + - LOGGER : Logger {static} + - sourceList : Queue + + GuardedQueue() + + get() : Integer + + put(e : Integer) + } +} +@enduml \ No newline at end of file diff --git a/guarded-suspension/pom.xml b/guarded-suspension/pom.xml index 6b8b977eb7c6..099bfe1e4c70 100644 --- a/guarded-suspension/pom.xml +++ b/guarded-suspension/pom.xml @@ -1,8 +1,10 @@ - - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT jar guarded-suspension - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -46,4 +49,23 @@ test - \ No newline at end of file + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.guarded.suspension.App + + + + + + + + + diff --git a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java index 8747c84e5809..5c6b7e0547dc 100644 --- a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java +++ b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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,57 +22,51 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -/** - * Guarded-suspension is a concurrent design pattern for handling situation when to execute some action we need - * condition to be satisfied. - *

    - * Implementation is based on GuardedQueue, which has two methods: get and put, - * the condition is that we cannot get from empty queue so when thread attempt - * to break the condition we invoke Object's wait method on him and when other thread put an element - * to the queue he notify the waiting one that now he can get from queue. - */ package com.iluwatar.guarded.suspension; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; /** - * Created by robertt240 on 1/26/17. + * Guarded-suspension is a concurrent design pattern for handling situation when to execute some + * action we need condition to be satisfied. The implementation utilizes a GuardedQueue, which + * features two primary methods: `get` and `put`. The key condition governing these operations is + * that elements cannot be retrieved (`get`) from an empty queue. When a thread attempts to retrieve + * an element under this condition, it triggers the invocation of the `wait` method from the Object + * class, causing the thread to pause. Conversely, when an element is added (`put`) to the queue by + * another thread, it invokes the `notify` method. This notifies the waiting thread that it can now + * successfully retrieve an element from the queue. */ +@Slf4j public class App { /** - * Example pattern execution + * Example pattern execution. * * @param args - command line args */ public static void main(String[] args) { - GuardedQueue guardedQueue = new GuardedQueue(); - ExecutorService executorService = Executors.newFixedThreadPool(3); + var guardedQueue = new GuardedQueue(); + var executorService = Executors.newFixedThreadPool(3); - //here we create first thread which is supposed to get from guardedQueue - executorService.execute(() -> { - guardedQueue.get(); - } - ); + // here we create first thread which is supposed to get from guardedQueue + executorService.execute(guardedQueue::get); - //here we wait two seconds to show that the thread which is trying to get from guardedQueue will be waiting + // here we wait two seconds to show that the thread which is trying + // to get from guardedQueue will be waiting try { Thread.sleep(2000); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("Error occurred: ", e); } - //now we execute second thread which will put number to guardedQueue and notify first thread that it could get - executorService.execute(() -> { - guardedQueue.put(20); - } - ); + // now we execute second thread which will put number to guardedQueue + // and notify first thread that it could get + executorService.execute(() -> guardedQueue.put(20)); executorService.shutdown(); try { executorService.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("Error occurred: ", e); } } - } diff --git a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java index e75fc6c496d3..346e7193a6a5 100644 --- a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java +++ b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,20 +24,20 @@ */ package com.iluwatar.guarded.suspension; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.LinkedList; import java.util.Queue; +import lombok.extern.slf4j.Slf4j; /** - * Guarded Queue is an implementation for Guarded Suspension Pattern - * Guarded suspension pattern is used to handle a situation when you want to execute a method - * on an object which is not in a proper state. - * @see http://java-design-patterns.com/patterns/guarded-suspension/ + * Guarded Queue is an implementation for Guarded Suspension Pattern Guarded suspension pattern is + * used to handle a situation when you want to execute a method on an object which is not in a + * proper state. + * + * @see http://java-design-patterns.com/patterns/guarded-suspension/ */ +@Slf4j public class GuardedQueue { - private static final Logger LOGGER = LoggerFactory.getLogger(GuardedQueue.class); private final Queue sourceList; public GuardedQueue() { @@ -43,6 +45,8 @@ public GuardedQueue() { } /** + * Get the last element of the queue if exists. + * * @return last element of a queue if queue is not empty */ public synchronized Integer get() { @@ -51,7 +55,7 @@ public synchronized Integer get() { LOGGER.info("waiting"); wait(); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("Error occurred: ", e); } } LOGGER.info("getting"); @@ -59,6 +63,8 @@ public synchronized Integer get() { } /** + * Put a value in the queue. + * * @param e number which we want to put to our queue */ public synchronized void put(Integer e) { diff --git a/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java b/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java index 2834bd4ef825..edbcf514586d 100644 --- a/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java +++ b/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,40 +24,37 @@ */ package com.iluwatar.guarded.suspension; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Test for Guarded Queue - */ -public class GuardedQueueTest { +/** Test for Guarded Queue. */ +@Slf4j +class GuardedQueueTest { private volatile Integer value; @Test - public void testGet() { - GuardedQueue g = new GuardedQueue(); - ExecutorService executorService = Executors.newFixedThreadPool(2); + void testGet() { + var g = new GuardedQueue(); + var executorService = Executors.newFixedThreadPool(2); executorService.submit(() -> value = g.get()); - executorService.submit(() -> g.put(Integer.valueOf(10))); + executorService.submit(() -> g.put(10)); executorService.shutdown(); try { executorService.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("Error occurred: ", e); } assertEquals(Integer.valueOf(10), value); } @Test - public void testPut() { - GuardedQueue g = new GuardedQueue(); + void testPut() { + var g = new GuardedQueue(); g.put(12); assertEquals(Integer.valueOf(12), g.get()); } - } diff --git a/half-sync-half-async/README.md b/half-sync-half-async/README.md index 8a091f8133a3..95fec081df73 100644 --- a/half-sync-half-async/README.md +++ b/half-sync-half-async/README.md @@ -1,37 +1,171 @@ --- -layout: pattern -title: Half-Sync/Half-Async -folder: half-sync-half-async -permalink: /patterns/half-sync-half-async/ -categories: Concurrency -tags: - - Java - - Difficulty-Intermediate +title: "Half-Sync/Half-Async Pattern in Java: Enhancing System Performance with Dual Processing" +shortTitle: Half-Sync/Half-Async +description: "Learn how the Half-Sync/Half-Async design pattern in Java improves concurrency and system efficiency by decoupling asynchronous and synchronous processing. Explore real-world examples, programmatic implementations, and key use cases." +category: Concurrency +language: en +tag: + - Asynchronous + - Decoupling + - Synchronization + - Thread management --- -## Intent -The Half-Sync/Half-Async pattern decouples synchronous I/O from -asynchronous I/O in a system to simplify concurrent programming effort without -degrading execution efficiency. +## Also known as -![Half-Sync/Half-Async class diagram](./etc/half-sync-half-async.png) +* Async-Sync Bridge +* Half-Synchronous/Half-Asynchronous -## Applicability -Use Half-Sync/Half-Async pattern when +## Intent of Half-Sync/Half-Async Design Pattern -* a system possesses following characteristics: - * the system must perform tasks in response to external events that occur asynchronously, like hardware interrupts in OS - * it is inefficient to dedicate separate thread of control to perform synchronous I/O for each external source of event - * the higher level tasks in the system can be simplified significantly if I/O is performed synchronously. -* one or more tasks in a system must run in a single thread of control, while other tasks may benefit from multi-threading. +The Half-Sync/Half-Async pattern in Java aims to decouple asynchronous and synchronous processing in concurrent systems, enhancing efficiency and performance. This pattern is particularly useful for managing complex concurrent operations in software systems. -## Real world examples +## Detailed Explanation of Half-Sync/Half-Async Pattern with Real-World Examples -* [BSD Unix networking subsystem](http://www.cs.wustl.edu/~schmidt/PDF/PLoP-95.pdf) -* [Real Time CORBA](http://www.omg.org/news/meetings/workshops/presentations/realtime2001/4-3_Pyarali_thread-pool.pdf) -* [Android AsyncTask framework](http://developer.android.com/reference/android/os/AsyncTask.html) +Real-world example -## Credits +> Imagine a busy restaurant kitchen where order taking is asynchronous, allowing waiters to keep working while chefs cook each dish synchronously. Similarly, the Half-Sync/Half-Async pattern handles multiple asynchronous tasks and synchronous processing in Java applications efficiently. Meanwhile, the cooking (synchronous part) follows a specific sequence and requires waiting for each dish to be prepared before starting the next. This setup enables the restaurant to handle multiple customer orders efficiently, while ensuring each dish is cooked with the required attention and timing, much like the Half-Sync/Half-Async pattern manages asynchronous tasks and synchronous processing in software systems. -* [Douglas C. Schmidt and Charles D. Cranor - Half Sync/Half Async](http://www.cs.wustl.edu/~schmidt/PDF/PLoP-95.pdf) -* [Pattern Oriented Software Architecture Vol I-V](http://www.amazon.com/Pattern-Oriented-Software-Architecture-Volume-Patterns/dp/0471958697) +In plain words + +> The Half-Sync/Half-Async pattern separates operations into asynchronous tasks that handle events without waiting, and synchronous tasks that process these events in an orderly and blocking manner. + +Wikipedia says + +> The Half-Sync/Half-Async design pattern is used to solve situations where one part of the application runs synchronously while another runs asynchronously, and the two modules need to communicate with each other. + +Sequence diagram + +![Half-Sync/Half-Async sequence diagram](./etc/half-sync-half-async-sequence-diagram.png) + +## Programmatic Example of Half-Sync/Half-Async Pattern in Java + +The Half-Sync/Half-Async design pattern is a concurrency pattern that separates synchronous and asynchronous processing in a system, simplifying the programming model without affecting performance. It's particularly useful in scenarios where you have a mix of short, mid, and long duration tasks. + +In the provided Java implementation, we can see an example of the Half-Sync/Half-Async pattern in the `App`, `AsynchronousService`, and `ArithmeticSumTask` classes. + +The `App` class is the entry point of the application. It creates an instance of `AsynchronousService` and uses it to handle various tasks asynchronously. + +```java +public class App { + + public static void main(String[] args) { + var service = new AsynchronousService(new LinkedBlockingQueue<>()); + service.execute(new ArithmeticSumTask(1000)); + service.execute(new ArithmeticSumTask(500)); + service.execute(new ArithmeticSumTask(2000)); + service.execute(new ArithmeticSumTask(1)); + service.close(); + } +} +``` + +The `AsynchronousService` class is the asynchronous part of the system. It manages a queue of tasks and processes them in a separate thread. + +```java +public class AsynchronousService { + // Implementation details... +} +``` + +The `ArithmeticSumTask` class represents a task that can be processed asynchronously. It implements the `AsyncTask` interface, which defines methods for pre-processing, post-processing, and error handling. + +```java +static class ArithmeticSumTask implements AsyncTask { + private final long numberOfElements; + + public ArithmeticSumTask(long numberOfElements) { + this.numberOfElements = numberOfElements; + } + + @Override + public Long call() throws Exception { + return ap(numberOfElements); + } + + @Override + public void onPreCall() { + if (numberOfElements < 0) { + throw new IllegalArgumentException("n is less than 0"); + } + } + + @Override + public void onPostCall(Long result) { + LOGGER.info(result.toString()); + } + + @Override + public void onError(Throwable throwable) { + throw new IllegalStateException("Should not occur"); + } +} +``` + +This is the `main` function in the `App` class. + +```java +public static void main(String[] args) { + + var service = new AsynchronousService(new LinkedBlockingQueue<>()); + + service.execute(new ArithmeticSumTask(1000)); + + service.execute(new ArithmeticSumTask(500)); + service.execute(new ArithmeticSumTask(2000)); + service.execute(new ArithmeticSumTask(1)); + + service.close(); +} +``` + +In this example, the `App` class enqueues tasks to the `AsynchronousService`, which processes them asynchronously. The `ArithmeticSumTask` class defines the task to be processed, including pre-processing, the actual processing, and post-processing steps. + +Running the code produces: + +``` +10:56:33.922 [pool-1-thread-4] INFO com.iluwatar.halfsynchalfasync.App -- 1 +10:56:34.425 [pool-1-thread-2] INFO com.iluwatar.halfsynchalfasync.App -- 125250 +10:56:34.925 [pool-1-thread-1] INFO com.iluwatar.halfsynchalfasync.App -- 500500 +10:56:35.925 [pool-1-thread-3] INFO com.iluwatar.halfsynchalfasync.App -- 2001000 +``` + +This is a basic example of the Half-Sync/Half-Async pattern, where tasks are enqueued and processed asynchronously, while the main thread continues to handle other tasks. + +## When to Use the Half-Sync/Half-Async Pattern in Java + +Use the Half-Sync/Half-Async pattern in scenarios where: + +* High performance and efficient concurrency are crucial, such as in Java's standard libraries and network servers managing concurrent connections. +* The system needs to effectively utilize multicore architectures to balance tasks between asynchronous and synchronous processing. +* Decoupling of asynchronous tasks from synchronous processing is necessary to simplify the design and implementation. + +## Real-World Applications of Half-Sync/Half-Async Pattern in Java + +* The Half-Sync/Half-Async pattern is utilized in various frameworks and systems, including BSD Unix networking, Real-Time CORBA, and Android's AsyncTask framework. +* Java's standard libraries utilize this pattern with thread pools and execution queues in the concurrency utilities (e.g., java.util.concurrent). +* Network servers handling concurrent connections where IO operations are handled asynchronously and processing of requests is done synchronously. + +## Benefits and Trade-offs of Half-Sync/Half-Async Pattern + +Benefits: + +* This pattern improves system responsiveness and throughput by isolating blocking operations from non-blocking ones, making it a valuable design pattern in Java concurrency. +* Simplifies programming model by isolating asynchronous and synchronous processing layers. + +Trade-offs: + +* Adds complexity in managing two different processing modes. +* Requires careful design to avoid bottlenecks between the synchronous and asynchronous parts. + +## Related Java Design Patterns + +* [Leader/Followers](https://java-design-patterns.com/patterns/leader-followers/): Both patterns manage thread assignments and concurrency, but Leader/Followers uses a single thread to handle all I/O events, dispatching work to others. +* [Producer/Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Can be integrated with Half-Sync/Half-Async to manage work queues between the async and sync parts. +* [Reactor](https://java-design-patterns.com/patterns/reactor/): Often used with Half-Sync/Half-Async to handle multiple service requests delivered to a service handler without blocking the handler. + +## References and Credits + +* [Java Concurrency in Practice](https://amzn.to/4aRMruW) +* [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) +* [Half-Sync/Half-Async (Douglas C. Schmidt and Charles D. Cranor)](https://www.dre.vanderbilt.edu/~schmidt/PDF/PLoP-95.pdf) diff --git a/half-sync-half-async/etc/half-sync-half-async-sequence-diagram.png b/half-sync-half-async/etc/half-sync-half-async-sequence-diagram.png new file mode 100644 index 000000000000..f7fdabbe242a Binary files /dev/null and b/half-sync-half-async/etc/half-sync-half-async-sequence-diagram.png differ diff --git a/half-sync-half-async/etc/half-sync-half-async.urm.puml b/half-sync-half-async/etc/half-sync-half-async.urm.puml new file mode 100644 index 000000000000..64d8a5f8d87d --- /dev/null +++ b/half-sync-half-async/etc/half-sync-half-async.urm.puml @@ -0,0 +1,33 @@ +@startuml +package com.iluwatar.halfsynchalfasync { + class App { + - LOGGER : Logger {static} + + App() + - ap(i : long) : long {static} + + main(args : String[]) {static} + } + ~class ArithmeticSumTask { + - numberOfElements : long + + ArithmeticSumTask(numberOfElements : long) + + call() : Long + + onError(throwable : Throwable) + + onPostCall(result : Long) + + onPreCall() + } + interface AsyncTask { + + call() : O {abstract} + + onError(Throwable) {abstract} + + onPostCall(O) {abstract} + + onPreCall() {abstract} + } + class AsynchronousService { + - LOGGER : Logger {static} + - service : ExecutorService + + AsynchronousService(workQueue : BlockingQueue) + + close() + + execute(task : AsyncTask) + } +} +ArithmeticSumTask ..+ App +ArithmeticSumTask ..|> AsyncTask +@enduml \ No newline at end of file diff --git a/half-sync-half-async/pom.xml b/half-sync-half-async/pom.xml index e6df33018859..33d6803db3da 100644 --- a/half-sync-half-async/pom.xml +++ b/half-sync-half-async/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT half-sync-half-async - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.halfsynchalfasync.App + + + + + + + + diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java index 90cb5ecbfb0d..1a8baafbc1ab 100644 --- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java +++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,42 +24,35 @@ */ package com.iluwatar.halfsynchalfasync; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.concurrent.LinkedBlockingQueue; +import lombok.extern.slf4j.Slf4j; /** - * - * This application demonstrates Half-Sync/Half-Async pattern. Key parts of the pattern are - * {@link AsyncTask} and {@link AsynchronousService}. - * - *

    - * PROBLEM
    - * A concurrent system have a mixture of short duration, mid duration and long duration tasks. Mid + * This application demonstrates Half-Sync/Half-Async pattern. Key parts of the pattern are {@link + * AsyncTask} and {@link AsynchronousService}. + * + *

    PROBLEM
    + * A concurrent system have a mixture of short duration, mid-duration and long duration tasks. Mid * or long duration tasks should be performed asynchronously to meet quality of service * requirements. - * - *

    - * INTENT
    - * The intent of this pattern is to separate the the synchronous and asynchronous processing in the + * + *

    INTENT
    + * The intent of this pattern is to separate the synchronous and asynchronous processing in the * concurrent application by introducing two intercommunicating layers - one for sync and one for * async. This simplifies the programming without unduly affecting the performance. - * - *

    - * APPLICABILITY
    - * UNIX network subsystems - In operating systems network operations are carried out - * asynchronously with help of hardware level interrupts.
    - * CORBA - At the asynchronous layer one thread is associated with each socket that is connected - * to the client. Thread blocks waiting for CORBA requests from the client. On receiving request it - * is inserted in the queuing layer which is then picked up by synchronous layer which processes the + * + *

    APPLICABILITY
    + * UNIX network subsystems - In operating systems network operations are carried out asynchronously + * with help of hardware level interrupts.
    + * CORBA - At the asynchronous layer one thread is associated with each socket that is connected to + * the client. Thread blocks waiting for CORBA requests from the client. On receiving request it is + * inserted in the queuing layer which is then picked up by synchronous layer which processes the * request and sends response back to the client.
    - * Android AsyncTask framework - Framework provides a way to execute long running blocking - * calls, such as downloading a file, in background threads so that the UI thread remains free to - * respond to user inputs.
    - * - *

    - * IMPLEMENTATION
    + * Android AsyncTask framework - Framework provides a way to execute long-running blocking calls, + * such as downloading a file, in background threads so that the UI thread remains free to respond + * to user inputs.
    + * + *

    IMPLEMENTATION
    * The main method creates an asynchronous service which does not block the main thread while the * task is being performed. The main thread continues its work which is similar to Async Method * Invocation pattern. The difference between them is that there is a queuing layer between @@ -65,19 +60,17 @@ * between both layers. Such as Priority Queue can be used as queuing layer to prioritize the way * tasks are executed. Our implementation is just one simple way of implementing this pattern, there * are many variants possible as described in its applications. - * */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); + var service = new AsynchronousService(new LinkedBlockingQueue<>()); /* * A new task to calculate sum is received but as this is main thread, it should not block. So * it passes it to the asynchronous task layer to compute and proceeds with handling other @@ -94,38 +87,36 @@ public static void main(String[] args) { service.execute(new ArithmeticSumTask(500)); service.execute(new ArithmeticSumTask(2000)); service.execute(new ArithmeticSumTask(1)); + + service.close(); } - /** - * - * ArithmeticSumTask - * - */ + /** ArithmeticSumTask. */ static class ArithmeticSumTask implements AsyncTask { - private long n; + private final long numberOfElements; - public ArithmeticSumTask(long n) { - this.n = n; + public ArithmeticSumTask(long numberOfElements) { + this.numberOfElements = numberOfElements; } /* - * This is the long running task that is performed in background. In our example the long - * running task is calculating arithmetic sum with artificial delay. + * This is the long-running task that is performed in background. In our example the long-running + * task is calculating arithmetic sum with artificial delay. */ @Override - public Long call() throws Exception { - return ap(n); + public Long call() { + return ap(numberOfElements); } /* * This will be called in context of the main thread where some validations can be done * regarding the inputs. Such as it must be greater than 0. It's a small computation which can - * be performed in main thread. If we did validated the input in background thread then we pay + * be performed in main thread. If we did validate the input in background thread then we pay * the cost of context switching which is much more than validating it in main thread. */ @Override public void onPreCall() { - if (n < 0) { + if (numberOfElements < 0) { throw new IllegalArgumentException("n is less than 0"); } } diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java index 2751b98709e4..c17ee86e05dc 100644 --- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java +++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -29,7 +31,7 @@ * typically done is background threads and the result is posted back in form of callback. The * callback does not implement {@code isComplete}, {@code cancel} as it is out of scope of this * pattern. - * + * * @param type of result */ public interface AsyncTask extends Callable { @@ -52,7 +54,7 @@ public interface AsyncTask extends Callable { /** * A callback called if computing the task resulted in some exception. This method is called when * either of {@link #call()} or {@link #onPreCall()} throw any exception. - * + * * @param throwable error cause */ void onError(Throwable throwable); diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java index 4e2f9c23a6cd..ca31b0d8b0a1 100644 --- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java +++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -28,6 +30,7 @@ import java.util.concurrent.FutureTask; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; /** * This is the asynchronous layer which does not block when a new request arrives. It just passes @@ -36,15 +39,15 @@ * thread picks up the task and executes it synchronously in background and the result is posted * back to the caller via callback. */ +@Slf4j public class AsynchronousService { - /* * This represents the queuing layer as well as synchronous layer of the pattern. The thread pool - * contains worker threads which execute the tasks in blocking/synchronous manner. Long running + * contains worker threads which execute the tasks in blocking/synchronous manner. Long-running * tasks should be performed in the background which does not affect the performance of main * thread. */ - private ExecutorService service; + private final ExecutorService service; /** * Creates an asynchronous service using {@code workQueue} as communication channel between @@ -55,16 +58,16 @@ public AsynchronousService(BlockingQueue workQueue) { service = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, workQueue); } - /** * A non-blocking method which performs the task provided in background and returns immediately. - *

    - * On successful completion of task the result is posted back using callback method - * {@link AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally due to - * some exception then the reason for error is posted back using callback method - * {@link AsyncTask#onError(Throwable)}. - *

    - * NOTE: The results are posted back in the context of background thread in this implementation. + * + *

    On successful completion of task the result is posted back using callback method {@link + * AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally due to some + * exception then the reason for error is posted back using callback method {@link + * AsyncTask#onError(Throwable)}. + * + *

    NOTE: The results are posted back in the context of background thread in this + * implementation. */ public void execute(final AsyncTask task) { try { @@ -75,24 +78,35 @@ public void execute(final AsyncTask task) { return; } - service.submit(new FutureTask(task) { - @Override - protected void done() { - super.done(); - try { - /* - * called in context of background thread. There is other variant possible where result is - * posted back and sits in the queue of caller thread which then picks it up for - * processing. An example of such a system is Android OS, where the UI elements can only - * be updated using UI thread. So result must be posted back in UI thread. - */ - task.onPostCall(get()); - } catch (InterruptedException e) { - // should not occur - } catch (ExecutionException e) { - task.onError(e.getCause()); - } - } - }); + service.submit( + new FutureTask<>(task) { + @Override + protected void done() { + super.done(); + try { + /* + * called in context of background thread. There is other variant possible where result is + * posted back and sits in the queue of caller thread which then picks it up for + * processing. An example of such a system is Android OS, where the UI elements can only + * be updated using UI thread. So result must be posted back in UI thread. + */ + task.onPostCall(get()); + } catch (InterruptedException e) { + // should not occur + } catch (ExecutionException e) { + task.onError(e.getCause()); + } + } + }); + } + + /** Stops the pool of workers. This is a blocking call to wait for all tasks to be completed. */ + public void close() { + service.shutdown(); + try { + service.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + LOGGER.error("Error waiting for executor service shutdown!"); + } } } diff --git a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java index dea242f85a6c..a871c81cb26b 100644 --- a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java +++ b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,19 +24,15 @@ */ package com.iluwatar.halfsynchalfasync; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() throws InterruptedException, ExecutionException { - App.main(null); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(null)); } } diff --git a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java index a5496415e36b..1360f7daa557 100644 --- a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java +++ b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,13 +24,7 @@ */ package com.iluwatar.halfsynchalfasync; -import org.junit.jupiter.api.Test; -import org.mockito.InOrder; - -import java.io.IOException; -import java.util.concurrent.LinkedBlockingQueue; - -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -38,24 +34,31 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -/** - * Date: 12/12/15 - 11:15 PM - * - * @author Jeroen Meulemeester - */ -public class AsynchronousServiceTest { +import java.io.IOException; +import java.util.concurrent.LinkedBlockingQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** AsynchronousServiceTest */ +class AsynchronousServiceTest { + private AsynchronousService service; + private AsyncTask task; + + @BeforeEach + void setUp() { + service = new AsynchronousService(new LinkedBlockingQueue<>()); + task = mock(AsyncTask.class); + } @Test - public void testPerfectExecution() throws Exception { - final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); - final AsyncTask task = mock(AsyncTask.class); - final Object result = new Object(); + void testPerfectExecution() throws Exception { + final var result = new Object(); when(task.call()).thenReturn(result); service.execute(task); verify(task, timeout(2000)).onPostCall(eq(result)); - final InOrder inOrder = inOrder(task); + final var inOrder = inOrder(task); inOrder.verify(task, times(1)).onPreCall(); inOrder.verify(task, times(1)).call(); inOrder.verify(task, times(1)).onPostCall(eq(result)); @@ -64,16 +67,14 @@ public void testPerfectExecution() throws Exception { } @Test - public void testCallException() throws Exception { - final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); - final AsyncTask task = mock(AsyncTask.class); - final IOException exception = new IOException(); + void testCallException() throws Exception { + final var exception = new IOException(); when(task.call()).thenThrow(exception); service.execute(task); verify(task, timeout(2000)).onError(eq(exception)); - final InOrder inOrder = inOrder(task); + final var inOrder = inOrder(task); inOrder.verify(task, times(1)).onPreCall(); inOrder.verify(task, times(1)).call(); inOrder.verify(task, times(1)).onError(exception); @@ -82,20 +83,17 @@ public void testCallException() throws Exception { } @Test - public void testPreCallException() throws Exception { - final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); - final AsyncTask task = mock(AsyncTask.class); - final IllegalStateException exception = new IllegalStateException(); + void testPreCallException() { + final var exception = new IllegalStateException(); doThrow(exception).when(task).onPreCall(); service.execute(task); verify(task, timeout(2000)).onError(eq(exception)); - final InOrder inOrder = inOrder(task); + final var inOrder = inOrder(task); inOrder.verify(task, times(1)).onPreCall(); inOrder.verify(task, times(1)).onError(exception); verifyNoMoreInteractions(task); } - -} \ No newline at end of file +} diff --git a/health-check/README.md b/health-check/README.md new file mode 100644 index 000000000000..f6fe0762f07e --- /dev/null +++ b/health-check/README.md @@ -0,0 +1,119 @@ +--- +title: "Health Check Pattern in Java: Monitoring System Health for Optimal Operation" +shortTitle: Health Check +description: "Learn about the Health Check pattern in Java, a vital design for monitoring system health and ensuring reliability in microservices and distributed systems. Discover examples, applications, and benefits." +category: Behavioral +language: en +tag: + - Fault tolerance + - Microservices + - Monitoring + - System health +--- + +## Also known as + +* Health Monitoring +* Service Health Check + +## Intent of Health Check Design Pattern + +The Health Check pattern in Java is designed to proactively monitor the health of individual software components or services, allowing for quick identification and remediation of issues that may affect overall system functionality in microservices architectures. + +## Detailed Explanation of Health Check Pattern with Real-World Examples + +Real-world example + +> Consider a hospital where patient monitoring systems are used to ensure the health of patients. Each monitoring device periodically checks the vital signs of a patient and reports back to a central system. Similarly, in Java-based software systems, a Health Check pattern allows each service to periodically report its status to a central monitoring system. If any device detects abnormal vital signs, it triggers an alert for immediate medical attention. Similarly, in software, a Health Check pattern allows each service to periodically report its status to a central monitoring system. If a service is found to be unhealthy, the system can take corrective actions such as alerting administrators, restarting the service, or redirecting traffic to healthy instances, thereby ensuring continuous and reliable operation. + +In plain words + +> The Health Check Pattern is like a regular doctor's visit for services in a microservices architecture. It helps in early detection of issues and ensures that services are healthy and available. + +Sequence diagram + +![Health Check sequence diagram](./etc/health-check-sequence-diagram.png) + +## Programmatic Example of Health Check Pattern in Java + +The Health Check design pattern is particularly useful in distributed systems where the health of individual components can affect the overall health of the system. Using Spring Boot Actuator, developers can easily implement health checks in Java applications. + +In the provided code, we can see an example of the Health Check pattern in the `App` class and the use of Spring Boot's Actuator. + +The `App` class is the entry point of the application. It starts a Spring Boot application which has health check capabilities built-in through the use of Spring Boot Actuator. + +```java +@EnableCaching +@EnableScheduling +@SpringBootApplication +public class App { + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } +} +``` + +Spring Boot Actuator provides several built-in health checks through its `/actuator/health` endpoint. For example, it can check the status of the database connection, disk space, and other important system parameters. You can also add custom health checks as needed. + +To add a custom health check, you can create a class that implements the `HealthIndicator` interface and override its `health` method. Here is an example: + +```java +@Component +public class CustomHealthCheck implements HealthIndicator { + @Override + public Health health() { + int errorCode = check(); // perform some specific health check + if (errorCode != 0) { + return Health.down() + .withDetail("Error Code", errorCode).build(); + } + return Health.up().build(); + } + + public int check() { + // Our logic to check health + return 0; + } +} +``` + +In this example, the `check` method contains the logic for the health check. If the health check fails, it returns a non-zero error code, and the `health` method builds a `DOWN` health status with the error code. If the health check passes, it returns a `UP` health status. + +This is a basic example of the Health Check pattern, where health checks are built into the system and can be easily accessed and monitored. + +## When to Use the Health Check Pattern in Java + +* Use when building Java microservices or distributed systems where it is crucial to monitor the health of each service. +* Suitable for scenarios where automated systems need to determine the operational status of services to perform load balancing, failover, or recovery operations. + +## Real-World Applications of Health Check Pattern in Java + +Known uses of the Health Check pattern in Java include + +* Kubernetes liveness and readiness probes +* AWS elastic load balancing health checks +* Spring Boot Actuator integrations + +## Benefits and Trade-offs of Health Check Pattern + +Benefits: + +* Improved system reliability through early detection of failures. +* Enhanced system availability by allowing for automatic or manual recovery processes. +* Simplifies maintenance and operations by providing clear visibility into system health. + +Trade-offs: + +* Additional overhead for implementing and maintaining health check mechanisms. +* May introduce complexity in handling false positives and negatives in health status reporting. + +## Related Java Design Patterns + +* [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Both patterns enhance system resilience; while Health Check monitors health status, Circuit Breaker protects a system from repeated failures. +* [Observer](https://java-design-patterns.com/patterns/observer/): Health Check can be seen as a specific use case of the Observer pattern, where the subject being observed is the system’s health. + +## References and Credits + +* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O) +* [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3Uul4kF) +* [Pattern: Health Check API (Microservices.io)](https://microservices.io/patterns/observability/health-check-api.html) diff --git a/health-check/etc/health-check-sequence-diagram.png b/health-check/etc/health-check-sequence-diagram.png new file mode 100644 index 000000000000..65ddb26ab812 Binary files /dev/null and b/health-check/etc/health-check-sequence-diagram.png differ diff --git a/health-check/etc/health-check.png b/health-check/etc/health-check.png new file mode 100644 index 000000000000..89966c464cb5 Binary files /dev/null and b/health-check/etc/health-check.png differ diff --git a/health-check/etc/health-check.puml b/health-check/etc/health-check.puml new file mode 100644 index 000000000000..f9f0c5d00b53 --- /dev/null +++ b/health-check/etc/health-check.puml @@ -0,0 +1,90 @@ +@startuml + +!theme plain +top to bottom direction +skinparam linetype ortho + +class App { + + App(): + + main(String[]): void +} +class AsynchronousHealthChecker { + + AsynchronousHealthChecker(): + + performCheck(Supplier, long): CompletableFuture + - awaitTerminationWithTimeout(): boolean + + shutdown(): void +} +class CpuHealthIndicator { + + CpuHealthIndicator(): + - processCpuLoadThreshold: double + - systemCpuLoadThreshold: double + - loadAverageThreshold: double + - osBean: OperatingSystemMXBean + - defaultWarningMessage: String + + init(): void + + health(): Health + defaultWarningMessage: String + osBean: OperatingSystemMXBean + loadAverageThreshold: double + processCpuLoadThreshold: double + systemCpuLoadThreshold: double +} +class CustomHealthIndicator { + + CustomHealthIndicator(AsynchronousHealthChecker, CacheManager, HealthCheckRepository): + + evictHealthCache(): void + - check(): Health + + health(): Health +} +class DatabaseTransactionHealthIndicator { + + DatabaseTransactionHealthIndicator(HealthCheckRepository, AsynchronousHealthChecker, RetryTemplate): + - retryTemplate: RetryTemplate + - healthCheckRepository: HealthCheckRepository + - timeoutInSeconds: long + - asynchronousHealthChecker: AsynchronousHealthChecker + + health(): Health + timeoutInSeconds: long + retryTemplate: RetryTemplate + healthCheckRepository: HealthCheckRepository + asynchronousHealthChecker: AsynchronousHealthChecker +} +class GarbageCollectionHealthIndicator { + + GarbageCollectionHealthIndicator(): + - memoryUsageThreshold: double + + health(): Health + memoryPoolMxBeans: List + garbageCollectorMxBeans: List + memoryUsageThreshold: double +} +class HealthCheck { + + HealthCheck(): + - status: String + - id: Integer + + equals(Object): boolean + # canEqual(Object): boolean + + hashCode(): int + + toString(): String + id: Integer + status: String +} +class HealthCheckRepository { + + HealthCheckRepository(): + + performTestTransaction(): void + + checkHealth(): Integer +} +class MemoryHealthIndicator { + + MemoryHealthIndicator(AsynchronousHealthChecker): + + checkMemory(): Health + + health(): Health +} +class RetryConfig { + + RetryConfig(): + + retryTemplate(): RetryTemplate +} + +CustomHealthIndicator "1" *-[#595959,plain]-> "healthChecker\n1" AsynchronousHealthChecker +CustomHealthIndicator "1" *-[#595959,plain]-> "healthCheckRepository\n1" HealthCheckRepository +DatabaseTransactionHealthIndicator "1" *-[#595959,plain]-> "asynchronousHealthChecker\n1" AsynchronousHealthChecker +DatabaseTransactionHealthIndicator "1" *-[#595959,plain]-> "healthCheckRepository\n1" HealthCheckRepository +HealthCheckRepository -[#595959,dashed]-> HealthCheck : "«create»" +MemoryHealthIndicator "1" *-[#595959,plain]-> "asynchronousHealthChecker\n1" AsynchronousHealthChecker +@enduml diff --git a/health-check/etc/health-check.urm.puml b/health-check/etc/health-check.urm.puml new file mode 100644 index 000000000000..ebd0fa9678e7 --- /dev/null +++ b/health-check/etc/health-check.urm.puml @@ -0,0 +1,124 @@ +@startuml +package com.iluwatar.health.check { + class App { + + App() + + main(args : String[]) {static} + } + class AsynchronousHealthChecker { + - HEALTH_CHECK_FAILED_MESSAGE : String {static} + - HEALTH_CHECK_TIMEOUT_MESSAGE : String {static} + - LOGGER : Logger {static} + - healthCheckExecutor : ScheduledExecutorService + + AsynchronousHealthChecker() + - awaitTerminationWithTimeout() : boolean + + performCheck(healthCheck : Supplier, timeoutInSeconds : long) : CompletableFuture + + shutdown() + } + class CpuHealthIndicator { + - ERROR_MESSAGE : String {static} + - HIGH_LOAD_AVERAGE_MESSAGE : String {static} + - HIGH_LOAD_AVERAGE_MESSAGE_WITHOUT_PARAM : String {static} + - HIGH_PROCESS_CPU_LOAD_MESSAGE : String {static} + - HIGH_PROCESS_CPU_LOAD_MESSAGE_WITHOUT_PARAM : String {static} + - HIGH_SYSTEM_CPU_LOAD_MESSAGE : String {static} + - HIGH_SYSTEM_CPU_LOAD_MESSAGE_WITHOUT_PARAM : String {static} + - LOGGER : Logger {static} + - defaultWarningMessage : String + - loadAverageThreshold : double + - osBean : OperatingSystemMXBean + - processCpuLoadThreshold : double + - systemCpuLoadThreshold : double + + CpuHealthIndicator() + + getDefaultWarningMessage() : String + + getLoadAverageThreshold() : double + + getOsBean() : OperatingSystemMXBean + + getProcessCpuLoadThreshold() : double + + getSystemCpuLoadThreshold() : double + + health() : Health + + init() + + setDefaultWarningMessage(defaultWarningMessage : String) + + setLoadAverageThreshold(loadAverageThreshold : double) + + setOsBean(osBean : OperatingSystemMXBean) + + setProcessCpuLoadThreshold(processCpuLoadThreshold : double) + + setSystemCpuLoadThreshold(systemCpuLoadThreshold : double) + } + class CustomHealthIndicator { + - LOGGER : Logger {static} + - cacheManager : CacheManager + - healthCheckRepository : HealthCheckRepository + - healthChecker : AsynchronousHealthChecker + - timeoutInSeconds : long + + CustomHealthIndicator(healthChecker : AsynchronousHealthChecker, cacheManager : CacheManager, healthCheckRepository : HealthCheckRepository) + - check() : Health + + evictHealthCache() + + health() : Health + } + class DatabaseTransactionHealthIndicator { + - LOGGER : Logger {static} + - asynchronousHealthChecker : AsynchronousHealthChecker + - healthCheckRepository : HealthCheckRepository + - retryTemplate : RetryTemplate + - timeoutInSeconds : long + + DatabaseTransactionHealthIndicator(healthCheckRepository : HealthCheckRepository, asynchronousHealthChecker : AsynchronousHealthChecker, retryTemplate : RetryTemplate) + + getAsynchronousHealthChecker() : AsynchronousHealthChecker + + getHealthCheckRepository() : HealthCheckRepository + + getRetryTemplate() : RetryTemplate + + getTimeoutInSeconds() : long + + health() : Health + + setTimeoutInSeconds(timeoutInSeconds : long) + } + class GarbageCollectionHealthIndicator { + - LOGGER : Logger {static} + - memoryUsageThreshold : double + + GarbageCollectionHealthIndicator() + - addMemoryPoolDetails(collectorDetails : Map, memoryPoolMxBeans : List, memoryPoolNamesList : List) + - createCollectorDetails(gcBean : GarbageCollectorMXBean, memoryPoolMxBeans : List) : Map + # getGarbageCollectorMxBeans() : List + # getMemoryPoolMxBeans() : List + + getMemoryUsageThreshold() : double + + health() : Health + + setMemoryUsageThreshold(memoryUsageThreshold : double) + } + class HealthCheck { + - id : Integer + - status : String + + HealthCheck() + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getId() : Integer + + getStatus() : String + + hashCode() : int + + setId(id : Integer) + + setStatus(status : String) + + toString() : String + } + class HealthCheckRepository { + - HEALTH_CHECK_OK : String {static} + - LOGGER : Logger {static} + - entityManager : EntityManager + + HealthCheckRepository() + + checkHealth() : Integer + + performTestTransaction() + } + class MemoryHealthIndicator { + - LOGGER : Logger {static} + - asynchronousHealthChecker : AsynchronousHealthChecker + - memoryThreshold : double + - timeoutInSeconds : long + + MemoryHealthIndicator(asynchronousHealthChecker : AsynchronousHealthChecker) + + checkMemory() : Health + + health() : Health + } + class RetryConfig { + - backOffPeriod : long + - maxAttempts : int + + RetryConfig() + + retryTemplate() : RetryTemplate + } +} +DatabaseTransactionHealthIndicator --> "-asynchronousHealthChecker" AsynchronousHealthChecker +DatabaseTransactionHealthIndicator --> "-healthCheckRepository" HealthCheckRepository +CustomHealthIndicator --> "-healthCheckRepository" HealthCheckRepository +CustomHealthIndicator --> "-healthChecker" AsynchronousHealthChecker +MemoryHealthIndicator --> "-asynchronousHealthChecker" AsynchronousHealthChecker +@enduml \ No newline at end of file diff --git a/health-check/pom.xml b/health-check/pom.xml new file mode 100644 index 000000000000..203503ad03b6 --- /dev/null +++ b/health-check/pom.xml @@ -0,0 +1,142 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + health-check + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hibernate + hibernate-core + 6.4.4.Final + + + jakarta.xml.bind + jakarta.xml.bind-api + 4.0.2 + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework.retry + spring-retry + 2.0.11 + + + + + com.h2database + h2 + runtime + + + + + org.assertj + assertj-core + 3.27.3 + test + + + + io.rest-assured + rest-assured + 5.5.1 + test + + + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + + jar-with-dependencies + + + + + com.iluwatar.healthcheck.App + + + + + + + + + + + + diff --git a/health-check/src/main/java/com/iluwatar/health/check/App.java b/health-check/src/main/java/com/iluwatar/health/check/App.java new file mode 100644 index 000000000000..8f8faed9f821 --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/App.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * This application provides health check APIs for various aspects of the microservice architecture, + * including database transactions, garbage collection, and overall system health. These health + * checks are essential for monitoring the health and performance of the microservices and ensuring + * their availability and responsiveness. For more information about health checks and their role in + * microservice architectures, please refer to: [Microservices Health Checks + * API]('https://microservices.io/patterns/observability/health-check-api.html'). + */ +@EnableCaching +@EnableScheduling +@SpringBootApplication +public class App { + /** Program entry point. */ + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/AsynchronousHealthChecker.java b/health-check/src/main/java/com/iluwatar/health/check/AsynchronousHealthChecker.java new file mode 100644 index 000000000000..50433d48adf6 --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/AsynchronousHealthChecker.java @@ -0,0 +1,138 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +import jakarta.annotation.PreDestroy; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.actuate.health.Health; +import org.springframework.stereotype.Component; + +/** An asynchronous health checker component that executes health checks in a separate thread. */ +@Slf4j +@Component +@RequiredArgsConstructor +public class AsynchronousHealthChecker { + + /** A scheduled executor service used to execute health checks in a separate thread. */ + private final ScheduledExecutorService healthCheckExecutor = + Executors.newSingleThreadScheduledExecutor(); + + private static final String HEALTH_CHECK_TIMEOUT_MESSAGE = "Health check timed out"; + private static final String HEALTH_CHECK_FAILED_MESSAGE = "Health check failed"; + + /** + * Performs a health check asynchronously using the provided health check logic with a specified + * timeout. + * + * @param healthCheck the health check logic supplied as a {@code Supplier} + * @param timeoutInSeconds the maximum time to wait for the health check to complete, in seconds + * @return a {@code CompletableFuture} object that represents the result of the health + * check + */ + public CompletableFuture performCheck( + Supplier healthCheck, long timeoutInSeconds) { + CompletableFuture future = + CompletableFuture.supplyAsync(healthCheck, healthCheckExecutor); + + // Schedule a task to enforce the timeout + healthCheckExecutor.schedule( + () -> { + if (!future.isDone()) { + LOGGER.error(HEALTH_CHECK_TIMEOUT_MESSAGE); + future.completeExceptionally(new TimeoutException(HEALTH_CHECK_TIMEOUT_MESSAGE)); + } + }, + timeoutInSeconds, + TimeUnit.SECONDS); + + return future.handle( + (result, throwable) -> { + if (throwable != null) { + LOGGER.error(HEALTH_CHECK_FAILED_MESSAGE, throwable); + // Check if the throwable is a TimeoutException or caused by a TimeoutException + Throwable rootCause = + throwable instanceof CompletionException ? throwable.getCause() : throwable; + if (!(rootCause instanceof TimeoutException)) { + LOGGER.error(HEALTH_CHECK_FAILED_MESSAGE, rootCause); + return Health.down().withException(rootCause).build(); + } else { + LOGGER.error(HEALTH_CHECK_TIMEOUT_MESSAGE, rootCause); + // If it is a TimeoutException, rethrow it wrapped in a CompletionException + throw new CompletionException(rootCause); + } + } else { + return result; + } + }); + } + + /** + * Checks whether the health check executor service has terminated completely. This method waits + * for the executor service to finish all its tasks within a specified timeout. If the timeout is + * reached before all tasks are completed, the method returns `true`; otherwise, it returns + * `false`. + * + * @throws InterruptedException if the current thread is interrupted while waiting for the + * executor service to terminate + */ + private boolean awaitTerminationWithTimeout() throws InterruptedException { + boolean isTerminationIncomplete = !healthCheckExecutor.awaitTermination(5, TimeUnit.SECONDS); + LOGGER.info("Termination status: {}", isTerminationIncomplete); + // Await termination and return true if termination is incomplete (timeout elapsed) + return isTerminationIncomplete; + } + + /** Shuts down the executor service, allowing in-flight tasks to complete. */ + @PreDestroy + public void shutdown() { + try { + // Wait a while for existing tasks to terminate + if (awaitTerminationWithTimeout()) { + LOGGER.info("Health check executor did not terminate in time"); + // Attempt to cancel currently executing tasks + healthCheckExecutor.shutdownNow(); + // Wait again for tasks to respond to being cancelled + if (awaitTerminationWithTimeout()) { + LOGGER.error("Health check executor did not terminate"); + } + } + } catch (InterruptedException ie) { + // Preserve interrupt status + Thread.currentThread().interrupt(); + // (Re-)Cancel if current thread also interrupted + healthCheckExecutor.shutdownNow(); + // Log the stack trace for interrupted exception + LOGGER.error("Shutdown of the health check executor was interrupted", ie); + } + } +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java new file mode 100644 index 000000000000..451b1263bd0c --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java @@ -0,0 +1,136 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +import jakarta.annotation.PostConstruct; +import java.lang.management.ManagementFactory; +import java.lang.management.OperatingSystemMXBean; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +/** A health indicator that checks the health of the system's CPU. */ +@Getter +@Setter +@Slf4j +@Component +public class CpuHealthIndicator implements HealthIndicator { + + /** The operating system MXBean used to gather CPU health information. */ + private OperatingSystemMXBean osBean; + + /** Initializes the {@link OperatingSystemMXBean} instance. */ + @PostConstruct + public void init() { + this.osBean = ManagementFactory.getOperatingSystemMXBean(); + } + + /** + * The system CPU load threshold. If the system CPU load is above this threshold, the health + * indicator will return a `down` health status. + */ + @Value("${cpu.system.load.threshold:80.0}") + private double systemCpuLoadThreshold; + + /** + * The process CPU load threshold. If the process CPU load is above this threshold, the health + * indicator will return a `down` health status. + */ + @Value("${cpu.process.load.threshold:50.0}") + private double processCpuLoadThreshold; + + /** + * The load average threshold. If the load average is above this threshold, the health indicator + * will return an `up` health status with a warning message. + */ + @Value("${cpu.load.average.threshold:0.75}") + private double loadAverageThreshold; + + private static final String ERROR_MESSAGE = "error"; + + private static final String HIGH_SYSTEM_CPU_LOAD_MESSAGE = "High system CPU load: {}"; + private static final String HIGH_PROCESS_CPU_LOAD_MESSAGE = "High process CPU load: {}"; + private static final String HIGH_LOAD_AVERAGE_MESSAGE = "High load average: {}"; + private static final String HIGH_PROCESS_CPU_LOAD_MESSAGE_WITHOUT_PARAM = "High process CPU load"; + private static final String HIGH_SYSTEM_CPU_LOAD_MESSAGE_WITHOUT_PARAM = "High system CPU load"; + private static final String HIGH_LOAD_AVERAGE_MESSAGE_WITHOUT_PARAM = "High load average"; + + /** + * Checks the health of the system's CPU and returns a health indicator object. + * + * @return a health indicator object + */ + @Override + public Health health() { + + if (!(osBean instanceof com.sun.management.OperatingSystemMXBean sunOsBean)) { + LOGGER.error("Unsupported operating system MXBean: {}", osBean.getClass().getName()); + return Health.unknown() + .withDetail(ERROR_MESSAGE, "Unsupported operating system MXBean") + .build(); + } + + double systemCpuLoad = sunOsBean.getCpuLoad() * 100; + double processCpuLoad = sunOsBean.getProcessCpuLoad() * 100; + int availableProcessors = sunOsBean.getAvailableProcessors(); + double loadAverage = sunOsBean.getSystemLoadAverage(); + + Map details = new HashMap<>(); + details.put("timestamp", Instant.now()); + details.put("systemCpuLoad", String.format("%.2f%%", systemCpuLoad)); + details.put("processCpuLoad", String.format("%.2f%%", processCpuLoad)); + details.put("availableProcessors", availableProcessors); + details.put("loadAverage", loadAverage); + + if (systemCpuLoad > systemCpuLoadThreshold) { + LOGGER.error(HIGH_SYSTEM_CPU_LOAD_MESSAGE, systemCpuLoad); + return Health.down() + .withDetails(details) + .withDetail(ERROR_MESSAGE, HIGH_SYSTEM_CPU_LOAD_MESSAGE_WITHOUT_PARAM) + .build(); + } else if (processCpuLoad > processCpuLoadThreshold) { + LOGGER.error(HIGH_PROCESS_CPU_LOAD_MESSAGE, processCpuLoad); + return Health.down() + .withDetails(details) + .withDetail(ERROR_MESSAGE, HIGH_PROCESS_CPU_LOAD_MESSAGE_WITHOUT_PARAM) + .build(); + } else if (loadAverage > (availableProcessors * loadAverageThreshold)) { + LOGGER.error(HIGH_LOAD_AVERAGE_MESSAGE, loadAverage); + return Health.up() + .withDetails(details) + .withDetail(ERROR_MESSAGE, HIGH_LOAD_AVERAGE_MESSAGE_WITHOUT_PARAM) + .build(); + } else { + return Health.up().withDetails(details).build(); + } + } +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/CustomHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/CustomHealthIndicator.java new file mode 100644 index 000000000000..54f2efe04db6 --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/CustomHealthIndicator.java @@ -0,0 +1,112 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** + * A custom health indicator that periodically checks the health of a database and caches the + * result. It leverages an asynchronous health checker to perform the health checks. + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class CustomHealthIndicator implements HealthIndicator { + + private final AsynchronousHealthChecker healthChecker; + private final CacheManager cacheManager; + private final HealthCheckRepository healthCheckRepository; + + @Value("${health.check.timeout:10}") + private long timeoutInSeconds; + + /** + * Perform a health check and cache the result. + * + * @return the health status of the application + * @throws HealthCheckInterruptedException if the health check is interrupted + */ + @Override + @Cacheable(value = "health-check", unless = "#result.status == 'DOWN'") + public Health health() { + LOGGER.info("Performing health check"); + CompletableFuture healthFuture = + healthChecker.performCheck(this::check, timeoutInSeconds); + try { + return healthFuture.get(timeoutInSeconds, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Health check interrupted", e); + throw new HealthCheckInterruptedException(e); + } catch (Exception e) { + LOGGER.error("Health check failed", e); + return Health.down(e).build(); + } + } + + /** + * Checks the health of the database by querying for a simple constant value expected from the + * database. + * + * @return Health indicating UP if the database returns the constant correctly, otherwise DOWN. + */ + private Health check() { + Integer result = healthCheckRepository.checkHealth(); + boolean databaseIsUp = result != null && result == 1; + LOGGER.info("Health check result: {}", databaseIsUp); + return databaseIsUp + ? Health.up().withDetail("database", "reachable").build() + : Health.down().withDetail("database", "unreachable").build(); + } + + /** + * Evicts all entries from the health check cache. This is scheduled to run at a fixed rate + * defined in the application properties. + */ + @Scheduled(fixedRateString = "${health.check.cache.evict.interval:60000}") + public void evictHealthCache() { + LOGGER.info("Evicting health check cache"); + try { + Cache healthCheckCache = cacheManager.getCache("health-check"); + LOGGER.info("Health check cache: {}", healthCheckCache); + if (healthCheckCache != null) { + healthCheckCache.clear(); + } + } catch (Exception e) { + LOGGER.error("Failed to evict health check cache", e); + } + } +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/DatabaseTransactionHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/DatabaseTransactionHealthIndicator.java new file mode 100644 index 000000000000..81658a27c727 --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/DatabaseTransactionHealthIndicator.java @@ -0,0 +1,94 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +import java.util.concurrent.ExecutionException; +import java.util.function.Supplier; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.retry.support.RetryTemplate; +import org.springframework.stereotype.Component; + +/** + * A health indicator that checks the health of database transactions by attempting to perform a + * test transaction using a retry mechanism. If the transaction succeeds after multiple attempts, + * the health indicator returns {@link Health#up()} and logs a success message. If all retry + * attempts fail, the health indicator returns {@link Health#down()} and logs an error message. + */ +@Slf4j +@Component +@RequiredArgsConstructor +@Setter +@Getter +public class DatabaseTransactionHealthIndicator implements HealthIndicator { + + /** A repository for performing health checks on the database. */ + private final HealthCheckRepository healthCheckRepository; + + /** An asynchronous health checker used to execute health checks in a separate thread. */ + private final AsynchronousHealthChecker asynchronousHealthChecker; + + /** A retry template used to retry the test transaction if it fails due to a transient error. */ + private final RetryTemplate retryTemplate; + + /** + * The timeout in seconds for the health check. If the health check does not complete within this + * timeout, it will be considered timed out and will return {@link Health#down()}. + */ + @Value("${health.check.timeout:10}") + private long timeoutInSeconds; + + /** + * Performs a health check by attempting to perform a test transaction with retry support. + * + * @return the health status of the database transactions + */ + @Override + public Health health() { + LOGGER.info("Calling performCheck with timeout {}", timeoutInSeconds); + Supplier dbTransactionCheck = + () -> { + try { + healthCheckRepository.performTestTransaction(); + return Health.up().build(); + } catch (Exception e) { + LOGGER.error("Database transaction health check failed", e); + return Health.down(e).build(); + } + }; + try { + return asynchronousHealthChecker.performCheck(dbTransactionCheck, timeoutInSeconds).get(); + } catch (InterruptedException | ExecutionException e) { + LOGGER.error("Database transaction health check timed out or was interrupted", e); + Thread.currentThread().interrupt(); + return Health.down(e).build(); + } + } +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/GarbageCollectionHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/GarbageCollectionHealthIndicator.java new file mode 100644 index 000000000000..0790f0407ad4 --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/GarbageCollectionHealthIndicator.java @@ -0,0 +1,154 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryPoolMXBean; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +/** + * A custom health indicator that checks the garbage collection status of the application and + * reports the health status accordingly. It gathers information about the collection count, + * collection time, memory pool name, and garbage collector algorithm for each garbage collector and + * presents the details in a structured manner. + */ +@Slf4j +@Component +@Getter +@Setter +public class GarbageCollectionHealthIndicator implements HealthIndicator { + + /** + * The memory usage threshold above which a warning message is included in the health check + * report. + */ + @Value("${memory.usage.threshold:0.8}") + private double memoryUsageThreshold; + + /** + * Performs a health check by gathering garbage collection metrics and evaluating the overall + * health of the garbage collection system. + * + * @return a {@link Health} object representing the health status of the garbage collection system + */ + @Override + public Health health() { + List gcBeans = getGarbageCollectorMxBeans(); + List memoryPoolMxBeans = getMemoryPoolMxBeans(); + Map> gcDetails = new HashMap<>(); + + for (GarbageCollectorMXBean gcBean : gcBeans) { + Map collectorDetails = createCollectorDetails(gcBean, memoryPoolMxBeans); + gcDetails.put(gcBean.getName(), collectorDetails); + } + + return Health.up().withDetails(gcDetails).build(); + } + + /** + * Creates details for the given garbage collector, including collection count, collection time, + * and memory pool information. + * + * @param gcBean The garbage collector MXBean + * @param memoryPoolMxBeans List of memory pool MXBeans + * @return Map containing details for the garbage collector + */ + private Map createCollectorDetails( + GarbageCollectorMXBean gcBean, List memoryPoolMxBeans) { + Map collectorDetails = new HashMap<>(); + long count = gcBean.getCollectionCount(); + long time = gcBean.getCollectionTime(); + collectorDetails.put("count", String.format("%d", count)); + collectorDetails.put("time", String.format("%dms", time)); + + String[] memoryPoolNames = gcBean.getMemoryPoolNames(); + List memoryPoolNamesList = Arrays.asList(memoryPoolNames); + if (!memoryPoolNamesList.isEmpty()) { + addMemoryPoolDetails(collectorDetails, memoryPoolMxBeans, memoryPoolNamesList); + } else { + LOGGER.error("Garbage collector '{}' does not have any memory pools", gcBean.getName()); + } + + return collectorDetails; + } + + /** + * Adds memory pool details to the collector details. + * + * @param collectorDetails Map containing details for the garbage collector + * @param memoryPoolMxBeans List of memory pool MXBeans + * @param memoryPoolNamesList List of memory pool names associated with the garbage collector + */ + private void addMemoryPoolDetails( + Map collectorDetails, + List memoryPoolMxBeans, + List memoryPoolNamesList) { + for (MemoryPoolMXBean memoryPoolmxbean : memoryPoolMxBeans) { + if (memoryPoolNamesList.contains(memoryPoolmxbean.getName())) { + double memoryUsage = + memoryPoolmxbean.getUsage().getUsed() / (double) memoryPoolmxbean.getUsage().getMax(); + if (memoryUsage > memoryUsageThreshold) { + collectorDetails.put( + "warning", + String.format( + "Memory pool '%s' usage is high (%2f%%)", + memoryPoolmxbean.getName(), memoryUsage)); + } + + collectorDetails.put( + "memoryPools", String.format("%s: %s%%", memoryPoolmxbean.getName(), memoryUsage)); + } + } + } + + /** + * Retrieves the list of garbage collector MXBeans using ManagementFactory. + * + * @return a list of {@link GarbageCollectorMXBean} objects representing the garbage collectors + */ + protected List getGarbageCollectorMxBeans() { + return ManagementFactory.getGarbageCollectorMXBeans(); + } + + /** + * Retrieves the list of memory pool MXBeans using ManagementFactory. + * + * @return a list of {@link MemoryPoolMXBean} objects representing the memory pools + */ + protected List getMemoryPoolMxBeans() { + return ManagementFactory.getMemoryPoolMXBeans(); + } +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/HealthCheck.java b/health-check/src/main/java/com/iluwatar/health/check/HealthCheck.java new file mode 100644 index 000000000000..6223acde083a --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/HealthCheck.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import lombok.Data; + +/** + * An entity class that represents a health check record in the database. This class is used to + * persist the results of health checks performed by the `DatabaseTransactionHealthIndicator`. + */ +@Entity +@Data +public class HealthCheck { + + /** The unique identifier of the health check record. */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + /** The status of the health check. Possible values are "UP" and "DOWN". */ + @Column(name = "status") + private String status; +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/HealthCheckInterruptedException.java b/health-check/src/main/java/com/iluwatar/health/check/HealthCheckInterruptedException.java new file mode 100644 index 000000000000..486a381f2756 --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/HealthCheckInterruptedException.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +/** + * Exception thrown when the health check is interrupted during execution. This exception is a + * runtime exception that wraps the original cause. + */ +public class HealthCheckInterruptedException extends RuntimeException { + /** + * Constructs a new HealthCheckInterruptedException with the specified cause. + * + * @param cause the cause of the exception + */ + public HealthCheckInterruptedException(Throwable cause) { + super("Health check interrupted", cause); + } +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/HealthCheckRepository.java b/health-check/src/main/java/com/iluwatar/health/check/HealthCheckRepository.java new file mode 100644 index 000000000000..d5016323ac6f --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/HealthCheckRepository.java @@ -0,0 +1,80 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.transaction.Transactional; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Repository; + +/** + * A repository class for managing health check records in the database. This class provides methods + * for checking the health of the database connection and performing test transactions. + */ +@Slf4j +@Repository +public class HealthCheckRepository { + + private static final String HEALTH_CHECK_OK = "OK"; + + @PersistenceContext private EntityManager entityManager; + + /** + * Checks the health of the database connection by executing a simple query that should always + * return 1 if the connection is healthy. + * + * @return 1 if the database connection is healthy, or null otherwise + */ + public Integer checkHealth() { + try { + return (Integer) entityManager.createNativeQuery("SELECT 1").getSingleResult(); + } catch (Exception e) { + LOGGER.error("Health check query failed", e); + throw e; + } + } + + /** + * Performs a test transaction by writing a record to the `health_check` table, reading it back, + * and then deleting it. If any of these operations fail, an exception is thrown. + * + * @throws Exception if the test transaction fails + */ + @Transactional + public void performTestTransaction() throws Exception { + try { + HealthCheck healthCheck = new HealthCheck(); + healthCheck.setStatus(HEALTH_CHECK_OK); + entityManager.persist(healthCheck); + entityManager.flush(); + HealthCheck retrievedHealthCheck = entityManager.find(HealthCheck.class, healthCheck.getId()); + entityManager.remove(retrievedHealthCheck); + } catch (Exception e) { + LOGGER.error("Test transaction failed", e); + throw e; + } + } +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/MemoryHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/MemoryHealthIndicator.java new file mode 100644 index 000000000000..08d82dd4ad5b --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/MemoryHealthIndicator.java @@ -0,0 +1,111 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryMXBean; +import java.lang.management.MemoryUsage; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.function.Supplier; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +/** + * A custom health indicator that checks the memory usage of the application and reports the health + * status accordingly. It uses an asynchronous health checker to perform the health check and a + * configurable memory usage threshold to determine the health status. + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class MemoryHealthIndicator implements HealthIndicator { + + private final AsynchronousHealthChecker asynchronousHealthChecker; + + /** The timeout in seconds for the health check. */ + @Value("${health.check.timeout:10}") + private long timeoutInSeconds; + + /** + * The memory usage threshold in percentage. If the memory usage is less than this threshold, the + * health status is reported as UP. Otherwise, the health status is reported as DOWN. + */ + @Value("${health.check.memory.threshold:0.9}") + private double memoryThreshold; + + /** + * Performs a health check by checking the memory usage of the application. + * + * @return the health status of the application + */ + public Health checkMemory() { + Supplier memoryCheck = + () -> { + MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean(); + MemoryUsage heapMemoryUsage = memoryMxBean.getHeapMemoryUsage(); + long maxMemory = heapMemoryUsage.getMax(); + long usedMemory = heapMemoryUsage.getUsed(); + + double memoryUsage = (double) usedMemory / maxMemory; + String format = String.format("%.2f%% of %d max", memoryUsage * 100, maxMemory); + + if (memoryUsage < memoryThreshold) { + LOGGER.info("Memory usage is below threshold: {}", format); + return Health.up().withDetail("memory usage", format).build(); + } else { + return Health.down().withDetail("memory usage", format).build(); + } + }; + + try { + CompletableFuture future = + asynchronousHealthChecker.performCheck(memoryCheck, timeoutInSeconds); + return future.get(); + } catch (InterruptedException e) { + LOGGER.error("Health check interrupted", e); + Thread.currentThread().interrupt(); + return Health.down().withDetail("error", "Health check interrupted").build(); + } catch (ExecutionException e) { + LOGGER.error("Health check failed", e); + Throwable cause = e.getCause() == null ? e : e.getCause(); + return Health.down().withDetail("error", cause.toString()).build(); + } + } + + /** + * Retrieves the health status of the application by checking the memory usage. + * + * @return the health status of the application + */ + @Override + public Health health() { + return checkMemory(); + } +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/RetryConfig.java b/health-check/src/main/java/com/iluwatar/health/check/RetryConfig.java new file mode 100644 index 000000000000..026a4dd11efe --- /dev/null +++ b/health-check/src/main/java/com/iluwatar/health/check/RetryConfig.java @@ -0,0 +1,67 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.health.check; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.retry.backoff.FixedBackOffPolicy; +import org.springframework.retry.policy.SimpleRetryPolicy; +import org.springframework.retry.support.RetryTemplate; +import org.springframework.stereotype.Component; + +/** Configuration class for retry policies used in health check operations. */ +@Configuration +@Component +public class RetryConfig { + + /** The backoff period in milliseconds to wait between retry attempts. */ + @Value("${retry.backoff.period:2000}") + private long backOffPeriod; + + /** The maximum number of retry attempts for health check operations. */ + @Value("${retry.max.attempts:3}") + private int maxAttempts; + + /** + * Creates a retry template with the configured backoff period and maximum number of attempts. + * + * @return a retry template + */ + @Bean + public RetryTemplate retryTemplate() { + RetryTemplate retryTemplate = new RetryTemplate(); + + FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy(); + fixedBackOffPolicy.setBackOffPeriod(backOffPeriod); // wait 2 seconds between retries + retryTemplate.setBackOffPolicy(fixedBackOffPolicy); + + SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); + retryPolicy.setMaxAttempts(maxAttempts); // retry a max of 3 attempts + retryTemplate.setRetryPolicy(retryPolicy); + + return retryTemplate; + } +} diff --git a/health-check/src/main/resources/application.properties b/health-check/src/main/resources/application.properties new file mode 100644 index 000000000000..b981013a2214 --- /dev/null +++ b/health-check/src/main/resources/application.properties @@ -0,0 +1,47 @@ +server.port=6161 +management.endpoints.web.base-path=/actuator +management.endpoint.health.probes.enabled=true +management.health.livenessState.enabled=true +management.health.readinessState.enabled=true +management.endpoints.web.exposure.include=health,info + +management.endpoint.health.show-details=always + +# Enable health check logging +logging.level.com.iluwatar.health.check=DEBUG + +# H2 Database configuration +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +# H2 console available at /h2-console +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console + +# JPA Hibernate ddl auto (none, update, create, create-drop, validate) +spring.jpa.hibernate.ddl-auto=create +spring.jpa.properties.hibernate.format_sql=true +spring.jpa.properties.hibernate.use_sql_comments=true + +# Show SQL statements +spring.jpa.show-sql=true + +# Custom health check configuration +health.check.timeout=10 +health.check.cache.evict.interval=60000 + +# CPU health check configuration +cpu.system.load.threshold=95.0 +cpu.process.load.threshold=70.0 +cpu.load.average.threshold=10.0 +cpu.warning.message=CPU usage is high + +# Retry configuration +retry.backoff.period=2000 +retry.max.attempts=3 + +# Memory health check configuration +memory.usage.threshold = 0.8 \ No newline at end of file diff --git a/health-check/src/test/java/AppTest.java b/health-check/src/test/java/AppTest.java new file mode 100644 index 000000000000..c9cd78366461 --- /dev/null +++ b/health-check/src/test/java/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import com.iluwatar.health.check.App; +import org.junit.jupiter.api.Test; + +/** Application test */ +class AppTest { + + /** Entry point */ + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/health-check/src/test/java/AsynchronousHealthCheckerTest.java b/health-check/src/test/java/AsynchronousHealthCheckerTest.java new file mode 100644 index 000000000000..2241f1989a4f --- /dev/null +++ b/health-check/src/test/java/AsynchronousHealthCheckerTest.java @@ -0,0 +1,243 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import com.iluwatar.health.check.AsynchronousHealthChecker; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; +import java.util.concurrent.*; +import java.util.function.Supplier; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Status; + +/** Tests for {@link AsynchronousHealthChecker}. */ +@Slf4j +class AsynchronousHealthCheckerTest { + + /** The {@link AsynchronousHealthChecker} instance to be tested. */ + private AsynchronousHealthChecker healthChecker; + + private ListAppender listAppender; + + @Mock private ScheduledExecutorService executorService; + + public AsynchronousHealthCheckerTest() { + MockitoAnnotations.openMocks(this); + } + + /** + * Sets up the test environment before each test method. + * + *

    Creates a new {@link AsynchronousHealthChecker} instance. + */ + @BeforeEach + void setUp() { + healthChecker = new AsynchronousHealthChecker(); + // Replace the logger with the root logger of logback + LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + // Create and start a ListAppender + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + listAppender = new ListAppender<>(); + listAppender.start(); + + // Add the appender to the root logger context + loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).addAppender(listAppender); + } + + /** + * Tears down the test environment after each test method. + * + *

    Shuts down the {@link AsynchronousHealthChecker} instance to prevent resource leaks. + */ + @AfterEach + void tearDown() { + healthChecker.shutdown(); + ((LoggerContext) LoggerFactory.getILoggerFactory()).reset(); + } + + /** + * Tests that the {@link performCheck()} method completes normally when the health supplier + * returns a successful health check. + * + *

    Given a health supplier that returns a healthy status, the test verifies that the {@link + * performCheck()} method completes normally and returns the expected health object. + */ + @Test + void whenPerformCheck_thenCompletesNormally() throws ExecutionException, InterruptedException { + // Given + Supplier healthSupplier = () -> Health.up().build(); + + // When + CompletableFuture healthFuture = healthChecker.performCheck(healthSupplier, 3); + + // Then + Health health = healthFuture.get(); + assertEquals(Health.up().build(), health); + } + + /** + * Tests that the {@link performCheck()} method returns a healthy health status when the health + * supplier returns a healthy status. + * + *

    Given a health supplier that returns a healthy status, the test verifies that the {@link + * performCheck()} method returns a health object with a status of UP. + */ + @Test + void whenHealthCheckIsSuccessful_ReturnsHealthy() + throws ExecutionException, InterruptedException { + // Arrange + Supplier healthSupplier = () -> Health.up().build(); + + // Act + CompletableFuture healthFuture = healthChecker.performCheck(healthSupplier, 4); + + // Assert + assertEquals(Status.UP, healthFuture.get().getStatus()); + } + + /** + * Tests that the {@link performCheck()} method rejects new tasks after the {@link shutdown()} + * method is called. + * + *

    Given the {@link AsynchronousHealthChecker} instance is shut down, the test verifies that + * the {@link performCheck()} method throws a {@link RejectedExecutionException} when attempting + * to submit a new health check task. + */ + @Test + void whenShutdown_thenRejectsNewTasks() { + // Given + healthChecker.shutdown(); + + // When/Then + assertThrows( + RejectedExecutionException.class, + () -> healthChecker.performCheck(() -> Health.up().build(), 2), + "Expected to throw RejectedExecutionException but did not"); + } + + /** + * Tests that the {@link performCheck()} method returns a healthy health status when the health + * supplier returns a healthy status. + * + *

    Given a health supplier that throws a RuntimeException, the test verifies that the {@link + * performCheck()} method returns a health object with a status of DOWN and an error message + * containing the exception message. + */ + @Test + void whenHealthCheckThrowsException_thenReturnsDown() { + // Arrange + Supplier healthSupplier = + () -> { + throw new RuntimeException("Health check failed"); + }; + // Act + CompletableFuture healthFuture = healthChecker.performCheck(healthSupplier, 10); + // Assert + Health health = healthFuture.join(); + assertEquals(Status.DOWN, health.getStatus()); + String errorMessage = health.getDetails().get("error").toString(); + assertTrue(errorMessage.contains("Health check failed")); + } + + /** + * Helper method to check if the log contains a specific message. + * + * @param action The action that triggers the log statement. + * @return True if the log contains the message after the action is performed, false otherwise. + */ + private boolean doesLogContainMessage(Runnable action) { + action.run(); + List events = listAppender.list; + return events.stream() + .anyMatch(event -> event.getMessage().contains("Health check executor did not terminate")); + } + + /** + * Tests that the {@link AsynchronousHealthChecker#shutdown()} method logs an error message when + * the executor does not terminate after attempting to cancel tasks. + */ + @Test + void whenShutdownExecutorDoesNotTerminateAfterCanceling_LogsErrorMessage() { + // Given + healthChecker.shutdown(); // To trigger the scenario + + // When/Then + boolean containsMessage = doesLogContainMessage(healthChecker::shutdown); + if (!containsMessage) { + List events = listAppender.list; + LOGGER.info("Logged events:"); + for (ch.qos.logback.classic.spi.ILoggingEvent event : events) { + LOGGER.info(event.getMessage()); + } + } + assertTrue(containsMessage, "Expected log message not found"); + } + + /** + * Verifies that {@link AsynchronousHealthChecker#awaitTerminationWithTimeout} returns true even + * if the executor service does not terminate completely within the specified timeout. + * + * @throws NoSuchMethodException if the private method cannot be accessed. + * @throws InvocationTargetException if the private method throws an exception. + * @throws IllegalAccessException if the private method is not accessible. + * @throws InterruptedException if the thread is interrupted while waiting for the executor + * service to terminate. + */ + @Test + void awaitTerminationWithTimeout_IncompleteTermination_ReturnsTrue() + throws NoSuchMethodException, + InvocationTargetException, + IllegalAccessException, + InterruptedException { + + // Mock executor service to return false (incomplete termination) + when(executorService.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(false); + + // Use reflection to access the private method for code coverage. + Method privateMethod = + AsynchronousHealthChecker.class.getDeclaredMethod("awaitTerminationWithTimeout"); + privateMethod.setAccessible(true); + + // When + boolean result = (boolean) privateMethod.invoke(healthChecker); + + // Then + assertTrue(result, "Termination should be incomplete"); + } +} diff --git a/health-check/src/test/java/CpuHealthIndicatorTest.java b/health-check/src/test/java/CpuHealthIndicatorTest.java new file mode 100644 index 000000000000..c59f3fea7c3f --- /dev/null +++ b/health-check/src/test/java/CpuHealthIndicatorTest.java @@ -0,0 +1,143 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +import com.iluwatar.health.check.CpuHealthIndicator; +import com.sun.management.OperatingSystemMXBean; +import java.lang.reflect.Field; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Status; + +/** Test class for the {@link CpuHealthIndicator} class. */ +class CpuHealthIndicatorTest { + + /** The CPU health indicator to be tested. */ + private CpuHealthIndicator cpuHealthIndicator; + + /** The mocked operating system MXBean used to simulate CPU health information. */ + private OperatingSystemMXBean mockOsBean; + + /** + * Sets up the test environment before each test method. + * + *

    Mocks the {@link OperatingSystemMXBean} and sets it in the {@link CpuHealthIndicator} + * instance. + */ + @BeforeEach + void setUp() { + // Mock the com.sun.management.OperatingSystemMXBean + mockOsBean = Mockito.mock(com.sun.management.OperatingSystemMXBean.class); + cpuHealthIndicator = new CpuHealthIndicator(); + setOperatingSystemMXBean(cpuHealthIndicator, mockOsBean); + } + + /** + * Reflection method to set the private osBean in CpuHealthIndicator. + * + * @param indicator The CpuHealthIndicator instance to set the osBean for. + * @param osBean The OperatingSystemMXBean to set. + */ + private void setOperatingSystemMXBean( + CpuHealthIndicator indicator, OperatingSystemMXBean osBean) { + try { + Field osBeanField = CpuHealthIndicator.class.getDeclaredField("osBean"); + osBeanField.setAccessible(true); + osBeanField.set(indicator, osBean); + } catch (NoSuchFieldException | IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + /** + * Tests that the health status is DOWN when the system CPU load is high. + * + *

    Sets the system CPU load to 90% and mocks the other getters to return appropriate values. + * Executes the health check and asserts that the health status is DOWN and the error message + * indicates high system CPU load. + */ + @Test + void whenSystemCpuLoadIsHigh_thenHealthIsDown() { + // Set thresholds for testing within the test method to avoid issues with Spring's @Value + cpuHealthIndicator.setSystemCpuLoadThreshold(80.0); + cpuHealthIndicator.setProcessCpuLoadThreshold(50.0); + cpuHealthIndicator.setLoadAverageThreshold(0.75); + + // Mock the getters to return your desired values + when(mockOsBean.getCpuLoad()).thenReturn(0.9); // Simulate 90% system CPU load + when(mockOsBean.getAvailableProcessors()).thenReturn(8); + when(mockOsBean.getSystemLoadAverage()).thenReturn(9.0); + + // Execute the health check + Health health = cpuHealthIndicator.health(); + + // Assertions + assertEquals( + Status.DOWN, + health.getStatus(), + "Health status should be DOWN when system CPU load is high"); + assertEquals( + "High system CPU load", + health.getDetails().get("error"), + "Error message should indicate high system CPU load"); + } + + /** + * Tests that the health status is DOWN when the process CPU load is high. + * + *

    Sets the process CPU load to 80% and mocks the other getters to return appropriate values. + * Executes the health check and asserts that the health status is DOWN and the error message + * indicates high process CPU load. + */ + @Test + void whenProcessCpuLoadIsHigh_thenHealthIsDown() { + // Set thresholds for testing within the test method to avoid issues with Spring's @Value + cpuHealthIndicator.setSystemCpuLoadThreshold(80.0); + cpuHealthIndicator.setProcessCpuLoadThreshold(50.0); + cpuHealthIndicator.setLoadAverageThreshold(0.75); + + // Mock the getters to return your desired values + when(mockOsBean.getCpuLoad()).thenReturn(0.5); // Simulate 50% system CPU load + when(mockOsBean.getProcessCpuLoad()).thenReturn(0.8); // Simulate 80% process CPU load + when(mockOsBean.getAvailableProcessors()).thenReturn(8); + when(mockOsBean.getSystemLoadAverage()).thenReturn(5.0); + + // Execute the health check + Health health = cpuHealthIndicator.health(); + + // Assertions + assertEquals( + Status.DOWN, + health.getStatus(), + "Health status should be DOWN when process CPU load is high"); + assertEquals( + "High process CPU load", + health.getDetails().get("error"), + "Error message should indicate high process CPU load"); + } +} diff --git a/health-check/src/test/java/CustomHealthIndicatorTest.java b/health-check/src/test/java/CustomHealthIndicatorTest.java new file mode 100644 index 000000000000..1c48861aac85 --- /dev/null +++ b/health-check/src/test/java/CustomHealthIndicatorTest.java @@ -0,0 +1,158 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.iluwatar.health.check.AsynchronousHealthChecker; +import com.iluwatar.health.check.CustomHealthIndicator; +import com.iluwatar.health.check.HealthCheckRepository; +import java.util.concurrent.CompletableFuture; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Status; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** Tests class< for {@link CustomHealthIndicator}. * */ +class CustomHealthIndicatorTest { + + /** Mocked AsynchronousHealthChecker instance. */ + @Mock private AsynchronousHealthChecker healthChecker; + + /** Mocked CacheManager instance. */ + @Mock private CacheManager cacheManager; + + /** Mocked HealthCheckRepository instance. */ + @Mock private HealthCheckRepository healthCheckRepository; + + /** Mocked Cache instance. */ + @Mock private Cache cache; + + /** `CustomHealthIndicator` instance to be tested. */ + private CustomHealthIndicator customHealthIndicator; + + /** Sets up the test environment. */ + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + when(cacheManager.getCache("health-check")).thenReturn(cache); + customHealthIndicator = + new CustomHealthIndicator(healthChecker, cacheManager, healthCheckRepository); + } + + /** + * Test case for the `health()` method when the database is up. + * + *

    Asserts that when the `health()` method is called and the database is up, it returns a + * Health object with Status.UP. + */ + @Test + void whenDatabaseIsUp_thenHealthIsUp() { + CompletableFuture future = + CompletableFuture.completedFuture(Health.up().withDetail("database", "reachable").build()); + when(healthChecker.performCheck(any(), anyLong())).thenReturn(future); + when(healthCheckRepository.checkHealth()).thenReturn(1); + + Health health = customHealthIndicator.health(); + + assertEquals(Status.UP, health.getStatus()); + } + + /** + * Test case for the `health()` method when the database is down. + * + *

    Asserts that when the `health()` method is called and the database is down, it returns a + * Health object with Status.DOWN. + */ + @Test + void whenDatabaseIsDown_thenHealthIsDown() { + CompletableFuture future = + CompletableFuture.completedFuture( + Health.down().withDetail("database", "unreachable").build()); + when(healthChecker.performCheck(any(), anyLong())).thenReturn(future); + when(healthCheckRepository.checkHealth()).thenReturn(null); + + Health health = customHealthIndicator.health(); + + assertEquals(Status.DOWN, health.getStatus()); + } + + /** + * Test case for the `health()` method when the health check times out. + * + *

    Asserts that when the `health()` method is called and the health check times out, it returns + * a Health object with Status.DOWN. + */ + @Test + void whenHealthCheckTimesOut_thenHealthIsDown() { + CompletableFuture future = new CompletableFuture<>(); + when(healthChecker.performCheck(any(), anyLong())).thenReturn(future); + + Health health = customHealthIndicator.health(); + + assertEquals(Status.DOWN, health.getStatus()); + } + + /** + * Test case for the `evictHealthCache()` method. + * + *

    Asserts that when the `evictHealthCache()` method is called, the health cache is cleared. + */ + @Test + void whenEvictHealthCache_thenCacheIsCleared() { + doNothing().when(cache).clear(); + + customHealthIndicator.evictHealthCache(); + + verify(cache, times(1)).clear(); + verify(cacheManager, times(1)).getCache("health-check"); + } + + /** Configuration static class for the health check cache. */ + @Configuration + static class CacheConfig { + /** + * Creates a concurrent map cache manager named "health-check". + * + * @return a new ConcurrentMapCacheManager instance + */ + @Bean + public CacheManager cacheManager() { + return new ConcurrentMapCacheManager("health-check"); + } + } +} diff --git a/health-check/src/test/java/DatabaseTransactionHealthIndicatorTest.java b/health-check/src/test/java/DatabaseTransactionHealthIndicatorTest.java new file mode 100644 index 000000000000..c396770d19d8 --- /dev/null +++ b/health-check/src/test/java/DatabaseTransactionHealthIndicatorTest.java @@ -0,0 +1,142 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.when; + +import com.iluwatar.health.check.AsynchronousHealthChecker; +import com.iluwatar.health.check.DatabaseTransactionHealthIndicator; +import com.iluwatar.health.check.HealthCheckRepository; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Status; +import org.springframework.retry.support.RetryTemplate; + +/** Unit tests for the {@link DatabaseTransactionHealthIndicator} class. */ +class DatabaseTransactionHealthIndicatorTest { + + /** Timeout value in seconds for the health check. */ + private final long timeoutInSeconds = 4; + + /** Mocked HealthCheckRepository instance. */ + @Mock private HealthCheckRepository healthCheckRepository; + + /** Mocked AsynchronousHealthChecker instance. */ + @Mock private AsynchronousHealthChecker asynchronousHealthChecker; + + /** Mocked RetryTemplate instance. */ + @Mock private RetryTemplate retryTemplate; + + /** `DatabaseTransactionHealthIndicator` instance to be tested. */ + private DatabaseTransactionHealthIndicator healthIndicator; + + /** Performs initialization before each test method. */ + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + healthIndicator = + new DatabaseTransactionHealthIndicator( + healthCheckRepository, asynchronousHealthChecker, retryTemplate); + healthIndicator.setTimeoutInSeconds(timeoutInSeconds); + } + + /** + * Test case for the `health()` method when the database transaction succeeds. + * + *

    Asserts that when the `health()` method is called and the database transaction succeeds, it + * returns a Health object with Status.UP. + */ + @Test + void whenDatabaseTransactionSucceeds_thenHealthIsUp() throws Exception { + CompletableFuture future = CompletableFuture.completedFuture(Health.up().build()); + when(asynchronousHealthChecker.performCheck(any(Supplier.class), eq(timeoutInSeconds))) + .thenReturn(future); + + // Simulate the health check repository behavior + doNothing().when(healthCheckRepository).performTestTransaction(); + + // Now call the actual method + Health health = healthIndicator.health(); + + // Check that the health status is UP + assertEquals(Status.UP, health.getStatus()); + } + + /** + * Test case for the `health()` method when the database transaction fails. + * + *

    Asserts that when the `health()` method is called and the database transaction fails, it + * returns a Health object with Status.DOWN. + */ + @Test + void whenDatabaseTransactionFails_thenHealthIsDown() throws Exception { + CompletableFuture future = new CompletableFuture<>(); + when(asynchronousHealthChecker.performCheck(any(Supplier.class), eq(timeoutInSeconds))) + .thenReturn(future); + + // Simulate a database exception during the transaction + doThrow(new RuntimeException("DB exception")) + .when(healthCheckRepository) + .performTestTransaction(); + + // Complete the future exceptionally to simulate a failure in the health check + future.completeExceptionally(new RuntimeException("DB exception")); + + Health health = healthIndicator.health(); + + // Check that the health status is DOWN + assertEquals(Status.DOWN, health.getStatus()); + } + + /** + * Test case for the `health()` method when the health check times out. + * + *

    Asserts that when the `health()` method is called and the health check times out, it returns + * a Health object with Status.DOWN. + */ + @Test + void whenHealthCheckTimesOut_thenHealthIsDown() { + CompletableFuture future = new CompletableFuture<>(); + when(asynchronousHealthChecker.performCheck(any(Supplier.class), eq(timeoutInSeconds))) + .thenReturn(future); + + // Complete the future exceptionally to simulate a timeout + future.completeExceptionally(new RuntimeException("Simulated timeout")); + + Health health = healthIndicator.health(); + + // Check that the health status is DOWN due to timeout + assertEquals(Status.DOWN, health.getStatus()); + } +} diff --git a/health-check/src/test/java/GarbageCollectionHealthIndicatorTest.java b/health-check/src/test/java/GarbageCollectionHealthIndicatorTest.java new file mode 100644 index 000000000000..6f3068b031d4 --- /dev/null +++ b/health-check/src/test/java/GarbageCollectionHealthIndicatorTest.java @@ -0,0 +1,159 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import com.iluwatar.health.check.GarbageCollectionHealthIndicator; +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.MemoryPoolMXBean; +import java.lang.management.MemoryUsage; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Status; + +/** Test class for {@link GarbageCollectionHealthIndicator}. */ +class GarbageCollectionHealthIndicatorTest { + + /** Mocked garbage collector MXBean. */ + @Mock private GarbageCollectorMXBean garbageCollectorMXBean; + + /** Mocked memory pool MXBean. */ + @Mock private MemoryPoolMXBean memoryPoolMXBean; + + /** Garbage collection health indicator instance to be tested. */ + private GarbageCollectionHealthIndicator healthIndicator; + + /** Set up the test environment before each test case. */ + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + healthIndicator = + spy( + new GarbageCollectionHealthIndicator() { + @Override + protected List getGarbageCollectorMxBeans() { + return Collections.singletonList(garbageCollectorMXBean); + } + + @Override + protected List getMemoryPoolMxBeans() { + return Collections.singletonList(memoryPoolMXBean); + } + }); + healthIndicator.setMemoryUsageThreshold(0.8); + Locale.setDefault(Locale.US); + } + + /** Test case to verify that the health status is up when memory usage is low. */ + @Test + void whenMemoryUsageIsLow_thenHealthIsUp() { + when(garbageCollectorMXBean.getCollectionCount()).thenReturn(100L); + when(garbageCollectorMXBean.getCollectionTime()).thenReturn(1000L); + when(garbageCollectorMXBean.getMemoryPoolNames()).thenReturn(new String[] {"Eden Space"}); + + when(memoryPoolMXBean.getUsage()).thenReturn(new MemoryUsage(0, 100, 500, 1000)); + when(memoryPoolMXBean.getName()).thenReturn("Eden Space"); + + var health = healthIndicator.health(); + assertEquals(Status.UP, health.getStatus()); + } + + /** Test case to verify that the health status contains a warning when memory usage is high. */ + @Test + void whenMemoryUsageIsHigh_thenHealthContainsWarning() { + // Arrange + double threshold = 0.8; // 80% threshold for test + healthIndicator.setMemoryUsageThreshold(threshold); + + String poolName = "CodeCache"; + when(garbageCollectorMXBean.getName()).thenReturn("G1 Young Generation"); + when(garbageCollectorMXBean.getMemoryPoolNames()).thenReturn(new String[] {poolName}); + + long maxMemory = 1000L; // e.g., 1000 bytes + long usedMemory = (long) (threshold * maxMemory) + 1; // e.g., 801 bytes to exceed 80% threshold + when(memoryPoolMXBean.getUsage()) + .thenReturn(new MemoryUsage(0, usedMemory, usedMemory, maxMemory)); + when(memoryPoolMXBean.getName()).thenReturn(poolName); + + // Act + Health health = healthIndicator.health(); + + // Assert + Map gcDetails = + (Map) health.getDetails().get("G1 Young Generation"); + assertNotNull(gcDetails, "Expected details for 'G1 Young Generation', but none were found."); + + String memoryPoolsDetail = (String) gcDetails.get("memoryPools"); + assertNotNull( + memoryPoolsDetail, "Expected memory pool details for 'CodeCache', but none were found."); + + // Extracting the actual usage reported in the details for comparison + String memoryUsageReported = memoryPoolsDetail.split(": ")[1].trim().replace("%", ""); + double memoryUsagePercentage = Double.parseDouble(memoryUsageReported); + + assertTrue( + memoryUsagePercentage > threshold, + "Memory usage percentage should be above the threshold."); + + String warning = (String) gcDetails.get("warning"); + assertNotNull(warning, "Expected a warning for high memory usage, but none was found."); + + // Check that the warning message is as expected + String expectedWarningRegex = + String.format("Memory pool '%s' usage is high \\(\\d+\\.\\d+%%\\)", poolName); + assertTrue( + warning.matches(expectedWarningRegex), + "Expected a high usage warning, but format is incorrect: " + warning); + } + + /** Test case to verify that the health status is up when there are no garbage collections. */ + @Test + void whenNoGarbageCollections_thenHealthIsUp() { + // Arrange: Mock the garbage collector to simulate no collections + when(garbageCollectorMXBean.getCollectionCount()).thenReturn(0L); + when(garbageCollectorMXBean.getCollectionTime()).thenReturn(0L); + when(garbageCollectorMXBean.getName()).thenReturn("G1 Young Generation"); + when(garbageCollectorMXBean.getMemoryPoolNames()).thenReturn(new String[] {}); + + // Act: Perform the health check + Health health = healthIndicator.health(); + + // Assert: Ensure the health is up and there are no warnings + assertEquals(Status.UP, health.getStatus()); + Map gcDetails = + (Map) health.getDetails().get("G1 Young Generation"); + assertNotNull(gcDetails, "Expected details for 'G1 Young Generation', but none were found."); + assertNull( + gcDetails.get("warning"), + "Expected no warning for 'G1 Young Generation' as there are no collections."); + } +} diff --git a/health-check/src/test/java/HealthCheckRepositoryTest.java b/health-check/src/test/java/HealthCheckRepositoryTest.java new file mode 100644 index 000000000000..8a630299dc85 --- /dev/null +++ b/health-check/src/test/java/HealthCheckRepositoryTest.java @@ -0,0 +1,125 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import com.iluwatar.health.check.HealthCheck; +import com.iluwatar.health.check.HealthCheckRepository; +import jakarta.persistence.EntityManager; +import jakarta.persistence.Query; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +/** Tests class for {@link HealthCheckRepository}. */ +@ExtendWith(MockitoExtension.class) +class HealthCheckRepositoryTest { + + /** Mocked EntityManager instance. */ + @Mock private EntityManager entityManager; + + /** `HealthCheckRepository` instance to be tested. */ + @InjectMocks private HealthCheckRepository healthCheckRepository; + + /** + * Test case for the `performTestTransaction()` method. + * + *

    Asserts that when the `performTestTransaction()` method is called, it successfully executes + * a test transaction. + */ + @Test + void whenCheckHealth_thenReturnsOne() { + // Arrange + Query mockedQuery = mock(Query.class); + when(entityManager.createNativeQuery("SELECT 1")).thenReturn(mockedQuery); + when(mockedQuery.getSingleResult()).thenReturn(1); + + // Act + Integer healthCheckResult = healthCheckRepository.checkHealth(); + + // Assert + assertNotNull(healthCheckResult); + assertEquals(1, healthCheckResult); + } + + /** + * Test case for the `performTestTransaction()` method. + * + *

    Asserts that when the `performTestTransaction()` method is called, it successfully executes + * a test transaction. + */ + @Test + void whenPerformTestTransaction_thenSucceeds() { + // Arrange + HealthCheck healthCheck = new HealthCheck(); + healthCheck.setStatus("OK"); + + // Mocking the necessary EntityManager behaviors + when(entityManager.find(eq(HealthCheck.class), any())).thenReturn(healthCheck); + + // Act & Assert + assertDoesNotThrow(() -> healthCheckRepository.performTestTransaction()); + + // Verify the interactions + verify(entityManager).persist(any(HealthCheck.class)); + verify(entityManager).flush(); + verify(entityManager).remove(any(HealthCheck.class)); + } + + /** + * Test case for the `checkHealth()` method when the database is down. + * + *

    Asserts that when the `checkHealth()` method is called and the database is down, it throws a + * RuntimeException. + */ + @Test + void whenCheckHealth_andDatabaseIsDown_thenThrowsException() { + // Arrange + when(entityManager.createNativeQuery("SELECT 1")).thenThrow(RuntimeException.class); + + // Act & Assert + assertThrows(RuntimeException.class, () -> healthCheckRepository.checkHealth()); + } + + /** + * Test case for the `performTestTransaction()` method when the persist operation fails. + * + *

    Asserts that when the `performTestTransaction()` method is called and the persist operation + * fails, it throws a RuntimeException. + */ + @Test + void whenPerformTestTransaction_andPersistFails_thenThrowsException() { + // Arrange + doThrow(new RuntimeException()).when(entityManager).persist(any(HealthCheck.class)); + + // Act & Assert + assertThrows(RuntimeException.class, () -> healthCheckRepository.performTestTransaction()); + + // Verify that remove is not called if persist fails + verify(entityManager, never()).remove(any(HealthCheck.class)); + } +} diff --git a/health-check/src/test/java/HealthEndpointIntegrationTest.java b/health-check/src/test/java/HealthEndpointIntegrationTest.java new file mode 100644 index 000000000000..0d0a3d8f8052 --- /dev/null +++ b/health-check/src/test/java/HealthEndpointIntegrationTest.java @@ -0,0 +1,235 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +import com.iluwatar.health.check.App; +import io.restassured.builder.RequestSpecBuilder; +import io.restassured.filter.log.LogDetail; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; + +/** + * Integration tests for the health endpoint. + * + *

    * * Log statement for the test case response in case of "DOWN" status with high CPU load + * during pipeline execution. * Note: During pipeline execution, if the health check shows "DOWN" + * status with high CPU load, it is expected behavior. The service checks CPU usage, and if it's not + * under 90%, it returns this error, example return value: + * {"status":"DOWN","components":{"cpu":{"status":"DOWN","details":{"processCpuLoad":"100.00%", * + * "availableProcessors":2,"systemCpuLoad":"100.00%","loadAverage":1.97,"timestamp":"2023-11-09T08:34:15.974557865Z", + * * "error":"High system CPU load"}}} * + */ +@Slf4j +@SpringBootTest( + classes = {App.class}, + webEnvironment = WebEnvironment.RANDOM_PORT) +class HealthEndpointIntegrationTest { + + /** Autowired TestRestTemplate instance for making HTTP requests. */ + @Autowired private TestRestTemplate restTemplate; + + // Create a RequestSpecification that logs the request details + private final RequestSpecification requestSpec = + new RequestSpecBuilder().log(LogDetail.ALL).build(); + + private String getEndpointBasePath() { + return restTemplate.getRootUri() + "/actuator/health"; + } + + // Common method to log response details + private void logResponseDetails(Response response) { + LOGGER.info("Request URI: " + response.getDetailedCookies()); + LOGGER.info("Response Time: " + response.getTime() + "ms"); + LOGGER.info("Response Status: " + response.getStatusCode()); + LOGGER.info("Response: " + response.getBody().asString()); + } + + /** Test that the health endpoint returns the UP status. */ + @Test + void healthEndpointReturnsUpStatus() { + Response response = given(requestSpec).get(getEndpointBasePath()).andReturn(); + logResponseDetails(response); + + if (response.getStatusCode() == HttpStatus.SERVICE_UNAVAILABLE.value()) { + LOGGER.warn( + "Health endpoint returned 503 Service Unavailable. This may be due to pipeline " + + "configuration. Please check the pipeline logs."); + response.then().assertThat().statusCode(HttpStatus.SERVICE_UNAVAILABLE.value()); + return; + } + + if (response.getStatusCode() != HttpStatus.OK.value() + || !"UP".equals(response.path("status"))) { + LOGGER.error("Health endpoint response: " + response.getBody().asString()); + LOGGER.error("Health endpoint status: " + response.getStatusCode()); + } + + response.then().assertThat().statusCode(HttpStatus.OK.value()).body("status", equalTo("UP")); + } + + /** + * Test that the health endpoint returns complete details about the application's health. If the + * status is 503, the test passes without further checks. If the status is 200, additional checks + * are performed on various components. In case of a "DOWN" status, the test logs the entire + * response for visibility. + */ + @Test + void healthEndpointReturnsCompleteDetails() { + // Make the HTTP request to the health endpoint + Response response = given(requestSpec).get(getEndpointBasePath()).andReturn(); + + // Log the response details + logResponseDetails(response); + + // Check if the status is 503 (SERVICE_UNAVAILABLE) + if (response.getStatusCode() == HttpStatus.SERVICE_UNAVAILABLE.value()) { + LOGGER.warn( + "Health endpoint returned 503 Service Unavailable. This may be due to CI pipeline " + + "configuration. Please check the CI pipeline logs."); + response + .then() + .assertThat() + .statusCode(HttpStatus.SERVICE_UNAVAILABLE.value()) + .log() + .all(); // Log the entire response for visibility + return; + } + + // If status is 200, proceed with additional checks + response + .then() + .assertThat() + .statusCode(HttpStatus.OK.value()) // Check that the status is UP + .body("status", equalTo("UP")) // Verify the status body is UP + .body("components.cpu.status", equalTo("UP")) // Check CPU status + .body("components.db.status", equalTo("UP")) // Check DB status + .body("components.diskSpace.status", equalTo("UP")) // Check disk space status + .body("components.ping.status", equalTo("UP")) // Check ping status + .body("components.custom.status", equalTo("UP")); // Check custom component status + + // Check for "DOWN" status and high CPU load + if ("DOWN".equals(response.path("status"))) { + LOGGER.error("Health endpoint response: " + response.getBody().asString()); + LOGGER.error("Health endpoint status: " + response.path("status")); + LOGGER.error( + "High CPU load detected: " + response.path("components.cpu.details.processCpuLoad")); + } + } + + /** + * Test that the liveness endpoint returns the UP status. + * + *

    The liveness endpoint is used to indicate whether the application is still running and + * responsive. + */ + @Test + void livenessEndpointShouldReturnUpStatus() { + // Make the HTTP request to the liveness endpoint + Response response = given(requestSpec).get(getEndpointBasePath() + "/liveness").andReturn(); + + // Log the response details + logResponseDetails(response); + + // Check if the status is 503 (SERVICE_UNAVAILABLE) + if (response.getStatusCode() == HttpStatus.SERVICE_UNAVAILABLE.value()) { + LOGGER.warn( + "Liveness endpoint returned 503 Service Unavailable. This may be due to CI pipeline " + + "configuration. Please check the CI pipeline logs."); + // If status is 503, the test passes without further checks + response + .then() + .assertThat() + .statusCode(HttpStatus.SERVICE_UNAVAILABLE.value()) + .log() + .all(); // Log the entire response for visibility + return; + } + + // If status is 200, proceed with additional checks + response.then().assertThat().statusCode(HttpStatus.OK.value()).body("status", equalTo("UP")); + + // Check for "DOWN" status and high CPU load + if ("DOWN".equals(response.path("status"))) { + LOGGER.error("Liveness endpoint response: " + response.getBody().asString()); + LOGGER.error("Liveness endpoint status: " + response.path("status")); + LOGGER.error( + "High CPU load detected: " + response.path("components.cpu.details.processCpuLoad")); + } + } + + /** + * Test that the custom health indicator returns the UP status and additional details. + * + *

    The custom health indicator is used to provide more specific information about the health of + * a particular component or aspect of the application. + */ + @Test + void customHealthIndicatorShouldReturnUpStatusAndDetails() { + // Make the HTTP request to the health endpoint + Response response = given(requestSpec).get(getEndpointBasePath()).andReturn(); + + // Log the response details + logResponseDetails(response); + + // Check if the status is 503 (SERVICE_UNAVAILABLE) + if (response.getStatusCode() == HttpStatus.SERVICE_UNAVAILABLE.value()) { + LOGGER.warn( + "Custom health indicator returned 503 Service Unavailable. This may be due to CI pipeline " + + "configuration. Please check the CI pipeline logs."); + // If status is 503, the test passes without further checks + response + .then() + .assertThat() + .statusCode(HttpStatus.SERVICE_UNAVAILABLE.value()) + .log() + .all(); // Log the entire response for visibility + return; + } + + // If status is 200, proceed with additional checks + response + .then() + .assertThat() + .statusCode(HttpStatus.OK.value()) // Check that the status is UP + .body("components.custom.status", equalTo("UP")) // Verify the custom component status + .body("components.custom.details.database", equalTo("reachable")); // Verify custom details + + // Check for "DOWN" status and high CPU load + if ("DOWN".equals(response.path("status"))) { + LOGGER.error("Custom health indicator response: " + response.getBody().asString()); + LOGGER.error("Custom health indicator status: " + response.path("status")); + LOGGER.error( + "High CPU load detected: " + response.path("components.cpu.details.processCpuLoad")); + } + } +} diff --git a/health-check/src/test/java/MemoryHealthIndicatorTest.java b/health-check/src/test/java/MemoryHealthIndicatorTest.java new file mode 100644 index 000000000000..8b8da1613408 --- /dev/null +++ b/health-check/src/test/java/MemoryHealthIndicatorTest.java @@ -0,0 +1,148 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.iluwatar.health.check.AsynchronousHealthChecker; +import com.iluwatar.health.check.MemoryHealthIndicator; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Status; + +/** Unit tests for {@link MemoryHealthIndicator}. */ +@ExtendWith(MockitoExtension.class) +class MemoryHealthIndicatorTest { + + /** Mocked AsynchronousHealthChecker instance. */ + @Mock private AsynchronousHealthChecker asynchronousHealthChecker; + + /** `MemoryHealthIndicator` instance to be tested. */ + @InjectMocks private MemoryHealthIndicator memoryHealthIndicator; + + /** + * Test case for the `health()` method when memory usage is below the threshold. + * + *

    Asserts that when the `health()` method is called and memory usage is below the threshold, + * it returns a Health object with Status.UP. + */ + @Test + void whenMemoryUsageIsBelowThreshold_thenHealthIsUp() { + // Arrange + CompletableFuture future = + CompletableFuture.completedFuture( + Health.up().withDetail("memory usage", "50% of max").build()); + when(asynchronousHealthChecker.performCheck(any(Supplier.class), anyLong())).thenReturn(future); + + // Act + Health health = memoryHealthIndicator.health(); + + // Assert + assertEquals(Status.UP, health.getStatus()); + assertEquals("50% of max", health.getDetails().get("memory usage")); + } + + /** + * Test case for the `health()` method when memory usage is above the threshold. + * + *

    Asserts that when the `health()` method is called and memory usage is above the threshold, + * it returns a Health object with Status.DOWN. + */ + @Test + void whenMemoryUsageIsAboveThreshold_thenHealthIsDown() { + // Arrange + CompletableFuture future = + CompletableFuture.completedFuture( + Health.down().withDetail("memory usage", "95% of max").build()); + when(asynchronousHealthChecker.performCheck(any(Supplier.class), anyLong())).thenReturn(future); + + // Act + Health health = memoryHealthIndicator.health(); + + // Assert + assertEquals(Status.DOWN, health.getStatus()); + assertEquals("95% of max", health.getDetails().get("memory usage")); + } + + /** + * Test case for the `health()` method when the health check is interrupted. + * + *

    Asserts that when the `health()` method is called and the health check is interrupted, it + * returns a Health object with Status DOWN and an error detail indicating the interruption. + * + * @throws ExecutionException if the future fails to complete + * @throws InterruptedException if the thread is interrupted while waiting for the future to + * complete + */ + @Test + void whenHealthCheckIsInterrupted_thenHealthIsDown() + throws ExecutionException, InterruptedException { + // Arrange + CompletableFuture future = mock(CompletableFuture.class); + when(asynchronousHealthChecker.performCheck(any(Supplier.class), anyLong())).thenReturn(future); + // Simulate InterruptedException when future.get() is called + when(future.get()).thenThrow(new InterruptedException("Health check interrupted")); + + // Act + Health health = memoryHealthIndicator.health(); + + // Assert + assertEquals(Status.DOWN, health.getStatus()); + String errorDetail = (String) health.getDetails().get("error"); + assertNotNull(errorDetail); + assertTrue(errorDetail.contains("Health check interrupted")); + } + + /** + * Test case for the `health()` method when the health check execution fails. + * + *

    Asserts that when the `health()` method is called and the health check execution fails, it + * returns a Health object with Status DOWN and an error detail indicating the failure. + */ + @Test + void whenHealthCheckExecutionFails_thenHealthIsDown() { + // Arrange + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally( + new ExecutionException(new RuntimeException("Service unavailable"))); + when(asynchronousHealthChecker.performCheck(any(Supplier.class), anyLong())).thenReturn(future); + + // Act + Health health = memoryHealthIndicator.health(); + + // Assert + assertEquals(Status.DOWN, health.getStatus()); + assertTrue(health.getDetails().get("error").toString().contains("Service unavailable")); + } +} diff --git a/health-check/src/test/java/RetryConfigTest.java b/health-check/src/test/java/RetryConfigTest.java new file mode 100644 index 000000000000..947616e45f18 --- /dev/null +++ b/health-check/src/test/java/RetryConfigTest.java @@ -0,0 +1,74 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.health.check.RetryConfig; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.retry.support.RetryTemplate; + +/** Unit tests for the {@link RetryConfig} class. */ +@SpringBootTest(classes = RetryConfig.class) +class RetryConfigTest { + + /** Injected RetryTemplate instance. */ + @Autowired private RetryTemplate retryTemplate; + + /** + * Tests that the retry template retries three times with a two-second delay. + * + *

    Verifies that the retryable operation is executed three times before throwing an exception, + * and that the total elapsed time for the retries is at least four seconds. + */ + @Test + void shouldRetryThreeTimesWithTwoSecondDelay() { + AtomicInteger attempts = new AtomicInteger(); + Runnable retryableOperation = + () -> { + attempts.incrementAndGet(); + throw new RuntimeException("Test exception for retry"); + }; + + long startTime = System.currentTimeMillis(); + try { + retryTemplate.execute( + context -> { + retryableOperation.run(); + return null; + }); + } catch (Exception e) { + // Expected exception + } + long endTime = System.currentTimeMillis(); + + assertEquals(3, attempts.get(), "Should have retried three times"); + assertTrue( + (endTime - startTime) >= 4000, + "Should have waited at least 4 seconds in total for backoff"); + } +} diff --git a/hexagonal-architecture/README.md b/hexagonal-architecture/README.md new file mode 100644 index 000000000000..d6fea210a008 --- /dev/null +++ b/hexagonal-architecture/README.md @@ -0,0 +1,211 @@ +--- +title: "Hexagonal Architecture Pattern in Java: Decoupling Core Logic for Enhanced Flexibility" +shortTitle: Hexagonal Architecture +description: "Explore the Hexagonal Architecture pattern in Java. Learn how it decouples core logic from external interfaces, enhances maintainability, and improves testability with practical examples." +category: Architectural +language: en +tag: + - Decoupling + - Layered architecture +--- + +## Also known as + +* Ports and Adapters + +## Intent of Hexagonal Architecture Design Pattern + +Hexagonal Architecture, also known as Ports and Adapters, is a design pattern in Java that promotes decoupling of core business logic from external interfaces like databases and user interfaces. This architectural approach enhances maintainability and testability of software systems. + +## Detailed Explanation of Hexagonal Architecture Pattern with Real-World Examples + +Real-world example + +> In online banking systems, Hexagonal Architecture allows core banking logic to remain unaffected by changes in user interfaces or third-party services. This decoupling ensures the system's maintainability and flexibility. In such systems, the core banking logic (like processing transactions, managing accounts, and calculating interest) represents the application's core. This core is then surrounded by various adapters that allow the system to interact with different external interfaces without affecting the business logic. For instance, customers might access their accounts through a web interface, a mobile app, or even through ATM services. Meanwhile, the banking system also needs to interface with external services for credit checks, fraud detection, and interbank transactions. Each of these interfaces interacts with the core banking logic through specific adapters designed to translate the external calls to and from the application's internal APIs. This setup allows the bank to modify or extend its external interfaces without having to alter the core business logic, enhancing flexibility and maintainability. + +In plain words + +> Hexagonal Architecture organizes an application into a central core of business logic surrounded by ports and adapters that manage interactions with external systems like user interfaces and databases, allowing the core to remain independent of external concerns. + +Wikipedia says + +> The hexagonal architecture, or ports and adapters architecture, is an architectural pattern used in software design. It aims at creating loosely coupled application components that can be easily connected to their software environment by means of ports and adapters. This makes components exchangeable at any level and facilitates test automation. + +Architecture diagram + +![Hexagonal Architecture Diagram](./etc/hexagonal-architecture-diagram.png) + + +## Programmatic Example of Hexagonal Architecture Pattern in Java + +The Hexagonal Architecture, also known as Ports and Adapters, is a design pattern that aims to create a loosely coupled application where the core business logic is isolated from external interfaces like databases, user interfaces, or third-party services. This allows the core application to be independent and easily testable. + +The Java code example below illustrates how Hexagonal Architecture isolates core business logic using dependency injection, making the application highly testable and independent from external components. + +In the provided code, we can see an example of the Hexagonal Architecture pattern in the `App` class and the use of Google's Guice for dependency injection. + +The `App` class is the entry point of the application. It creates an instance of `LotteryAdministration` and `LotteryService` through dependency injection and uses them to handle various tasks. + +```java +public class App { + + public static void main(String[] args) { + + var injector = Guice.createInjector(new LotteryTestingModule()); + + // start new lottery round + var administration = injector.getInstance(LotteryAdministration.class); + administration.resetLottery(); + + // submit some lottery tickets + var service = injector.getInstance(LotteryService.class); + SampleData.submitTickets(service, 20); + + // perform lottery + administration.performLottery(); + } +} +``` + +The `LotteryAdministration` class is responsible for managing the lottery rounds. It has methods to start a new round, perform the lottery, and reset the lottery. + +```java +public class LotteryAdministration { + + private final LotteryTicketRepository repository; + private final LotteryEventLog notifications; + private final WireTransfers wireTransfers; + + @Inject + public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog notifications, + WireTransfers wireTransfers) { + this.repository = repository; + this.notifications = notifications; + this.wireTransfers = wireTransfers; + } + + public Map getAllSubmittedTickets() { + return repository.findAll(); + } + + public LotteryNumbers performLottery() { + // Implementation details... + } + + public void resetLottery() { + repository.deleteAll(); + } +} +``` + +The `LotteryService` class is responsible for managing the lottery tickets. It has methods to submit a ticket, check a ticket's status, and get the winning ticket. + +```java +public class LotteryService { + + private final LotteryTicketRepository repository; + private final LotteryEventLog notifications; + private final WireTransfers wireTransfers; + + @Inject + public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifications, + WireTransfers wireTransfers) { + this.repository = repository; + this.notifications = notifications; + this.wireTransfers = wireTransfers; + } + + public Optional submitTicket(LotteryTicket ticket) { + // Implementation details... + } + + public LotteryTicketCheckResult checkTicketForPrize( + LotteryTicketId id, + LotteryNumbers winningNumbers + ) { + // Implementation details... + } +} +``` + +Running the main function of App class produces the following output: + +``` +11:06:58.357 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was submitted. Bank account 334-746 was charged for 3 credits. +11:06:58.359 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for arnold@google.com was submitted. Bank account 114-988 was charged for 3 credits. +11:06:58.359 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for ollie@google.com was submitted. Bank account 190-045 was charged for 3 credits. +11:06:58.359 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for peter@google.com was submitted. Bank account 335-886 was charged for 3 credits. +11:06:58.359 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for ray@google.com was submitted. Bank account 843-073 was charged for 3 credits. +11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was submitted. Bank account 334-746 was charged for 3 credits. +11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for lisa@google.com was submitted. Bank account 024-653 was charged for 3 credits. +11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for harriet@google.com was submitted. Bank account 842-404 was charged for 3 credits. +11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for larry@google.com was submitted. Bank account 734-853 was charged for 3 credits. +11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for lars@google.com was submitted. Bank account 746-936 was charged for 3 credits. +11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for tyron@google.com was submitted. Bank account 310-992 was charged for 3 credits. +11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for xavier@google.com was submitted. Bank account 143-947 was charged for 3 credits. +11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for kevin@google.com was submitted. Bank account 453-936 was charged for 3 credits. +11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for yngwie@google.com was submitted. Bank account 241-465 was charged for 3 credits. +11:06:58.361 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was submitted. Bank account 334-746 was charged for 3 credits. +11:06:58.361 [main] ERROR com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for larry@google.com could not be submitted because the credit transfer of 3 credits failed. +11:06:58.362 [main] ERROR com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for larry@google.com could not be submitted because the credit transfer of 3 credits failed. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for mary@google.com was submitted. Bank account 234-987 was charged for 3 credits. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for edwin@google.com was submitted. Bank account 895-345 was charged for 3 credits. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for jacob@google.com was submitted. Bank account 444-766 was charged for 3 credits. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for ollie@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for jacob@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for peter@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for ray@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for lisa@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for harriet@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for larry@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for lars@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for tyron@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for xavier@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for kevin@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for yngwie@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for mary@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for arnold@google.com was checked and unfortunately did not win this time. +11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for edwin@google.com was checked and unfortunately did not win this time. +``` + +In this example, the `LotteryAdministration` and `LotteryService` classes are the core of the application. They interact with external interfaces like `LotteryTicketRepository`, `LotteryEventLog`, and `WireTransfers` through dependency injection, keeping the core business logic decoupled from external concerns. This is a basic example of the Hexagonal Architecture pattern, where the core application is at the center of input/output systems. + +## When to Use the Hexagonal Architecture Pattern in Java + +Hexagonal Architecture is particularly beneficial in scenarios: + +* The application needs to interact with multiple external systems. +* There is a requirement for high testability and maintainability. +* The application should remain unaffected by changes in external interfaces. + +## Real-World Applications of Hexagonal Architecture Pattern in Java + +* Implemented extensively within enterprise applications that leverage frameworks like Spring. +* Used in microservices architectures to maintain clear boundaries and protocols between services. +* Adopted in systems that require integration with various databases or external APIs without impacting the business logic. + +## Benefits and Trade-offs of Hexagonal Architecture Pattern + +Benefits: + +* Improved Testability: Allows the core functionality to be tested independently of external components. +* Flexibility: Facilitates the addition or replacement of components that interact with the application without modifying the core business logic. +* Maintainability: Reduces dependencies on external interfaces, simplifying upgrades and maintenance. + +Trade-offs: + +* Complexity: Introduces more abstractions and layers, which can complicate the system design and understanding. +* Overhead: Might be an over-engineering for simple applications, where simpler architectural patterns could suffice. + +## Related Java Design Patterns + +* [Layered Architecture](https://java-design-patterns.com/patterns/layers/): Shares the concept of organizing code into responsibilities; however, Hexagonal emphasizes port-based interaction with external elements. +* Microservices: Often used in conjunction with Hexagonal Architecture to define clear boundaries and protocols between services. + +## References and Credits + +* [Implementing Domain-Driven Design](https://amzn.to/4dmBjrB) +* [Building Microservices](https://amzn.to/3UACtrU) diff --git a/hexagonal-architecture/etc/hexagonal-architecture-diagram.png b/hexagonal-architecture/etc/hexagonal-architecture-diagram.png new file mode 100644 index 000000000000..39ca7d99b2d4 Binary files /dev/null and b/hexagonal-architecture/etc/hexagonal-architecture-diagram.png differ diff --git a/hexagonal-architecture/etc/hexagonal-architecture.urm.puml b/hexagonal-architecture/etc/hexagonal-architecture.urm.puml new file mode 100644 index 000000000000..f86e734747f3 --- /dev/null +++ b/hexagonal-architecture/etc/hexagonal-architecture.urm.puml @@ -0,0 +1,282 @@ +@startuml +package com.iluwatar.hexagonal.sampledata { + class SampleData { + - PLAYERS : List {static} + - RANDOM : SecureRandom {static} + + SampleData() + - getRandomPlayerDetails() : PlayerDetails {static} + + submitTickets(lotteryService : LotteryService, numTickets : int) {static} + } +} +package com.iluwatar.hexagonal.service { + class ConsoleLottery { + - LOGGER : Logger {static} + + ConsoleLottery() + + main(args : String[]) {static} + - printMainMenu() {static} + - readString(scanner : Scanner) : String {static} + } + interface LotteryConsoleService { + + addFundsToLotteryAccount(WireTransfers, Scanner) {abstract} + + checkTicket(LotteryService, Scanner) {abstract} + + queryLotteryAccountFunds(WireTransfers, Scanner) {abstract} + + submitTicket(LotteryService, Scanner) {abstract} + } + class LotteryConsoleServiceImpl { + - logger : Logger + + LotteryConsoleServiceImpl(logger : Logger) + + addFundsToLotteryAccount(bank : WireTransfers, scanner : Scanner) + + checkTicket(service : LotteryService, scanner : Scanner) + + queryLotteryAccountFunds(bank : WireTransfers, scanner : Scanner) + - readString(scanner : Scanner) : String + + submitTicket(service : LotteryService, scanner : Scanner) + } +} +package com.iluwatar.hexagonal.mongo { + class MongoConnectionPropertiesLoader { + - DEFAULT_HOST : String {static} + - DEFAULT_PORT : int {static} + - LOGGER : Logger {static} + + MongoConnectionPropertiesLoader() + + load() {static} + } +} +package com.iluwatar.hexagonal.domain { + class LotteryAdministration { + - notifications : LotteryEventLog + - repository : LotteryTicketRepository + - wireTransfers : WireTransfers + + LotteryAdministration(repository : LotteryTicketRepository, notifications : LotteryEventLog, wireTransfers : WireTransfers) + + getAllSubmittedTickets() : Map + + performLottery() : LotteryNumbers + + resetLottery() + } + class LotteryConstants { + + PLAYER_MAX_BALANCE : int {static} + + PRIZE_AMOUNT : int {static} + + SERVICE_BANK_ACCOUNT : String {static} + + SERVICE_BANK_ACCOUNT_BALANCE : int {static} + + TICKET_PRIZE : int {static} + - LotteryConstants() + } + class LotteryNumbers { + + MAX_NUMBER : int {static} + + MIN_NUMBER : int {static} + + NUM_NUMBERS : int {static} + - numbers : Set + - LotteryNumbers() + - LotteryNumbers(givenNumbers : Set) + # canEqual(other : Object) : boolean + + create(givenNumbers : Set) : LotteryNumbers {static} + + createRandom() : LotteryNumbers {static} + + equals(o : Object) : boolean + - generateRandomNumbers() + + getNumbers() : Set + + getNumbersAsString() : String + + hashCode() : int + + toString() : String + } + -class RandomNumberGenerator { + - randomIterator : OfInt + + RandomNumberGenerator(min : int, max : int) + + nextInt() : int + } + class LotteryService { + - notifications : LotteryEventLog + - repository : LotteryTicketRepository + - wireTransfers : WireTransfers + + LotteryService(repository : LotteryTicketRepository, notifications : LotteryEventLog, wireTransfers : WireTransfers) + + checkTicketForPrize(id : LotteryTicketId, winningNumbers : LotteryNumbers) : LotteryTicketCheckResult + + submitTicket(ticket : LotteryTicket) : Optional + } + class LotteryTicketCheckResult { + - prizeAmount : int + - result : CheckResult + + LotteryTicketCheckResult(result : CheckResult) + + LotteryTicketCheckResult(result : CheckResult, prizeAmount : int) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getPrizeAmount() : int + + getResult() : CheckResult + + hashCode() : int + } + enum CheckResult { + + NO_PRIZE {static} + + TICKET_NOT_SUBMITTED {static} + + WIN_PRIZE {static} + + valueOf(name : String) : CheckResult {static} + + values() : CheckResult[] {static} + } + class LotteryTicketId { + - id : int + - numAllocated : AtomicInteger {static} + + LotteryTicketId() + + LotteryTicketId(id : int) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getId() : int + + hashCode() : int + + toString() : String + } + class LotteryUtils { + - LotteryUtils() + + checkTicketForPrize(repository : LotteryTicketRepository, id : LotteryTicketId, winningNumbers : LotteryNumbers) : LotteryTicketCheckResult {static} + } +} +package com.iluwatar.hexagonal.banking { + class InMemoryBank { + - accounts : Map {static} + + InMemoryBank() + + getFunds(bankAccount : String) : int + + setFunds(bankAccount : String, amount : int) + + transferFunds(amount : int, sourceAccount : String, destinationAccount : String) : boolean + } + class MongoBank { + - DEFAULT_ACCOUNTS_COLLECTION : String {static} + - DEFAULT_DB : String {static} + - accountsCollection : MongoCollection + - database : MongoDatabase + - mongoClient : MongoClient + + MongoBank() + + MongoBank(dbName : String, accountsCollectionName : String) + + connect() + + connect(dbName : String, accountsCollectionName : String) + + getAccountsCollection() : MongoCollection + + getDatabase() : MongoDatabase + + getFunds(bankAccount : String) : int + + getMongoClient() : MongoClient + + setFunds(bankAccount : String, amount : int) + + transferFunds(amount : int, sourceAccount : String, destinationAccount : String) : boolean + } + interface WireTransfers { + + getFunds(String) : int {abstract} + + setFunds(String, int) {abstract} + + transferFunds(int, String, String) : boolean {abstract} + } +} +package com.iluwatar.hexagonal.database { + class InMemoryTicketRepository { + - tickets : Map {static} + + InMemoryTicketRepository() + + deleteAll() + + findAll() : Map + + findById(id : LotteryTicketId) : Optional + + save(ticket : LotteryTicket) : Optional + } + interface LotteryTicketRepository { + + deleteAll() {abstract} + + findAll() : Map {abstract} + + findById(LotteryTicketId) : Optional {abstract} + + save(LotteryTicket) : Optional {abstract} + } + class MongoTicketRepository { + - DEFAULT_COUNTERS_COLLECTION : String {static} + - DEFAULT_DB : String {static} + - DEFAULT_TICKETS_COLLECTION : String {static} + - TICKET_ID : String {static} + - countersCollection : MongoCollection + - database : MongoDatabase + - mongoClient : MongoClient + - ticketsCollection : MongoCollection + + MongoTicketRepository() + + MongoTicketRepository(dbName : String, ticketsCollectionName : String, countersCollectionName : String) + + connect() + + connect(dbName : String, ticketsCollectionName : String, countersCollectionName : String) + + deleteAll() + - docToTicket(doc : Document) : LotteryTicket + + findAll() : Map + + findById(id : LotteryTicketId) : Optional + + getCountersCollection() : MongoCollection + + getNextId() : int + + getTicketsCollection() : MongoCollection + - initCounters() + + save(ticket : LotteryTicket) : Optional + } +} +package com.iluwatar.hexagonal { + class App { + + App() + + main(args : String[]) {static} + } +} +package com.iluwatar.hexagonal.administration { + class ConsoleAdministration { + - LOGGER : Logger {static} + + ConsoleAdministration() + + main(args : String[]) {static} + - printMainMenu() {static} + - readString(scanner : Scanner) : String {static} + } + interface ConsoleAdministrationSrv { + + getAllSubmittedTickets() {abstract} + + performLottery() {abstract} + + resetLottery() {abstract} + } + class ConsoleAdministrationSrvImpl { + - administration : LotteryAdministration + - logger : Logger + + ConsoleAdministrationSrvImpl(administration : LotteryAdministration, logger : Logger) + + getAllSubmittedTickets() + + performLottery() + + resetLottery() + } +} +package com.iluwatar.hexagonal.eventlog { + interface LotteryEventLog { + + prizeError(PlayerDetails, int) {abstract} + + ticketDidNotWin(PlayerDetails) {abstract} + + ticketSubmitError(PlayerDetails) {abstract} + + ticketSubmitted(PlayerDetails) {abstract} + + ticketWon(PlayerDetails, int) {abstract} + } + class MongoEventLog { + - DEFAULT_DB : String {static} + - DEFAULT_EVENTS_COLLECTION : String {static} + - EMAIL : String {static} + + MESSAGE : String {static} + - PHONE : String {static} + - database : MongoDatabase + - eventsCollection : MongoCollection + - mongoClient : MongoClient + - stdOutEventLog : StdOutEventLog + + MongoEventLog() + + MongoEventLog(dbName : String, eventsCollectionName : String) + + connect() + + connect(dbName : String, eventsCollectionName : String) + + getDatabase() : MongoDatabase + + getEventsCollection() : MongoCollection + + getMongoClient() : MongoClient + + prizeError(details : PlayerDetails, prizeAmount : int) + + ticketDidNotWin(details : PlayerDetails) + + ticketSubmitError(details : PlayerDetails) + + ticketSubmitted(details : PlayerDetails) + + ticketWon(details : PlayerDetails, prizeAmount : int) + } + class StdOutEventLog { + - LOGGER : Logger {static} + + StdOutEventLog() + + prizeError(details : PlayerDetails, prizeAmount : int) + + ticketDidNotWin(details : PlayerDetails) + + ticketSubmitError(details : PlayerDetails) + + ticketSubmitted(details : PlayerDetails) + + ticketWon(details : PlayerDetails, prizeAmount : int) + } +} +LotteryAdministration --> "-wireTransfers" WireTransfers +LotteryService --> "-notifications" LotteryEventLog +LotteryAdministration --> "-repository" LotteryTicketRepository +MongoEventLog --> "-stdOutEventLog" StdOutEventLog +LotteryService --> "-wireTransfers" WireTransfers +LotteryAdministration --> "-notifications" LotteryEventLog +ConsoleAdministrationSrvImpl --> "-administration" LotteryAdministration +LotteryService --> "-repository" LotteryTicketRepository +LotteryTicketCheckResult --> "-result" CheckResult +ConsoleAdministrationSrvImpl ..|> ConsoleAdministrationSrv +InMemoryBank ..|> WireTransfers +MongoBank ..|> WireTransfers +InMemoryTicketRepository ..|> LotteryTicketRepository +MongoTicketRepository ..|> LotteryTicketRepository +MongoEventLog ..|> LotteryEventLog +StdOutEventLog ..|> LotteryEventLog +LotteryConsoleServiceImpl ..|> LotteryConsoleService +@enduml \ No newline at end of file diff --git a/hexagonal/etc/hexagonal.png b/hexagonal-architecture/etc/hexagonal.png similarity index 100% rename from hexagonal/etc/hexagonal.png rename to hexagonal-architecture/etc/hexagonal.png diff --git a/hexagonal/etc/hexagonal.ucls b/hexagonal-architecture/etc/hexagonal.ucls similarity index 100% rename from hexagonal/etc/hexagonal.ucls rename to hexagonal-architecture/etc/hexagonal.ucls diff --git a/hexagonal-architecture/etc/hexagonal.urm.puml b/hexagonal-architecture/etc/hexagonal.urm.puml new file mode 100644 index 000000000000..10fcc7f6d71e --- /dev/null +++ b/hexagonal-architecture/etc/hexagonal.urm.puml @@ -0,0 +1,305 @@ +@startuml +package com.iluwatar.hexagonal.sampledata { + class SampleData { + - PLAYERS : List {static} + - RANDOM : Random {static} + + SampleData() + - getRandomPlayerDetails() : PlayerDetails {static} + + submitTickets(lotteryService : LotteryService, numTickets : int) {static} + } +} +package com.iluwatar.hexagonal.service { + class ConsoleLottery { + - LOGGER : Logger {static} + + ConsoleLottery() + + main(args : String[]) {static} + - printMainMenu() {static} + - readString(scanner : Scanner) : String {static} + } + interface LotteryConsoleService { + + addFundsToLotteryAccount(WireTransfers, Scanner) {abstract} + + checkTicket(LotteryService, Scanner) {abstract} + + queryLotteryAccountFunds(WireTransfers, Scanner) {abstract} + + submitTicket(LotteryService, Scanner) {abstract} + } + class LotteryConsoleServiceImpl { + - logger : Logger + + LotteryConsoleServiceImpl(logger : Logger) + + addFundsToLotteryAccount(bank : WireTransfers, scanner : Scanner) + + checkTicket(service : LotteryService, scanner : Scanner) + + queryLotteryAccountFunds(bank : WireTransfers, scanner : Scanner) + - readString(scanner : Scanner) : String + + submitTicket(service : LotteryService, scanner : Scanner) + } +} +package com.iluwatar.hexagonal.mongo { + class MongoConnectionPropertiesLoader { + - DEFAULT_HOST : String {static} + - DEFAULT_PORT : int {static} + + MongoConnectionPropertiesLoader() + + load() {static} + } +} +package com.iluwatar.hexagonal.domain { + class LotteryAdministration { + - notifications : LotteryEventLog + - repository : LotteryTicketRepository + - wireTransfers : WireTransfers + + LotteryAdministration(repository : LotteryTicketRepository, notifications : LotteryEventLog, wireTransfers : WireTransfers) + + getAllSubmittedTickets() : Map + + performLottery() : LotteryNumbers + + resetLottery() + } + class LotteryConstants { + + PLAYER_MAX_BALANCE : int {static} + + PRIZE_AMOUNT : int {static} + + SERVICE_BANK_ACCOUNT : String {static} + + SERVICE_BANK_ACCOUNT_BALANCE : int {static} + + TICKET_PRIZE : int {static} + - LotteryConstants() + } + class LotteryNumbers { + + MAX_NUMBER : int {static} + + MIN_NUMBER : int {static} + + NUM_NUMBERS : int {static} + - numbers : Set + - LotteryNumbers() + - LotteryNumbers(givenNumbers : Set) + + create(givenNumbers : Set) : LotteryNumbers {static} + + createRandom() : LotteryNumbers {static} + + equals(obj : Object) : boolean + - generateRandomNumbers() + + getNumbers() : Set + + getNumbersAsString() : String + + hashCode() : int + + toString() : String + } + -class RandomNumberGenerator { + - randomIterator : OfInt + + RandomNumberGenerator(min : int, max : int) + + nextInt() : int + } + class LotteryService { + - notifications : LotteryEventLog + - repository : LotteryTicketRepository + - wireTransfers : WireTransfers + + LotteryService(repository : LotteryTicketRepository, notifications : LotteryEventLog, wireTransfers : WireTransfers) + + checkTicketForPrize(id : LotteryTicketId, winningNumbers : LotteryNumbers) : LotteryTicketCheckResult + + submitTicket(ticket : LotteryTicket) : Optional + } + class LotteryTicket { + - id : LotteryTicketId + - lotteryNumbers : LotteryNumbers + - playerDetails : PlayerDetails + + LotteryTicket(id : LotteryTicketId, details : PlayerDetails, numbers : LotteryNumbers) + + equals(obj : Object) : boolean + + getId() : LotteryTicketId + + getNumbers() : LotteryNumbers + + getPlayerDetails() : PlayerDetails + + hashCode() : int + + setId(id : LotteryTicketId) + + toString() : String + } + class LotteryTicketCheckResult { + - checkResult : CheckResult + - prizeAmount : int + + LotteryTicketCheckResult(result : CheckResult) + + LotteryTicketCheckResult(result : CheckResult, amount : int) + + equals(obj : Object) : boolean + + getPrizeAmount() : int + + getResult() : CheckResult + + hashCode() : int + } + enum CheckResult { + + NO_PRIZE {static} + + TICKET_NOT_SUBMITTED {static} + + WIN_PRIZE {static} + + valueOf(name : String) : CheckResult {static} + + values() : CheckResult[] {static} + } + class LotteryTicketId { + - id : int + - numAllocated : AtomicInteger {static} + + LotteryTicketId() + + LotteryTicketId(id : int) + + equals(o : Object) : boolean + + getId() : int + + hashCode() : int + + toString() : String + } + class LotteryUtils { + - LotteryUtils() + + checkTicketForPrize(repository : LotteryTicketRepository, id : LotteryTicketId, winningNumbers : LotteryNumbers) : LotteryTicketCheckResult {static} + } + class PlayerDetails { + - bankAccountNumber : String + - emailAddress : String + - phoneNumber : String + + PlayerDetails(email : String, bankAccount : String, phone : String) + + equals(obj : Object) : boolean + + getBankAccount() : String + + getEmail() : String + + getPhoneNumber() : String + + hashCode() : int + + toString() : String + } +} +package com.iluwatar.hexagonal.banking { + class InMemoryBank { + - accounts : Map {static} + + InMemoryBank() + + getFunds(bankAccount : String) : int + + setFunds(bankAccount : String, amount : int) + + transferFunds(amount : int, sourceAccount : String, destinationAccount : String) : boolean + } + class MongoBank { + - DEFAULT_ACCOUNTS_COLLECTION : String {static} + - DEFAULT_DB : String {static} + - accountsCollection : MongoCollection + - database : MongoDatabase + - mongoClient : MongoClient + + MongoBank() + + MongoBank(dbName : String, accountsCollectionName : String) + + connect() + + connect(dbName : String, accountsCollectionName : String) + + getAccountsCollection() : MongoCollection + + getFunds(bankAccount : String) : int + + getMongoClient() : MongoClient + + getMongoDatabase() : MongoDatabase + + setFunds(bankAccount : String, amount : int) + + transferFunds(amount : int, sourceAccount : String, destinationAccount : String) : boolean + } + interface WireTransfers { + + getFunds(String) : int {abstract} + + setFunds(String, int) {abstract} + + transferFunds(int, String, String) : boolean {abstract} + } +} +package com.iluwatar.hexagonal.database { + class InMemoryTicketRepository { + - tickets : Map {static} + + InMemoryTicketRepository() + + deleteAll() + + findAll() : Map + + findById(id : LotteryTicketId) : Optional + + save(ticket : LotteryTicket) : Optional + } + interface LotteryTicketRepository { + + deleteAll() {abstract} + + findAll() : Map {abstract} + + findById(LotteryTicketId) : Optional {abstract} + + save(LotteryTicket) : Optional {abstract} + } + class MongoTicketRepository { + - DEFAULT_COUNTERS_COLLECTION : String {static} + - DEFAULT_DB : String {static} + - DEFAULT_TICKETS_COLLECTION : String {static} + - countersCollection : MongoCollection + - database : MongoDatabase + - mongoClient : MongoClient + - ticketsCollection : MongoCollection + + MongoTicketRepository() + + MongoTicketRepository(dbName : String, ticketsCollectionName : String, countersCollectionName : String) + + connect() + + connect(dbName : String, ticketsCollectionName : String, countersCollectionName : String) + + deleteAll() + - docToTicket(doc : Document) : LotteryTicket + + findAll() : Map + + findById(id : LotteryTicketId) : Optional + + getCountersCollection() : MongoCollection + + getNextId() : int + + getTicketsCollection() : MongoCollection + - initCounters() + + save(ticket : LotteryTicket) : Optional + } +} +package com.iluwatar.hexagonal { + class App { + + App() + + main(args : String[]) {static} + } +} +package com.iluwatar.hexagonal.administration { + class ConsoleAdministration { + - LOGGER : Logger {static} + + ConsoleAdministration() + + main(args : String[]) {static} + - printMainMenu() {static} + - readString(scanner : Scanner) : String {static} + } + interface ConsoleAdministrationSrv { + + getAllSubmittedTickets() {abstract} + + performLottery() {abstract} + + resetLottery() {abstract} + } + class ConsoleAdministrationSrvImpl { + - administration : LotteryAdministration + - logger : Logger + + ConsoleAdministrationSrvImpl(administration : LotteryAdministration, logger : Logger) + + getAllSubmittedTickets() + + performLottery() + + resetLottery() + } +} +package com.iluwatar.hexagonal.eventlog { + interface LotteryEventLog { + + prizeError(PlayerDetails, int) {abstract} + + ticketDidNotWin(PlayerDetails) {abstract} + + ticketSubmitError(PlayerDetails) {abstract} + + ticketSubmitted(PlayerDetails) {abstract} + + ticketWon(PlayerDetails, int) {abstract} + } + class MongoEventLog { + - DEFAULT_DB : String {static} + - DEFAULT_EVENTS_COLLECTION : String {static} + - database : MongoDatabase + - eventsCollection : MongoCollection + - mongoClient : MongoClient + - stdOutEventLog : StdOutEventLog + + MongoEventLog() + + MongoEventLog(dbName : String, eventsCollectionName : String) + + connect() + + connect(dbName : String, eventsCollectionName : String) + + getEventsCollection() : MongoCollection + + getMongoClient() : MongoClient + + getMongoDatabase() : MongoDatabase + + prizeError(details : PlayerDetails, prizeAmount : int) + + ticketDidNotWin(details : PlayerDetails) + + ticketSubmitError(details : PlayerDetails) + + ticketSubmitted(details : PlayerDetails) + + ticketWon(details : PlayerDetails, prizeAmount : int) + } + class StdOutEventLog { + - LOGGER : Logger {static} + + StdOutEventLog() + + prizeError(details : PlayerDetails, prizeAmount : int) + + ticketDidNotWin(details : PlayerDetails) + + ticketSubmitError(details : PlayerDetails) + + ticketSubmitted(details : PlayerDetails) + + ticketWon(details : PlayerDetails, prizeAmount : int) + } +} +LotteryTicket --> "-playerDetails" PlayerDetails +MongoEventLog --> "-stdOutEventLog" StdOutEventLog +LotteryService --> "-wireTransfers" WireTransfers +LotteryAdministration --> "-notifications" LotteryEventLog +LotteryAdministration --> "-wireTransfers" WireTransfers +LotteryTicket --> "-id" LotteryTicketId +LotteryAdministration --> "-repository" LotteryTicketRepository +LotteryService --> "-notifications" LotteryEventLog +LotteryTicket --> "-lotteryNumbers" LotteryNumbers +SampleData --> "-PLAYERS" PlayerDetails +ConsoleAdministrationSrvImpl --> "-administration" LotteryAdministration +RandomNumberGenerator ..+ LotteryNumbers +LotteryService --> "-repository" LotteryTicketRepository +CheckResult ..+ LotteryTicketCheckResult +LotteryTicketCheckResult --> "-checkResult" CheckResult +ConsoleAdministrationSrvImpl ..|> ConsoleAdministrationSrv +InMemoryBank ..|> WireTransfers +MongoBank ..|> WireTransfers +InMemoryTicketRepository ..|> LotteryTicketRepository +MongoTicketRepository ..|> LotteryTicketRepository +MongoEventLog ..|> LotteryEventLog +StdOutEventLog ..|> LotteryEventLog +LotteryConsoleServiceImpl ..|> LotteryConsoleService +@enduml \ No newline at end of file diff --git a/hexagonal-architecture/pom.xml b/hexagonal-architecture/pom.xml new file mode 100644 index 000000000000..1ac50cecfa04 --- /dev/null +++ b/hexagonal-architecture/pom.xml @@ -0,0 +1,88 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + hexagonal-architecture + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + com.google.inject + guice + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + 4.20.0 + test + + + org.mongodb + bson + + + org.mongodb + mongodb-driver-legacy + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.hexagonal.App + + + + + + + + + \ No newline at end of file diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/App.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/App.java new file mode 100644 index 000000000000..b2ea0e635ced --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/App.java @@ -0,0 +1,77 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal; + +import com.google.inject.Guice; +import com.iluwatar.hexagonal.domain.LotteryAdministration; +import com.iluwatar.hexagonal.domain.LotteryService; +import com.iluwatar.hexagonal.module.LotteryTestingModule; +import com.iluwatar.hexagonal.sampledata.SampleData; + +/** + * Hexagonal Architecture pattern decouples the application core from the services it uses. This + * allows the services to be plugged in and the application will run with or without the services. + * + *

    The core logic, or business logic, of an application consists of the algorithms that are + * essential to its purpose. They implement the use cases that are the heart of the application. + * When you change them, you change the essence of the application. + * + *

    The services are not essential. They can be replaced without changing the purpose of the + * application. Examples: database access and other types of storage, user interface components, + * e-mail and other communication components, hardware devices. + * + *

    This example demonstrates Hexagonal Architecture with a lottery system. The application core + * is separate from the services that drive it and from the services it uses. + * + *

    The primary ports for the application are console interfaces {@link + * com.iluwatar.hexagonal.administration.ConsoleAdministration} through which the lottery round is + * initiated and run and {@link com.iluwatar.hexagonal.service.ConsoleLottery} that allows players + * to submit lottery tickets for the draw. + * + *

    The secondary ports that application core uses are{@link + * com.iluwatar.hexagonal.banking.WireTransfers} which is a banking service, {@link + * com.iluwatar.hexagonal.eventlog.LotteryEventLog} that delivers eventlog as lottery events occur + * and {@link com.iluwatar.hexagonal.database.LotteryTicketRepository} that is the storage for the + * lottery tickets. + */ +public class App { + + /** Program entry point. */ + public static void main(String[] args) { + + var injector = Guice.createInjector(new LotteryTestingModule()); + + // start new lottery round + var administration = injector.getInstance(LotteryAdministration.class); + administration.resetLottery(); + + // submit some lottery tickets + var service = injector.getInstance(LotteryService.class); + SampleData.submitTickets(service, 20); + + // perform lottery + administration.performLottery(); + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java new file mode 100644 index 000000000000..80c47e3d1279 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java @@ -0,0 +1,81 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.administration; + +import com.google.inject.Guice; +import com.iluwatar.hexagonal.domain.LotteryAdministration; +import com.iluwatar.hexagonal.domain.LotteryService; +import com.iluwatar.hexagonal.module.LotteryModule; +import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import com.iluwatar.hexagonal.sampledata.SampleData; +import java.util.Scanner; +import lombok.extern.slf4j.Slf4j; + +/** Console interface for lottery administration. */ +@Slf4j +public class ConsoleAdministration { + + /** Program entry point. */ + public static void main(String[] args) { + MongoConnectionPropertiesLoader.load(); + var injector = Guice.createInjector(new LotteryModule()); + var administration = injector.getInstance(LotteryAdministration.class); + var service = injector.getInstance(LotteryService.class); + SampleData.submitTickets(service, 20); + var consoleAdministration = new ConsoleAdministrationSrvImpl(administration, LOGGER); + try (var scanner = new Scanner(System.in)) { + var exit = false; + while (!exit) { + printMainMenu(); + var cmd = readString(scanner); + if ("1".equals(cmd)) { + consoleAdministration.getAllSubmittedTickets(); + } else if ("2".equals(cmd)) { + consoleAdministration.performLottery(); + } else if ("3".equals(cmd)) { + consoleAdministration.resetLottery(); + } else if ("4".equals(cmd)) { + exit = true; + } else { + LOGGER.info("Unknown command: {}", cmd); + } + } + } + } + + private static void printMainMenu() { + LOGGER.info(""); + LOGGER.info("### Lottery Administration Console ###"); + LOGGER.info("(1) Show all submitted tickets"); + LOGGER.info("(2) Perform lottery draw"); + LOGGER.info("(3) Reset lottery ticket database"); + LOGGER.info("(4) Exit"); + } + + private static String readString(Scanner scanner) { + LOGGER.info("> "); + return scanner.next(); + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java new file mode 100644 index 000000000000..f361ede46f12 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.administration; + +/** Console interface for lottery administration. */ +public interface ConsoleAdministrationSrv { + + /** Get all submitted tickets. */ + void getAllSubmittedTickets(); + + /** Draw lottery numbers. */ + void performLottery(); + + /** Begin new lottery round. */ + void resetLottery(); +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java new file mode 100644 index 000000000000..02612ff83685 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java @@ -0,0 +1,60 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.administration; + +import com.iluwatar.hexagonal.domain.LotteryAdministration; +import org.slf4j.Logger; + +/** Console implementation for lottery administration. */ +public class ConsoleAdministrationSrvImpl implements ConsoleAdministrationSrv { + private final LotteryAdministration administration; + private final Logger logger; + + /** Constructor. */ + public ConsoleAdministrationSrvImpl(LotteryAdministration administration, Logger logger) { + this.administration = administration; + this.logger = logger; + } + + @Override + public void getAllSubmittedTickets() { + administration + .getAllSubmittedTickets() + .forEach((k, v) -> logger.info("Key: {}, Value: {}", k, v)); + } + + @Override + public void performLottery() { + var numbers = administration.performLottery(); + logger.info("The winning numbers: {}", numbers.getNumbersAsString()); + logger.info("Time to reset the database for next round, eh?"); + } + + @Override + public void resetLottery() { + administration.resetLottery(); + logger.info("The lottery ticket database was cleared."); + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java new file mode 100644 index 000000000000..421d5c32dfc4 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.banking; + +import com.iluwatar.hexagonal.domain.LotteryConstants; +import java.util.HashMap; +import java.util.Map; + +/** Banking implementation. */ +public class InMemoryBank implements WireTransfers { + + private static final Map accounts = new HashMap<>(); + + static { + accounts.put( + LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_BALANCE); + } + + @Override + public void setFunds(String bankAccount, int amount) { + accounts.put(bankAccount, amount); + } + + @Override + public int getFunds(String bankAccount) { + return accounts.getOrDefault(bankAccount, 0); + } + + @Override + public boolean transferFunds(int amount, String sourceAccount, String destinationAccount) { + if (accounts.getOrDefault(sourceAccount, 0) >= amount) { + accounts.put(sourceAccount, accounts.get(sourceAccount) - amount); + accounts.put(destinationAccount, accounts.get(destinationAccount) + amount); + return true; + } else { + return false; + } + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java new file mode 100644 index 000000000000..c7af4693137e --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java @@ -0,0 +1,104 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.banking; + +import com.mongodb.MongoClient; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.UpdateOptions; +import java.util.ArrayList; +import lombok.Getter; +import org.bson.Document; + +/** Mongo based banking adapter. */ +public class MongoBank implements WireTransfers { + + private static final String DEFAULT_DB = "lotteryDB"; + private static final String DEFAULT_ACCOUNTS_COLLECTION = "accounts"; + + @Getter private MongoClient mongoClient; + @Getter private MongoDatabase database; + @Getter private MongoCollection accountsCollection; + + /** Constructor. */ + public MongoBank() { + connect(); + } + + /** Constructor accepting parameters. */ + public MongoBank(String dbName, String accountsCollectionName) { + connect(dbName, accountsCollectionName); + } + + /** Connect to database with default parameters. */ + public void connect() { + connect(DEFAULT_DB, DEFAULT_ACCOUNTS_COLLECTION); + } + + /** Connect to database with given parameters. */ + public void connect(String dbName, String accountsCollectionName) { + if (mongoClient != null) { + mongoClient.close(); + } + mongoClient = + new MongoClient( + System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); + database = mongoClient.getDatabase(dbName); + accountsCollection = database.getCollection(accountsCollectionName); + } + + @Override + public void setFunds(String bankAccount, int amount) { + var search = new Document("_id", bankAccount); + var update = new Document("_id", bankAccount).append("funds", amount); + var updateOptions = new UpdateOptions().upsert(true); + accountsCollection.updateOne(search, new Document("$set", update), updateOptions); + } + + @Override + public int getFunds(String bankAccount) { + return accountsCollection + .find(new Document("_id", bankAccount)) + .limit(1) + .into(new ArrayList<>()) + .stream() + .findFirst() + .map(x -> x.getInteger("funds")) + .orElse(0); + } + + @Override + public boolean transferFunds(int amount, String sourceAccount, String destinationAccount) { + var sourceFunds = getFunds(sourceAccount); + if (sourceFunds < amount) { + return false; + } else { + var destFunds = getFunds(destinationAccount); + setFunds(sourceAccount, sourceFunds - amount); + setFunds(destinationAccount, destFunds + amount); + return true; + } + } +} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java similarity index 78% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java index 670824cb898e..f8981420933f 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,26 +24,15 @@ */ package com.iluwatar.hexagonal.banking; -/** - * - * Interface to bank accounts. - * - */ +/** Interface to bank accounts. */ public interface WireTransfers { - /** - * Set amount of funds for bank account - */ + /** Set amount of funds for bank account. */ void setFunds(String bankAccount, int amount); - /** - * Get amount of funds for bank account - */ + /** Get amount of funds for bank account. */ int getFunds(String bankAccount); - /** - * Transfer funds from one bank account to another - */ + /** Transfer funds from one bank account to another. */ boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount); - } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java similarity index 81% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java index f2f4c7db2053..5805e80aade6 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,35 +24,25 @@ */ package com.iluwatar.hexagonal.database; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; import java.util.HashMap; import java.util.Map; import java.util.Optional; -import com.iluwatar.hexagonal.domain.LotteryTicket; -import com.iluwatar.hexagonal.domain.LotteryTicketId; - -/** - * - * Mock database for lottery tickets. - * - */ +/** Mock database for lottery tickets. */ public class InMemoryTicketRepository implements LotteryTicketRepository { - - private static Map tickets = new HashMap<>(); + + private static final Map tickets = new HashMap<>(); @Override public Optional findById(LotteryTicketId id) { - LotteryTicket ticket = tickets.get(id); - if (ticket == null) { - return Optional.empty(); - } else { - return Optional.of(ticket); - } + return Optional.ofNullable(tickets.get(id)); } @Override public Optional save(LotteryTicket ticket) { - LotteryTicketId id = new LotteryTicketId(); + var id = new LotteryTicketId(); tickets.put(id, ticket); return Optional.of(id); } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java similarity index 79% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java index 5daf3af9c20c..29ca16af70c3 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,37 +24,23 @@ */ package com.iluwatar.hexagonal.database; -import java.util.Map; -import java.util.Optional; - import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; +import java.util.Map; +import java.util.Optional; -/** - * - * Interface for accessing lottery tickets in database. - * - */ +/** Interface for accessing lottery tickets in database. */ public interface LotteryTicketRepository { - /** - * Find lottery ticket by id - */ + /** Find lottery ticket by id. */ Optional findById(LotteryTicketId id); - /** - * Save lottery ticket - */ + /** Save lottery ticket. */ Optional save(LotteryTicket ticket); - /** - * Get all lottery tickets - */ + /** Get all lottery tickets. */ Map findAll(); - /** - * Delete all lottery tickets - */ + /** Delete all lottery tickets. */ void deleteAll(); - } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java new file mode 100644 index 000000000000..ecb26c9c470b --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java @@ -0,0 +1,152 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.database; + +import com.iluwatar.hexagonal.domain.LotteryNumbers; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; +import com.iluwatar.hexagonal.domain.PlayerDetails; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; +import lombok.Getter; +import org.bson.Document; + +/** Mongo lottery ticket database. */ +public class MongoTicketRepository implements LotteryTicketRepository { + + private static final String DEFAULT_DB = "lotteryDB"; + private static final String DEFAULT_TICKETS_COLLECTION = "lotteryTickets"; + private static final String DEFAULT_COUNTERS_COLLECTION = "counters"; + private static final String TICKET_ID = "ticketId"; + + private MongoClient mongoClient; + private MongoDatabase database; + @Getter private MongoCollection ticketsCollection; + @Getter private MongoCollection countersCollection; + + /** Constructor. */ + public MongoTicketRepository() { + connect(); + } + + /** Constructor accepting parameters. */ + public MongoTicketRepository( + String dbName, String ticketsCollectionName, String countersCollectionName) { + connect(dbName, ticketsCollectionName, countersCollectionName); + } + + /** Connect to database with default parameters. */ + public void connect() { + connect(DEFAULT_DB, DEFAULT_TICKETS_COLLECTION, DEFAULT_COUNTERS_COLLECTION); + } + + /** Connect to database with given parameters. */ + public void connect(String dbName, String ticketsCollectionName, String countersCollectionName) { + if (mongoClient != null) { + mongoClient.close(); + } + mongoClient = + new MongoClient( + System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); + database = mongoClient.getDatabase(dbName); + ticketsCollection = database.getCollection(ticketsCollectionName); + countersCollection = database.getCollection(countersCollectionName); + if (countersCollection.countDocuments() <= 0) { + initCounters(); + } + } + + private void initCounters() { + var doc = new Document("_id", TICKET_ID).append("seq", 1); + countersCollection.insertOne(doc); + } + + /** + * Get next ticket id. + * + * @return next ticket id + */ + public int getNextId() { + var find = new Document("_id", TICKET_ID); + var increase = new Document("seq", 1); + var update = new Document("$inc", increase); + var result = countersCollection.findOneAndUpdate(find, update); + return result.getInteger("seq"); + } + + @Override + public Optional findById(LotteryTicketId id) { + return ticketsCollection + .find(new Document(TICKET_ID, id.getId())) + .limit(1) + .into(new ArrayList<>()) + .stream() + .findFirst() + .map(this::docToTicket); + } + + @Override + public Optional save(LotteryTicket ticket) { + var ticketId = getNextId(); + var doc = new Document(TICKET_ID, ticketId); + doc.put("email", ticket.playerDetails().email()); + doc.put("bank", ticket.playerDetails().bankAccount()); + doc.put("phone", ticket.playerDetails().phoneNumber()); + doc.put("numbers", ticket.lotteryNumbers().getNumbersAsString()); + ticketsCollection.insertOne(doc); + return Optional.of(new LotteryTicketId(ticketId)); + } + + @Override + public Map findAll() { + return ticketsCollection.find(new Document()).into(new ArrayList<>()).stream() + .map(this::docToTicket) + .collect(Collectors.toMap(LotteryTicket::id, Function.identity())); + } + + @Override + public void deleteAll() { + ticketsCollection.deleteMany(new Document()); + } + + private LotteryTicket docToTicket(Document doc) { + var playerDetails = + new PlayerDetails(doc.getString("email"), doc.getString("bank"), doc.getString("phone")); + var numbers = + Arrays.stream(doc.getString("numbers").split(",")) + .map(Integer::parseInt) + .collect(Collectors.toSet()); + var lotteryNumbers = LotteryNumbers.create(numbers); + var ticketId = new LotteryTicketId(doc.getInteger(TICKET_ID)); + return new LotteryTicket(ticketId, playerDetails, lotteryNumbers); + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java new file mode 100644 index 000000000000..28cf0fbbd22a --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java @@ -0,0 +1,85 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import static com.iluwatar.hexagonal.domain.LotteryConstants.PRIZE_AMOUNT; +import static com.iluwatar.hexagonal.domain.LotteryConstants.SERVICE_BANK_ACCOUNT; + +import com.google.inject.Inject; +import com.iluwatar.hexagonal.banking.WireTransfers; +import com.iluwatar.hexagonal.database.LotteryTicketRepository; +import com.iluwatar.hexagonal.eventlog.LotteryEventLog; +import java.util.Map; + +/** Lottery administration implementation. */ +public class LotteryAdministration { + + private final LotteryTicketRepository repository; + private final LotteryEventLog notifications; + private final WireTransfers wireTransfers; + + /** Constructor. */ + @Inject + public LotteryAdministration( + LotteryTicketRepository repository, + LotteryEventLog notifications, + WireTransfers wireTransfers) { + this.repository = repository; + this.notifications = notifications; + this.wireTransfers = wireTransfers; + } + + /** Get all the lottery tickets submitted for lottery. */ + public Map getAllSubmittedTickets() { + return repository.findAll(); + } + + /** Draw lottery numbers. */ + public LotteryNumbers performLottery() { + var numbers = LotteryNumbers.createRandom(); + var tickets = getAllSubmittedTickets(); + for (var id : tickets.keySet()) { + var lotteryTicket = tickets.get(id); + var playerDetails = lotteryTicket.playerDetails(); + var playerAccount = playerDetails.bankAccount(); + var result = LotteryUtils.checkTicketForPrize(repository, id, numbers).getResult(); + if (result == LotteryTicketCheckResult.CheckResult.WIN_PRIZE) { + if (wireTransfers.transferFunds(PRIZE_AMOUNT, SERVICE_BANK_ACCOUNT, playerAccount)) { + notifications.ticketWon(playerDetails, PRIZE_AMOUNT); + } else { + notifications.prizeError(playerDetails, PRIZE_AMOUNT); + } + } else if (result == LotteryTicketCheckResult.CheckResult.NO_PRIZE) { + notifications.ticketDidNotWin(playerDetails); + } + } + return numbers; + } + + /** Begin new lottery round. */ + public void resetLottery() { + repository.deleteAll(); + } +} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java similarity index 78% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java index 9ecbb74b9f82..21dcbc2d48be 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,14 @@ */ package com.iluwatar.hexagonal.domain; -/** - * - * Lottery domain constants - * - */ +/** Lottery domain constants. */ public class LotteryConstants { - private LotteryConstants() { - } + private LotteryConstants() {} public static final int PRIZE_AMOUNT = 100000; public static final String SERVICE_BANK_ACCOUNT = "123-123"; public static final int TICKET_PRIZE = 3; - public static final int SERVICE_BANK_ACCOUNT_SALDO = 150000; - public static final int PLAYER_MAX_SALDO = 100; - + public static final int SERVICE_BANK_ACCOUNT_BALANCE = 150000; + public static final int PLAYER_MAX_BALANCE = 100; } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java new file mode 100644 index 000000000000..3319251f479d --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java @@ -0,0 +1,133 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import com.google.common.base.Joiner; +import java.security.SecureRandom; +import java.util.Collections; +import java.util.HashSet; +import java.util.PrimitiveIterator; +import java.util.Set; +import lombok.EqualsAndHashCode; +import lombok.ToString; + +/** + * Value object representing lottery numbers. This lottery uses sets of 4 numbers. The numbers must + * be unique and between 1 and 20. + */ +@EqualsAndHashCode +@ToString +public class LotteryNumbers { + + private final Set numbers; + + public static final int MIN_NUMBER = 1; + public static final int MAX_NUMBER = 20; + public static final int NUM_NUMBERS = 4; + + /** Constructor. Creates random lottery numbers. */ + private LotteryNumbers() { + numbers = new HashSet<>(); + generateRandomNumbers(); + } + + /** Constructor. Uses given numbers. */ + private LotteryNumbers(Set givenNumbers) { + numbers = new HashSet<>(); + numbers.addAll(givenNumbers); + } + + /** + * Creates a random lottery number. + * + * @return random LotteryNumbers + */ + public static LotteryNumbers createRandom() { + return new LotteryNumbers(); + } + + /** + * Creates lottery number from given set of numbers. + * + * @return given LotteryNumbers + */ + public static LotteryNumbers create(Set givenNumbers) { + return new LotteryNumbers(givenNumbers); + } + + /** + * Get numbers. + * + * @return lottery numbers + */ + public Set getNumbers() { + return Collections.unmodifiableSet(numbers); + } + + /** + * Get numbers as string. + * + * @return numbers as comma separated string + */ + public String getNumbersAsString() { + return Joiner.on(',').join(numbers); + } + + /** Generates 4 unique random numbers between 1-20 into numbers set. */ + private void generateRandomNumbers() { + numbers.clear(); + var generator = new RandomNumberGenerator(MIN_NUMBER, MAX_NUMBER); + while (numbers.size() < NUM_NUMBERS) { + var num = generator.nextInt(); + numbers.add(num); + } + } + + /** Helper class for generating random numbers. */ + private static class RandomNumberGenerator { + + private final PrimitiveIterator.OfInt randomIterator; + + /** + * Initialize a new random number generator that generates random numbers in the range [min, + * max]. + * + * @param min the min value (inclusive) + * @param max the max value (inclusive) + */ + public RandomNumberGenerator(int min, int max) { + randomIterator = new SecureRandom().ints(min, max + 1).iterator(); + } + + /** + * Gets next random integer in [min, max] range. + * + * @return a random number in the range (min, max) + */ + public int nextInt() { + return randomIterator.nextInt(); + } + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java new file mode 100644 index 000000000000..38d33ab957e4 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import static com.iluwatar.hexagonal.domain.LotteryConstants.SERVICE_BANK_ACCOUNT; +import static com.iluwatar.hexagonal.domain.LotteryConstants.TICKET_PRIZE; + +import com.google.inject.Inject; +import com.iluwatar.hexagonal.banking.WireTransfers; +import com.iluwatar.hexagonal.database.LotteryTicketRepository; +import com.iluwatar.hexagonal.eventlog.LotteryEventLog; +import java.util.Optional; + +/** Implementation for lottery service. */ +public class LotteryService { + + private final LotteryTicketRepository repository; + private final LotteryEventLog notifications; + private final WireTransfers wireTransfers; + + /** Constructor. */ + @Inject + public LotteryService( + LotteryTicketRepository repository, + LotteryEventLog notifications, + WireTransfers wireTransfers) { + this.repository = repository; + this.notifications = notifications; + this.wireTransfers = wireTransfers; + } + + /** Submit lottery ticket to participate in the lottery. */ + public Optional submitTicket(LotteryTicket ticket) { + var playerDetails = ticket.playerDetails(); + var playerAccount = playerDetails.bankAccount(); + var result = wireTransfers.transferFunds(TICKET_PRIZE, playerAccount, SERVICE_BANK_ACCOUNT); + if (!result) { + notifications.ticketSubmitError(playerDetails); + return Optional.empty(); + } + var optional = repository.save(ticket); + if (optional.isPresent()) { + notifications.ticketSubmitted(playerDetails); + } + return optional; + } + + /** Check if lottery ticket has won. */ + public LotteryTicketCheckResult checkTicketForPrize( + LotteryTicketId id, LotteryNumbers winningNumbers) { + return LotteryUtils.checkTicketForPrize(repository, id, winningNumbers); + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java new file mode 100644 index 000000000000..0b895f8169a2 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java @@ -0,0 +1,65 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +/** Immutable value object representing lottery ticket. */ +public record LotteryTicket( + LotteryTicketId id, PlayerDetails playerDetails, LotteryNumbers lotteryNumbers) { + + @Override + public int hashCode() { + final var prime = 31; + var result = 1; + result = prime * result + ((lotteryNumbers == null) ? 0 : lotteryNumbers.hashCode()); + result = prime * result + ((playerDetails == null) ? 0 : playerDetails.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + var other = (LotteryTicket) obj; + if (lotteryNumbers == null) { + if (other.lotteryNumbers != null) { + return false; + } + } else if (!lotteryNumbers.equals(other.lotteryNumbers)) { + return false; + } + if (playerDetails == null) { + return other.playerDetails == null; + } else { + return playerDetails.equals(other.playerDetails); + } + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java new file mode 100644 index 000000000000..ff0245f30b1e --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +/** Represents lottery ticket check result. */ +@Getter +@EqualsAndHashCode +@RequiredArgsConstructor +public class LotteryTicketCheckResult { + + /** Enumeration of Type of Outcomes of a Lottery. */ + public enum CheckResult { + WIN_PRIZE, + NO_PRIZE, + TICKET_NOT_SUBMITTED + } + + private final CheckResult result; + private final int prizeAmount; + + /** Constructor. */ + public LotteryTicketCheckResult(CheckResult result) { + this.result = result; + prizeAmount = 0; + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java new file mode 100644 index 000000000000..4bd1074fb3d9 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java @@ -0,0 +1,49 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import java.util.concurrent.atomic.AtomicInteger; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +/** Lottery ticked id. */ +@Getter +@EqualsAndHashCode +@RequiredArgsConstructor +public class LotteryTicketId { + + private static final AtomicInteger numAllocated = new AtomicInteger(0); + private final int id; + + public LotteryTicketId() { + this.id = numAllocated.incrementAndGet(); + } + + @Override + public String toString() { + return String.format("%d", id); + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java new file mode 100644 index 000000000000..5e4ed138c7df --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java @@ -0,0 +1,49 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import com.iluwatar.hexagonal.database.LotteryTicketRepository; +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; + +/** Lottery utilities. */ +public class LotteryUtils { + + private LotteryUtils() {} + + /** Checks if lottery ticket has won. */ + public static LotteryTicketCheckResult checkTicketForPrize( + LotteryTicketRepository repository, LotteryTicketId id, LotteryNumbers winningNumbers) { + var optional = repository.findById(id); + if (optional.isPresent()) { + if (optional.get().lotteryNumbers().equals(winningNumbers)) { + return new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 1000); + } else { + return new LotteryTicketCheckResult(CheckResult.NO_PRIZE); + } + } else { + return new LotteryTicketCheckResult(CheckResult.TICKET_NOT_SUBMITTED); + } + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java new file mode 100644 index 000000000000..5fa3a3145253 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java @@ -0,0 +1,28 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +/** Immutable value object containing lottery player details. */ +public record PlayerDetails(String email, String bankAccount, String phoneNumber) {} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java similarity index 78% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java index fd6bfebdf9f1..6cea51b6bbe7 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,36 +26,21 @@ import com.iluwatar.hexagonal.domain.PlayerDetails; -/** - * - * Event log for lottery events - * - */ +/** Event log for lottery events. */ public interface LotteryEventLog { - /** - * lottery ticket submitted - */ + /** lottery ticket submitted. */ void ticketSubmitted(PlayerDetails details); - /** - * error submitting lottery ticket - */ + /** error submitting lottery ticket. */ void ticketSubmitError(PlayerDetails details); - /** - * lottery ticket did not win - */ + /** lottery ticket did not win. */ void ticketDidNotWin(PlayerDetails details); - /** - * lottery ticket won - */ + /** lottery ticket won. */ void ticketWon(PlayerDetails details, int prizeAmount); - /** - * error paying the prize - */ + /** error paying the prize. */ void prizeError(PlayerDetails details, int prizeAmount); - } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java new file mode 100644 index 000000000000..47120d3d7840 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java @@ -0,0 +1,133 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.eventlog; + +import com.iluwatar.hexagonal.domain.PlayerDetails; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import lombok.Getter; +import org.bson.Document; + +/** Mongo based event log. */ +public class MongoEventLog implements LotteryEventLog { + + private static final String DEFAULT_DB = "lotteryDB"; + private static final String DEFAULT_EVENTS_COLLECTION = "events"; + private static final String EMAIL = "email"; + private static final String PHONE = "phone"; + public static final String MESSAGE = "message"; + + @Getter private MongoClient mongoClient; + @Getter private MongoDatabase database; + @Getter private MongoCollection eventsCollection; + + private final StdOutEventLog stdOutEventLog = new StdOutEventLog(); + + /** Constructor. */ + public MongoEventLog() { + connect(); + } + + /** Constructor accepting parameters. */ + public MongoEventLog(String dbName, String eventsCollectionName) { + connect(dbName, eventsCollectionName); + } + + /** Connect to database with default parameters. */ + public void connect() { + connect(DEFAULT_DB, DEFAULT_EVENTS_COLLECTION); + } + + /** Connect to database with given parameters. */ + public void connect(String dbName, String eventsCollectionName) { + if (mongoClient != null) { + mongoClient.close(); + } + mongoClient = + new MongoClient( + System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); + database = mongoClient.getDatabase(dbName); + eventsCollection = database.getCollection(eventsCollectionName); + } + + @Override + public void ticketSubmitted(PlayerDetails details) { + var document = new Document(EMAIL, details.email()); + document.put(PHONE, details.phoneNumber()); + document.put("bank", details.bankAccount()); + document.put( + MESSAGE, "Lottery ticket was submitted and bank account was charged for 3 credits."); + eventsCollection.insertOne(document); + stdOutEventLog.ticketSubmitted(details); + } + + @Override + public void ticketSubmitError(PlayerDetails details) { + var document = new Document(EMAIL, details.email()); + document.put(PHONE, details.phoneNumber()); + document.put("bank", details.bankAccount()); + document.put(MESSAGE, "Lottery ticket could not be submitted because lack of funds."); + eventsCollection.insertOne(document); + stdOutEventLog.ticketSubmitError(details); + } + + @Override + public void ticketDidNotWin(PlayerDetails details) { + var document = new Document(EMAIL, details.email()); + document.put(PHONE, details.phoneNumber()); + document.put("bank", details.bankAccount()); + document.put(MESSAGE, "Lottery ticket was checked and unfortunately did not win this time."); + eventsCollection.insertOne(document); + stdOutEventLog.ticketDidNotWin(details); + } + + @Override + public void ticketWon(PlayerDetails details, int prizeAmount) { + var document = new Document(EMAIL, details.email()); + document.put(PHONE, details.phoneNumber()); + document.put("bank", details.bankAccount()); + document.put( + MESSAGE, + String.format( + "Lottery ticket won! The bank account was deposited with %d credits.", prizeAmount)); + eventsCollection.insertOne(document); + stdOutEventLog.ticketWon(details, prizeAmount); + } + + @Override + public void prizeError(PlayerDetails details, int prizeAmount) { + var document = new Document(EMAIL, details.email()); + document.put(PHONE, details.phoneNumber()); + document.put("bank", details.bankAccount()); + document.put( + MESSAGE, + String.format( + "Lottery ticket won! Unfortunately the bank credit transfer of %d failed.", + prizeAmount)); + eventsCollection.insertOne(document); + stdOutEventLog.prizeError(details, prizeAmount); + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java new file mode 100644 index 000000000000..1ddd93d5932b --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java @@ -0,0 +1,73 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.eventlog; + +import com.iluwatar.hexagonal.domain.PlayerDetails; +import lombok.extern.slf4j.Slf4j; + +/** Standard output event log. */ +@Slf4j +public class StdOutEventLog implements LotteryEventLog { + + @Override + public void ticketSubmitted(PlayerDetails details) { + LOGGER.info( + "Lottery ticket for {} was submitted. Bank account {} was charged for 3 credits.", + details.email(), + details.bankAccount()); + } + + @Override + public void ticketDidNotWin(PlayerDetails details) { + LOGGER.info( + "Lottery ticket for {} was checked and unfortunately did not win this time.", + details.email()); + } + + @Override + public void ticketWon(PlayerDetails details, int prizeAmount) { + LOGGER.info( + "Lottery ticket for {} has won! The bank account {} was deposited with {} credits.", + details.email(), + details.bankAccount(), + prizeAmount); + } + + @Override + public void prizeError(PlayerDetails details, int prizeAmount) { + LOGGER.error( + "Lottery ticket for {} has won! Unfortunately the bank credit transfer of" + " {} failed.", + details.email(), + prizeAmount); + } + + @Override + public void ticketSubmitError(PlayerDetails details) { + LOGGER.error( + "Lottery ticket for {} could not be submitted because the credit transfer" + + " of 3 credits failed.", + details.email()); + } +} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java similarity index 87% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java index 72fb78dad9d7..c45117bc6e6c 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -30,9 +32,7 @@ import com.iluwatar.hexagonal.eventlog.LotteryEventLog; import com.iluwatar.hexagonal.eventlog.MongoEventLog; -/** - * Guice module for binding production dependencies - */ +/** Guice module for binding production dependencies. */ public class LotteryModule extends AbstractModule { @Override protected void configure() { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java similarity index 88% rename from hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java rename to hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java index 624acf5780a2..1ed43183be3d 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -30,9 +32,7 @@ import com.iluwatar.hexagonal.eventlog.LotteryEventLog; import com.iluwatar.hexagonal.eventlog.StdOutEventLog; -/** - * Guice module for testing dependencies - */ +/** Guice module for testing dependencies. */ public class LotteryTestingModule extends AbstractModule { @Override protected void configure() { diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java new file mode 100644 index 000000000000..5a90579898e9 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.mongo; + +import java.io.FileInputStream; +import java.util.Properties; +import lombok.extern.slf4j.Slf4j; + +/** Mongo connection properties loader. */ +@Slf4j +public class MongoConnectionPropertiesLoader { + + private static final String DEFAULT_HOST = "localhost"; + private static final int DEFAULT_PORT = 27017; + + /** Try to load connection properties from file. Fall back to default connection properties. */ + public static void load() { + var host = DEFAULT_HOST; + var port = DEFAULT_PORT; + var path = System.getProperty("hexagonal.properties.path"); + var properties = new Properties(); + if (path != null) { + try (var fin = new FileInputStream(path)) { + properties.load(fin); + host = properties.getProperty("mongo-host"); + port = Integer.parseInt(properties.getProperty("mongo-port")); + } catch (Exception e) { + // error occurred, use default properties + LOGGER.error("Error occurred: ", e); + } + } + System.setProperty("mongo-host", host); + System.setProperty("mongo-port", String.format("%d", port)); + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java new file mode 100644 index 000000000000..7d0bb4136f68 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java @@ -0,0 +1,109 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.sampledata; + +import com.iluwatar.hexagonal.banking.InMemoryBank; +import com.iluwatar.hexagonal.domain.LotteryConstants; +import com.iluwatar.hexagonal.domain.LotteryNumbers; +import com.iluwatar.hexagonal.domain.LotteryService; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; +import com.iluwatar.hexagonal.domain.PlayerDetails; +import java.security.SecureRandom; +import java.util.AbstractMap.SimpleEntry; +import java.util.List; +import java.util.stream.Collectors; + +/** Utilities for creating sample lottery tickets. */ +public class SampleData { + + private static final List PLAYERS; + private static final SecureRandom RANDOM = new SecureRandom(); + + static { + PLAYERS = + List.of( + new PlayerDetails("john@google.com", "312-342", "+3242434242"), + new PlayerDetails("mary@google.com", "234-987", "+23452346"), + new PlayerDetails("steve@google.com", "833-836", "+63457543"), + new PlayerDetails("wayne@google.com", "319-826", "+24626"), + new PlayerDetails("johnie@google.com", "983-322", "+3635635"), + new PlayerDetails("andy@google.com", "934-734", "+0898245"), + new PlayerDetails("richard@google.com", "536-738", "+09845325"), + new PlayerDetails("kevin@google.com", "453-936", "+2423532"), + new PlayerDetails("arnold@google.com", "114-988", "+5646346524"), + new PlayerDetails("ian@google.com", "663-765", "+928394235"), + new PlayerDetails("robin@google.com", "334-763", "+35448"), + new PlayerDetails("ted@google.com", "735-964", "+98752345"), + new PlayerDetails("larry@google.com", "734-853", "+043842423"), + new PlayerDetails("calvin@google.com", "334-746", "+73294135"), + new PlayerDetails("jacob@google.com", "444-766", "+358042354"), + new PlayerDetails("edwin@google.com", "895-345", "+9752435"), + new PlayerDetails("mary@google.com", "760-009", "+34203542"), + new PlayerDetails("lolita@google.com", "425-907", "+9872342"), + new PlayerDetails("bruno@google.com", "023-638", "+673824122"), + new PlayerDetails("peter@google.com", "335-886", "+5432503945"), + new PlayerDetails("warren@google.com", "225-946", "+9872341324"), + new PlayerDetails("monica@google.com", "265-748", "+134124"), + new PlayerDetails("ollie@google.com", "190-045", "+34453452"), + new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"), + new PlayerDetails("lars@google.com", "746-936", "+42345298345"), + new PlayerDetails("bobbie@google.com", "946-384", "+79831742"), + new PlayerDetails("tyron@google.com", "310-992", "+0498837412"), + new PlayerDetails("tyrell@google.com", "032-045", "+67834134"), + new PlayerDetails("nadja@google.com", "000-346", "+498723"), + new PlayerDetails("wendy@google.com", "994-989", "+987324454"), + new PlayerDetails("luke@google.com", "546-634", "+987642435"), + new PlayerDetails("bjorn@google.com", "342-874", "+7834325"), + new PlayerDetails("lisa@google.com", "024-653", "+980742154"), + new PlayerDetails("anton@google.com", "834-935", "+876423145"), + new PlayerDetails("bruce@google.com", "284-936", "+09843212345"), + new PlayerDetails("ray@google.com", "843-073", "+678324123"), + new PlayerDetails("ron@google.com", "637-738", "+09842354"), + new PlayerDetails("xavier@google.com", "143-947", "+375245"), + new PlayerDetails("harriet@google.com", "842-404", "+131243252")); + var wireTransfers = new InMemoryBank(); + PLAYERS.stream() + .map(PlayerDetails::bankAccount) + .map(e -> new SimpleEntry<>(e, RANDOM.nextInt(LotteryConstants.PLAYER_MAX_BALANCE))) + .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)) + .forEach(wireTransfers::setFunds); + } + + /** Inserts lottery tickets into the database based on the sample data. */ + public static void submitTickets(LotteryService lotteryService, int numTickets) { + for (var i = 0; i < numTickets; i++) { + var randomPlayerDetails = getRandomPlayerDetails(); + var lotteryNumbers = LotteryNumbers.createRandom(); + var lotteryTicketId = new LotteryTicketId(); + var ticket = new LotteryTicket(lotteryTicketId, randomPlayerDetails, lotteryNumbers); + lotteryService.submitTicket(ticket); + } + } + + private static PlayerDetails getRandomPlayerDetails() { + return PLAYERS.get(RANDOM.nextInt(PLAYERS.size())); + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java new file mode 100644 index 000000000000..8832b71a5241 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java @@ -0,0 +1,82 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.service; + +import com.google.inject.Guice; +import com.iluwatar.hexagonal.banking.WireTransfers; +import com.iluwatar.hexagonal.domain.LotteryService; +import com.iluwatar.hexagonal.module.LotteryModule; +import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import java.util.Scanner; +import lombok.extern.slf4j.Slf4j; + +/** Console interface for lottery players. */ +@Slf4j +public class ConsoleLottery { + + /** Program entry point. */ + public static void main(String[] args) { + MongoConnectionPropertiesLoader.load(); + var injector = Guice.createInjector(new LotteryModule()); + var service = injector.getInstance(LotteryService.class); + var bank = injector.getInstance(WireTransfers.class); + try (Scanner scanner = new Scanner(System.in)) { + var exit = false; + while (!exit) { + printMainMenu(); + var cmd = readString(scanner); + var lotteryConsoleService = new LotteryConsoleServiceImpl(LOGGER); + if ("1".equals(cmd)) { + lotteryConsoleService.queryLotteryAccountFunds(bank, scanner); + } else if ("2".equals(cmd)) { + lotteryConsoleService.addFundsToLotteryAccount(bank, scanner); + } else if ("3".equals(cmd)) { + lotteryConsoleService.submitTicket(service, scanner); + } else if ("4".equals(cmd)) { + lotteryConsoleService.checkTicket(service, scanner); + } else if ("5".equals(cmd)) { + exit = true; + } else { + LOGGER.info("Unknown command"); + } + } + } + } + + private static void printMainMenu() { + LOGGER.info(""); + LOGGER.info("### Lottery Service Console ###"); + LOGGER.info("(1) Query lottery account funds"); + LOGGER.info("(2) Add funds to lottery account"); + LOGGER.info("(3) Submit ticket"); + LOGGER.info("(4) Check ticket"); + LOGGER.info("(5) Exit"); + } + + private static String readString(Scanner scanner) { + LOGGER.info("> "); + return scanner.next(); + } +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java new file mode 100644 index 000000000000..39fbb08c31f4 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.service; + +import com.iluwatar.hexagonal.banking.WireTransfers; +import com.iluwatar.hexagonal.domain.LotteryService; +import java.util.Scanner; + +/** Console interface for lottery service. */ +public interface LotteryConsoleService { + + void checkTicket(LotteryService service, Scanner scanner); + + /** Submit lottery ticket to participate in the lottery. */ + void submitTicket(LotteryService service, Scanner scanner); + + /** Add funds to lottery account. */ + void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner); + + /** Recovery funds from lottery account. */ + void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner); +} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java new file mode 100644 index 000000000000..dbdd16f79a4e --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java @@ -0,0 +1,125 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.service; + +import com.iluwatar.hexagonal.banking.WireTransfers; +import com.iluwatar.hexagonal.domain.LotteryNumbers; +import com.iluwatar.hexagonal.domain.LotteryService; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult; +import com.iluwatar.hexagonal.domain.LotteryTicketId; +import com.iluwatar.hexagonal.domain.PlayerDetails; +import java.util.Arrays; +import java.util.Scanner; +import java.util.stream.Collectors; +import org.slf4j.Logger; + +/** Console implementation for lottery console service. */ +public class LotteryConsoleServiceImpl implements LotteryConsoleService { + + private final Logger logger; + + /** Constructor. */ + public LotteryConsoleServiceImpl(Logger logger) { + this.logger = logger; + } + + @Override + public void checkTicket(LotteryService service, Scanner scanner) { + logger.info("What is the ID of the lottery ticket?"); + var id = readString(scanner); + logger.info("Give the 4 comma separated winning numbers?"); + var numbers = readString(scanner); + try { + var winningNumbers = + Arrays.stream(numbers.split(",")) + .map(Integer::parseInt) + .limit(4) + .collect(Collectors.toSet()); + + final var lotteryTicketId = new LotteryTicketId(Integer.parseInt(id)); + final var lotteryNumbers = LotteryNumbers.create(winningNumbers); + var result = service.checkTicketForPrize(lotteryTicketId, lotteryNumbers); + + if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { + logger.info("Congratulations! The lottery ticket has won!"); + } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { + logger.info("Unfortunately the lottery ticket did not win."); + } else { + logger.info("Such lottery ticket has not been submitted."); + } + } catch (Exception e) { + logger.info("Failed checking the lottery ticket - please try again."); + } + } + + @Override + public void submitTicket(LotteryService service, Scanner scanner) { + logger.info("What is your email address?"); + var email = readString(scanner); + logger.info("What is your bank account number?"); + var account = readString(scanner); + logger.info("What is your phone number?"); + var phone = readString(scanner); + var details = new PlayerDetails(email, account, phone); + logger.info("Give 4 comma separated lottery numbers?"); + var numbers = readString(scanner); + try { + var chosen = + Arrays.stream(numbers.split(",")).map(Integer::parseInt).collect(Collectors.toSet()); + var lotteryNumbers = LotteryNumbers.create(chosen); + var lotteryTicket = new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers); + service + .submitTicket(lotteryTicket) + .ifPresentOrElse( + (id) -> logger.info("Submitted lottery ticket with id: {}", id), + () -> logger.info("Failed submitting lottery ticket - please try again.")); + } catch (Exception e) { + logger.info("Failed submitting lottery ticket - please try again."); + } + } + + @Override + public void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner) { + logger.info("What is the account number?"); + var account = readString(scanner); + logger.info("How many credits do you want to deposit?"); + var amount = readString(scanner); + bank.setFunds(account, Integer.parseInt(amount)); + logger.info("The account {} now has {} credits.", account, bank.getFunds(account)); + } + + @Override + public void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner) { + logger.info("What is the account number?"); + var account = readString(scanner); + logger.info("The account {} has {} credits.", account, bank.getFunds(account)); + } + + private String readString(Scanner scanner) { + logger.info("> "); + return scanner.next(); + } +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/AppTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/AppTest.java new file mode 100644 index 000000000000..1022ccb09c21 --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Unit test for simple App. */ +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java similarity index 75% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java index f32a7068fd0f..4e3c1fac7b7d 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,29 +24,25 @@ */ package com.iluwatar.hexagonal.banking; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * - * Tests for banking - * - */ -public class InMemoryBankTest { +import org.junit.jupiter.api.Test; + +/** Tests for banking */ +class InMemoryBankTest { private final WireTransfers bank = new InMemoryBank(); - + @Test - public void testInit() { - assertEquals(bank.getFunds("foo"), 0); + void testInit() { + assertEquals(0, bank.getFunds("foo")); bank.setFunds("foo", 100); - assertEquals(bank.getFunds("foo"), 100); + assertEquals(100, bank.getFunds("foo")); bank.setFunds("bar", 150); - assertEquals(bank.getFunds("bar"), 150); + assertEquals(150, bank.getFunds("bar")); assertTrue(bank.transferFunds(50, "bar", "foo")); - assertEquals(bank.getFunds("foo"), 150); - assertEquals(bank.getFunds("bar"), 100); + assertEquals(150, bank.getFunds("foo")); + assertEquals(100, bank.getFunds("bar")); } } diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java new file mode 100644 index 000000000000..8253ac7cb279 --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java @@ -0,0 +1,95 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.banking; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoDatabase; +import de.flapdoodle.embed.mongo.commands.ServerAddress; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.mongo.transitions.Mongod; +import de.flapdoodle.embed.mongo.transitions.RunningMongodProcess; +import de.flapdoodle.reverse.TransitionWalker; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Tests for Mongo banking adapter */ +class MongoBankTest { + + private static final String TEST_DB = "lotteryDBTest"; + private static final String TEST_ACCOUNTS_COLLECTION = "testAccounts"; + + private static MongoClient mongoClient; + private static MongoDatabase mongoDatabase; + + private MongoBank mongoBank; + + private static TransitionWalker.ReachedState mongodProcess; + + private static ServerAddress serverAddress; + + @BeforeAll + static void setUp() { + mongodProcess = Mongod.instance().start(Version.Main.V7_0); + serverAddress = mongodProcess.current().getServerAddress(); + mongoClient = MongoClients.create("mongodb://" + serverAddress.toString()); + mongoClient.startSession(); + mongoDatabase = mongoClient.getDatabase(TEST_DB); + } + + @AfterAll + static void tearDown() { + mongoClient.close(); + mongodProcess.close(); + } + + @BeforeEach + void init() { + System.setProperty("mongo-host", serverAddress.getHost()); + System.setProperty("mongo-port", String.valueOf(serverAddress.getPort())); + mongoDatabase.drop(); + mongoBank = new MongoBank(mongoDatabase.getName(), TEST_ACCOUNTS_COLLECTION); + } + + @Test + void testSetup() { + assertEquals(0, mongoBank.getAccountsCollection().countDocuments()); + } + + @Test + void testFundTransfers() { + assertEquals(0, mongoBank.getFunds("000-000")); + mongoBank.setFunds("000-000", 10); + assertEquals(10, mongoBank.getFunds("000-000")); + assertEquals(0, mongoBank.getFunds("111-111")); + mongoBank.transferFunds(9, "000-000", "111-111"); + assertEquals(1, mongoBank.getFunds("000-000")); + assertEquals(9, mongoBank.getFunds("111-111")); + } +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java new file mode 100644 index 000000000000..5d9017033edf --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java @@ -0,0 +1,55 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.database; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.hexagonal.test.LotteryTestUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Tests for {@link LotteryTicketRepository} */ +class InMemoryTicketRepositoryTest { + + private final LotteryTicketRepository repository = new InMemoryTicketRepository(); + + @BeforeEach + void clear() { + repository.deleteAll(); + } + + @Test + void testCrudOperations() { + var repository = new InMemoryTicketRepository(); + assertTrue(repository.findAll().isEmpty()); + var ticket = LotteryTestUtils.createLotteryTicket(); + var id = repository.save(ticket); + assertTrue(id.isPresent()); + assertEquals(1, repository.findAll().size()); + var optionalTicket = repository.findById(id.get()); + assertTrue(optionalTicket.isPresent()); + } +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java new file mode 100644 index 000000000000..0a45adcace8b --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java @@ -0,0 +1,96 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.database; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.hexagonal.domain.LotteryNumbers; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; +import com.iluwatar.hexagonal.domain.PlayerDetails; +import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import com.mongodb.MongoClient; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** Tests for Mongo based ticket repository */ +@Disabled +class MongoTicketRepositoryTest { + + private static final String TEST_DB = "lotteryTestDB"; + private static final String TEST_TICKETS_COLLECTION = "lotteryTestTickets"; + private static final String TEST_COUNTERS_COLLECTION = "testCounters"; + + private MongoTicketRepository repository; + + @BeforeEach + void init() { + MongoConnectionPropertiesLoader.load(); + var mongoClient = + new MongoClient( + System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient.dropDatabase(TEST_DB); + mongoClient.close(); + repository = + new MongoTicketRepository(TEST_DB, TEST_TICKETS_COLLECTION, TEST_COUNTERS_COLLECTION); + } + + @Test + void testSetup() { + assertEquals(1, repository.getCountersCollection().countDocuments()); + assertEquals(0, repository.getTicketsCollection().countDocuments()); + } + + @Test + void testNextId() { + assertEquals(1, repository.getNextId()); + assertEquals(2, repository.getNextId()); + assertEquals(3, repository.getNextId()); + } + + @Test + void testCrudOperations() { + // create new lottery ticket and save it + var details = new PlayerDetails("foo@bar.com", "123-123", "07001234"); + var random = LotteryNumbers.createRandom(); + var original = new LotteryTicket(new LotteryTicketId(), details, random); + var saved = repository.save(original); + assertEquals(1, repository.getTicketsCollection().countDocuments()); + assertTrue(saved.isPresent()); + // fetch the saved lottery ticket from database and check its contents + var found = repository.findById(saved.get()); + assertTrue(found.isPresent()); + var ticket = found.get(); + assertEquals("foo@bar.com", ticket.playerDetails().email()); + assertEquals("123-123", ticket.playerDetails().bankAccount()); + assertEquals("07001234", ticket.playerDetails().phoneNumber()); + assertEquals(original.lotteryNumbers(), ticket.lotteryNumbers()); + // clear the collection + repository.deleteAll(); + assertEquals(0, repository.getTicketsCollection().countDocuments()); + } +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java new file mode 100644 index 000000000000..0aa740690802 --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java @@ -0,0 +1,68 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Set; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link LotteryNumbers} */ +class LotteryNumbersTest { + + @Test + void testGivenNumbers() { + var numbers = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + assertEquals(numbers.getNumbers().size(), 4); + assertTrue(numbers.getNumbers().contains(1)); + assertTrue(numbers.getNumbers().contains(2)); + assertTrue(numbers.getNumbers().contains(3)); + assertTrue(numbers.getNumbers().contains(4)); + } + + @Test + void testNumbersCantBeModified() { + var numbers = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + assertThrows(UnsupportedOperationException.class, () -> numbers.getNumbers().add(5)); + } + + @Test + void testRandomNumbers() { + var numbers = LotteryNumbers.createRandom(); + assertEquals(numbers.getNumbers().size(), LotteryNumbers.NUM_NUMBERS); + } + + @Test + void testEquals() { + var numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + var numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + assertEquals(numbers1, numbers2); + var numbers3 = LotteryNumbers.create(Set.of(11, 12, 13, 14)); + assertNotEquals(numbers1, numbers3); + } +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java new file mode 100644 index 000000000000..c71f887882ad --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java @@ -0,0 +1,113 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.inject.Guice; +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.iluwatar.hexagonal.banking.WireTransfers; +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; +import com.iluwatar.hexagonal.module.LotteryTestingModule; +import com.iluwatar.hexagonal.test.LotteryTestUtils; +import java.util.Set; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Test the lottery system */ +class LotteryTest { + + private final Injector injector; + @Inject private LotteryAdministration administration; + @Inject private LotteryService service; + @Inject private WireTransfers wireTransfers; + + LotteryTest() { + this.injector = Guice.createInjector(new LotteryTestingModule()); + } + + @BeforeEach + void setup() { + injector.injectMembers(this); + // add funds to the test player's bank account + wireTransfers.setFunds("123-12312", 100); + } + + @Test + void testLottery() { + // admin resets the lottery + administration.resetLottery(); + assertEquals(0, administration.getAllSubmittedTickets().size()); + + // players submit the lottery tickets + var ticket1 = + service.submitTicket( + LotteryTestUtils.createLotteryTicket( + "cvt@bbb.com", "123-12312", "+32425255", Set.of(1, 2, 3, 4))); + assertTrue(ticket1.isPresent()); + var ticket2 = + service.submitTicket( + LotteryTestUtils.createLotteryTicket( + "ant@bac.com", "123-12312", "+32423455", Set.of(11, 12, 13, 14))); + assertTrue(ticket2.isPresent()); + var ticket3 = + service.submitTicket( + LotteryTestUtils.createLotteryTicket( + "arg@boo.com", "123-12312", "+32421255", Set.of(6, 8, 13, 19))); + assertTrue(ticket3.isPresent()); + assertEquals(3, administration.getAllSubmittedTickets().size()); + + // perform lottery + var winningNumbers = administration.performLottery(); + + // cheat a bit for testing sake, use winning numbers to submit another ticket + var ticket4 = + service.submitTicket( + LotteryTestUtils.createLotteryTicket( + "lucky@orb.com", "123-12312", "+12421255", winningNumbers.getNumbers())); + assertTrue(ticket4.isPresent()); + assertEquals(4, administration.getAllSubmittedTickets().size()); + + // check winners + var tickets = administration.getAllSubmittedTickets(); + for (var id : tickets.keySet()) { + var checkResult = service.checkTicketForPrize(id, winningNumbers); + assertNotEquals(CheckResult.TICKET_NOT_SUBMITTED, checkResult.getResult()); + if (checkResult.getResult().equals(CheckResult.WIN_PRIZE)) { + assertTrue(checkResult.getPrizeAmount() > 0); + } else { + assertEquals(0, checkResult.getPrizeAmount()); + } + } + + // check another ticket that has not been submitted + var checkResult = service.checkTicketForPrize(new LotteryTicketId(), winningNumbers); + assertEquals(CheckResult.TICKET_NOT_SUBMITTED, checkResult.getResult()); + assertEquals(0, checkResult.getPrizeAmount()); + } +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java new file mode 100644 index 000000000000..05af100dc68d --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link LotteryTicketCheckResult} */ +class LotteryTicketCheckResultTest { + + @Test + void testEquals() { + var result1 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); + var result2 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); + assertEquals(result1, result2); + var result3 = new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 300000); + assertNotEquals(result1, result3); + } +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java new file mode 100644 index 000000000000..cde988eaa6d2 --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import org.junit.jupiter.api.Test; + +/** Tests for lottery ticket id */ +class LotteryTicketIdTest { + + @Test + void testEquals() { + var ticketId1 = new LotteryTicketId(); + var ticketId2 = new LotteryTicketId(); + var ticketId3 = new LotteryTicketId(); + assertNotEquals(ticketId1, ticketId2); + assertNotEquals(ticketId2, ticketId3); + var ticketId4 = new LotteryTicketId(ticketId1.getId()); + assertEquals(ticketId1, ticketId4); + } +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java new file mode 100644 index 000000000000..9b8e400c8957 --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import java.util.Set; +import org.junit.jupiter.api.Test; + +/** Test Lottery Tickets for equality */ +class LotteryTicketTest { + + @Test + void testEquals() { + var details1 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); + var numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + var ticket1 = new LotteryTicket(new LotteryTicketId(), details1, numbers1); + var details2 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); + var numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + var ticket2 = new LotteryTicket(new LotteryTicketId(), details2, numbers2); + assertEquals(ticket1, ticket2); + var details3 = new PlayerDetails("elsa@foo.bar", "1223-121212", "+49332322"); + var numbers3 = LotteryNumbers.create(Set.of(1, 2, 3, 8)); + var ticket3 = new LotteryTicket(new LotteryTicketId(), details3, numbers3); + assertNotEquals(ticket1, ticket3); + } +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java new file mode 100644 index 000000000000..266f907797fb --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.domain; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link PlayerDetails} */ +class PlayerDetailsTest { + + @Test + void testEquals() { + var details1 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); + var details2 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); + assertEquals(details1, details2); + var details3 = new PlayerDetails("john@foo.bar", "16412-123439", "+34323432"); + assertNotEquals(details1, details3); + } +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java new file mode 100644 index 000000000000..0227d9a6da6f --- /dev/null +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java @@ -0,0 +1,85 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.hexagonal.eventlog; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.iluwatar.hexagonal.domain.PlayerDetails; +import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import com.mongodb.MongoClient; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** Tests for Mongo event log */ +@Disabled +class MongoEventLogTest { + + private static final String TEST_DB = "lotteryDBTest"; + private static final String TEST_EVENTS_COLLECTION = "testEvents"; + + private MongoEventLog mongoEventLog; + + @BeforeEach + void init() { + MongoConnectionPropertiesLoader.load(); + var mongoClient = + new MongoClient( + System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient.dropDatabase(TEST_DB); + mongoClient.close(); + mongoEventLog = new MongoEventLog(TEST_DB, TEST_EVENTS_COLLECTION); + } + + @Test + void testSetup() { + assertEquals(0, mongoEventLog.getEventsCollection().countDocuments()); + } + + @Test + void testFundTransfers() { + var playerDetails = new PlayerDetails("john@wayne.com", "000-000", "03432534543"); + mongoEventLog.prizeError(playerDetails, 1000); + assertEquals(1, mongoEventLog.getEventsCollection().countDocuments()); + mongoEventLog.prizeError(playerDetails, 1000); + assertEquals(2, mongoEventLog.getEventsCollection().countDocuments()); + mongoEventLog.ticketDidNotWin(playerDetails); + assertEquals(3, mongoEventLog.getEventsCollection().countDocuments()); + mongoEventLog.ticketDidNotWin(playerDetails); + assertEquals(4, mongoEventLog.getEventsCollection().countDocuments()); + mongoEventLog.ticketSubmitError(playerDetails); + assertEquals(5, mongoEventLog.getEventsCollection().countDocuments()); + mongoEventLog.ticketSubmitError(playerDetails); + assertEquals(6, mongoEventLog.getEventsCollection().countDocuments()); + mongoEventLog.ticketSubmitted(playerDetails); + assertEquals(7, mongoEventLog.getEventsCollection().countDocuments()); + mongoEventLog.ticketSubmitted(playerDetails); + assertEquals(8, mongoEventLog.getEventsCollection().countDocuments()); + mongoEventLog.ticketWon(playerDetails, 1000); + assertEquals(9, mongoEventLog.getEventsCollection().countDocuments()); + mongoEventLog.ticketWon(playerDetails, 1000); + assertEquals(10, mongoEventLog.getEventsCollection().countDocuments()); + } +} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java similarity index 77% rename from hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java rename to hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java index 7f6c0edab291..3002879ba468 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,36 +24,29 @@ */ package com.iluwatar.hexagonal.test; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - import com.iluwatar.hexagonal.domain.LotteryNumbers; import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; +import java.util.Set; -/** - * - * Utilities for lottery tests - * - */ +/** Utilities for lottery tests */ public class LotteryTestUtils { /** * @return lottery ticket */ public static LotteryTicket createLotteryTicket() { - return createLotteryTicket("foo@bar.com", "12231-213132", "+99324554", new HashSet<>(Arrays.asList(1, 2, 3, 4))); + return createLotteryTicket("foo@bar.com", "12231-213132", "+99324554", Set.of(1, 2, 3, 4)); } - + /** * @return lottery ticket */ - public static LotteryTicket createLotteryTicket(String email, String account, String phone, - Set givenNumbers) { - PlayerDetails details = new PlayerDetails(email, account, phone); - LotteryNumbers numbers = LotteryNumbers.create(givenNumbers); + public static LotteryTicket createLotteryTicket( + String email, String account, String phone, Set givenNumbers) { + var details = new PlayerDetails(email, account, phone); + var numbers = LotteryNumbers.create(givenNumbers); return new LotteryTicket(new LotteryTicketId(), details, numbers); } } diff --git a/hexagonal/README.md b/hexagonal/README.md deleted file mode 100644 index 7d27f4b622b8..000000000000 --- a/hexagonal/README.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -layout: pattern -title: Hexagonal Architecture -folder: hexagonal -permalink: /patterns/hexagonal/ -pumlformat: svg -categories: Architectural -tags: - - Java - - Difficulty-Expert ---- - -## Also known as -* Ports and Adapters -* Clean Architecture -* Onion Architecture - -## Intent -Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases. - -![Hexagonal Architecture class diagram](./etc/hexagonal.png) - -## Applicability -Use Hexagonal Architecture pattern when - -* When the application needs to be independent of any frameworks -* When it is important that the application highly maintainable and fully testable - -## Tutorials -* [Build Maintainable Systems With Hexagonal Architecture](http://java-design-patterns.com/blog/build-maintainable-systems-with-hexagonal-architecture/) - -## Presentations -* [Hexagonal Architecture](https://github.com/iluwatar/java-design-patterns/tree/master/hexagonal/etc/presentation.html) - -## Real world examples - -* [Apache Isis](https://isis.apache.org/) builds generic UI and REST API directly from the underlying domain objects - -## Credits - -* [Alistair Cockburn - Hexagonal Architecture](http://alistair.cockburn.us/Hexagonal+architecture) diff --git a/hexagonal/etc/layers.png b/hexagonal/etc/layers.png deleted file mode 100644 index cb5a9c90bbe9..000000000000 Binary files a/hexagonal/etc/layers.png and /dev/null differ diff --git a/hexagonal/etc/ports_and_adapters.png b/hexagonal/etc/ports_and_adapters.png deleted file mode 100644 index d285045dea68..000000000000 Binary files a/hexagonal/etc/ports_and_adapters.png and /dev/null differ diff --git a/hexagonal/etc/ports_and_adapters.xml b/hexagonal/etc/ports_and_adapters.xml deleted file mode 100644 index 9df3173d902e..000000000000 --- a/hexagonal/etc/ports_and_adapters.xml +++ /dev/null @@ -1,25 +0,0 @@ - -7Zpdk6I4FIZ/jbdbJAHEyx7nY/diqrqqd2tnLiOJSDUSK6ZHe3/9BkmUfFiDDqBM2TcNBwLxOe85nBOYoPl6/4XjzeorI7SYwIDsJ+jjBEKA4kj+qyzvtWUag9qQ8Zyok06Gl/w/qoyBsr7lhG6NEwVjhcg3pjFlZUlTYdgw52xnnrZkhXnXDc6oY3hJceFa/82JWNXWJApO9j9pnq30nUGgjixw+ppx9laq+00gWh7+6sNrrK+lzt+uMGG7hgl9mqA5Z0zUW+v9nBYVW42tHvf5zNHjvDktRZsBqB7wAxdvVM/4MC/xrlnIKW6qzRXd44yVE/RhQ3m+poLyk/X5ZPqwW+WCvmxwWo3aSYFI20qsC7kH5Ka6I+WC7s/OGhxZSI1RJi/N3+UpagBMFD4lL6D3dydnIa2lVcNRMFZGrASSHa99giQ3FCc/MzhKZmgaGcyOKBrMAPQwO2r7V5iFDrM549ThJgfJEKc/B7LMi2LOCsYP46oYg2kq7VvB2SttHCHxIo7ibhCGATARJshBqDNfk2AXoot+Lrpr4RFMk6UXXpwmdLHsCF5s6W/qwkMe+aEO4MW/GzwEPQmvJ3jT0cMDMxNeGA0GLxk7PDQ1H7VDKm82fnh2zoODwdPlz3jphdCUHoyGkx5oUeRdTS+iCQl99BK4QHFHxUoUWfQ89V5v9Fq0FXdOz9ZeMCC9Nk/ckjxVfa7cK1lJTWJ0n4tvje3vcjuotks5k2/Nne/6rJJ8zqsJHQ7Vd6PE6ZEtenJG7I2n1KhQBeYZFU0duJAbECMPRG3jtMAi/2HOwkdW3eGZ5XJ+Z7vECFjOqWevRjWbZOtCCJkXCu2Cvv7NzoUOjj7+7Ha+b1MwXOz7P6IefQwfPr7Qx33WNYNkR5s60nXuANkR9lnXDEIPWc8WNBvu2aJn+8v5JfDkF/V0Ac2nS3e5J/Hkntkj91yWe7S7O/U/OO/9/nzfWC5/+L6d70dfldsrOSEcbiXHs4R9ZeTUGdEXO41E2mX0TD3Rc1+Vue2gq6Mn6S963BX4Z8bF1hGBlLcwPW/GhFJGM4CUCRd5VsrdVDrz8FaoCpY8xcWTOrDOCSnOBWcH8YVmoYHzGDgNWYS+12pdxJe7SP/PVlKQZ1Q0ltVvtVEfXrRSojD3/w4NALvudd9hAN97x7ALQO6ywN90WwUDzqiS903h2CvFiZucZ32xcdvmv6RqMi6zFCtvjuZY4et851lN6g2N221+xAIv8Pb28RQHJhcwG04yOrU1uHxl6au0kLvBYz3dYOTi6S3doPF2irpKNAqe2I96mIIHWJ6Mr20XgF059dcuoD5axWEEoOsRQwDThwAuFECbfvE+Ox5dlxkCSB4CuFAAXbW8vpcRvldRHT4CfAK46WrhKAXQ5quzOxUAdAWAbrpkOEoBuE35E8Eb2Y//XuseVh+CPP1ZR+secvf0dXftkdMn9OjT/w== \ No newline at end of file diff --git a/hexagonal/etc/presentation.html b/hexagonal/etc/presentation.html deleted file mode 100644 index 5c6d1d0a5c6a..000000000000 --- a/hexagonal/etc/presentation.html +++ /dev/null @@ -1,127 +0,0 @@ - - - - - Title - - - - - - - - - - diff --git a/hexagonal/pom.xml b/hexagonal/pom.xml deleted file mode 100644 index e6084ac70fbd..000000000000 --- a/hexagonal/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - hexagonal - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - com.google.inject - guice - - - org.mongodb - mongo-java-driver - - - diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java deleted file mode 100644 index 6e226a1e19a8..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/App.java +++ /dev/null @@ -1,83 +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.hexagonal; - -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.iluwatar.hexagonal.domain.LotteryAdministration; -import com.iluwatar.hexagonal.domain.LotteryService; -import com.iluwatar.hexagonal.module.LotteryTestingModule; -import com.iluwatar.hexagonal.sampledata.SampleData; - -/** - * - * Hexagonal Architecture pattern decouples the application core from the - * services it uses. This allows the services to be plugged in and the - * application will run with or without the services.

    - * - * The core logic, or business logic, of an application consists of the - * algorithms that are essential to its purpose. They implement the use - * cases that are the heart of the application. When you change them, you - * change the essence of the application.

    - * - * The services are not essential. They can be replaced without changing - * the purpose of the application. Examples: database access and other - * types of storage, user interface components, e-mail and other - * communication components, hardware devices.

    - * - * This example demonstrates Hexagonal Architecture with a lottery system. - * The application core is separate from the services that drive it and - * from the services it uses.

    - * - * The primary ports for the application are console interfaces - * {@link com.iluwatar.hexagonal.administration.ConsoleAdministration} through which the lottery round is - * initiated and run and {@link com.iluwatar.hexagonal.service.ConsoleLottery} that allows players to - * submit lottery tickets for the draw.

    - * - * The secondary ports that application core uses are {@link com.iluwatar.hexagonal.banking.WireTransfers} - * which is a banking service, {@link com.iluwatar.hexagonal.eventlog.LotteryEventLog} that delivers - * eventlog as lottery events occur and {@link com.iluwatar.hexagonal.database.LotteryTicketRepository} - * that is the storage for the lottery tickets. - * - */ -public class App { - - /** - * Program entry point - */ - public static void main(String[] args) { - - Injector injector = Guice.createInjector(new LotteryTestingModule()); - - // start new lottery round - LotteryAdministration administartion = injector.getInstance(LotteryAdministration.class); - administartion.resetLottery(); - - // submit some lottery tickets - LotteryService service = injector.getInstance(LotteryService.class); - SampleData.submitTickets(service, 20); - - // perform lottery - administartion.performLottery(); - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java deleted file mode 100644 index 9dc20f87c63e..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java +++ /dev/null @@ -1,90 +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.hexagonal.administration; - -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.iluwatar.hexagonal.domain.LotteryAdministration; -import com.iluwatar.hexagonal.domain.LotteryNumbers; -import com.iluwatar.hexagonal.domain.LotteryService; -import com.iluwatar.hexagonal.module.LotteryModule; -import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; -import com.iluwatar.hexagonal.sampledata.SampleData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Scanner; - -/** - * Console interface for lottery administration - */ -public class ConsoleAdministration { - - private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleAdministration.class); - - /** - * Program entry point - */ - public static void main(String[] args) { - MongoConnectionPropertiesLoader.load(); - Injector injector = Guice.createInjector(new LotteryModule()); - LotteryAdministration administartion = injector.getInstance(LotteryAdministration.class); - LotteryService service = injector.getInstance(LotteryService.class); - SampleData.submitTickets(service, 20); - try (Scanner scanner = new Scanner(System.in)) { - boolean exit = false; - while (!exit) { - printMainMenu(); - String cmd = readString(scanner); - if ("1".equals(cmd)) { - administartion.getAllSubmittedTickets().forEach((k, v) -> LOGGER.info("Key: {}, Value: {}", k, v)); - } else if ("2".equals(cmd)) { - LotteryNumbers numbers = administartion.performLottery(); - LOGGER.info("The winning numbers: {}", numbers.getNumbersAsString()); - LOGGER.info("Time to reset the database for next round, eh?"); - } else if ("3".equals(cmd)) { - administartion.resetLottery(); - LOGGER.info("The lottery ticket database was cleared."); - } else if ("4".equals(cmd)) { - exit = true; - } else { - LOGGER.info("Unknown command: {}", cmd); - } - } - } - } - - private static void printMainMenu() { - LOGGER.info(""); - LOGGER.info("### Lottery Administration Console ###"); - LOGGER.info("(1) Show all submitted tickets"); - LOGGER.info("(2) Perform lottery draw"); - LOGGER.info("(3) Reset lottery ticket database"); - LOGGER.info("(4) Exit"); - } - - private static String readString(Scanner scanner) { - System.out.print("> "); - return scanner.next(); - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java deleted file mode 100644 index a8eb7817c046..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java +++ /dev/null @@ -1,63 +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.hexagonal.banking; - -import java.util.HashMap; -import java.util.Map; - -import com.iluwatar.hexagonal.domain.LotteryConstants; - -/** - * - * Banking implementation - * - */ -public class InMemoryBank implements WireTransfers { - - private static Map accounts = new HashMap<>(); - - static { - accounts.put(LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_SALDO); - } - - @Override - public void setFunds(String bankAccount, int amount) { - accounts.put(bankAccount, amount); - } - - @Override - public int getFunds(String bankAccount) { - return accounts.getOrDefault(bankAccount, 0); - } - - @Override - public boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount) { - if (accounts.getOrDefault(sourceBackAccount, 0) >= amount) { - accounts.put(sourceBackAccount, accounts.get(sourceBackAccount) - amount); - accounts.put(destinationBankAccount, accounts.get(destinationBankAccount) + amount); - return true; - } else { - return false; - } - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java deleted file mode 100644 index 7ccc829eda98..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java +++ /dev/null @@ -1,134 +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.hexagonal.banking; - -import com.mongodb.MongoClient; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.UpdateOptions; -import org.bson.Document; - -import java.util.ArrayList; -import java.util.List; - -/** - * Mongo based banking adapter - */ -public class MongoBank implements WireTransfers { - - private static final String DEFAULT_DB = "lotteryDB"; - private static final String DEFAULT_ACCOUNTS_COLLECTION = "accounts"; - - private MongoClient mongoClient; - private MongoDatabase database; - private MongoCollection accountsCollection; - - /** - * Constructor - */ - public MongoBank() { - connect(); - } - - /** - * Constructor accepting parameters - */ - public MongoBank(String dbName, String accountsCollectionName) { - connect(dbName, accountsCollectionName); - } - - /** - * Connect to database with default parameters - */ - public void connect() { - connect(DEFAULT_DB, DEFAULT_ACCOUNTS_COLLECTION); - } - - /** - * Connect to database with given parameters - */ - public void connect(String dbName, String accountsCollectionName) { - if (mongoClient != null) { - mongoClient.close(); - } - mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); - database = mongoClient.getDatabase(dbName); - accountsCollection = database.getCollection(accountsCollectionName); - } - - /** - * @return mongo client - */ - public MongoClient getMongoClient() { - return mongoClient; - } - - /** - * - * @return mongo database - */ - public MongoDatabase getMongoDatabase() { - return database; - } - - /** - * - * @return accounts collection - */ - public MongoCollection getAccountsCollection() { - return accountsCollection; - } - - - @Override - public void setFunds(String bankAccount, int amount) { - Document search = new Document("_id", bankAccount); - Document update = new Document("_id", bankAccount).append("funds", amount); - accountsCollection.updateOne(search, new Document("$set", update), new UpdateOptions().upsert(true)); - } - - @Override - public int getFunds(String bankAccount) { - Document search = new Document("_id", bankAccount); - List results = accountsCollection.find(search).limit(1).into(new ArrayList()); - if (results.size() > 0) { - return results.get(0).getInteger("funds"); - } else { - return 0; - } - } - - @Override - public boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount) { - int sourceFunds = getFunds(sourceBackAccount); - if (sourceFunds < amount) { - return false; - } else { - int destFunds = getFunds(destinationBankAccount); - setFunds(sourceBackAccount, sourceFunds - amount); - setFunds(destinationBankAccount, destFunds + amount); - return true; - } - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java deleted file mode 100644 index ac747d4eaf4e..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java +++ /dev/null @@ -1,195 +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.hexagonal.database; - -import com.iluwatar.hexagonal.domain.LotteryNumbers; -import com.iluwatar.hexagonal.domain.LotteryTicket; -import com.iluwatar.hexagonal.domain.LotteryTicketId; -import com.iluwatar.hexagonal.domain.PlayerDetails; -import com.mongodb.MongoClient; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import org.bson.Document; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * Mongo lottery ticket database - */ -public class MongoTicketRepository implements LotteryTicketRepository { - - private static final String DEFAULT_DB = "lotteryDB"; - private static final String DEFAULT_TICKETS_COLLECTION = "lotteryTickets"; - private static final String DEFAULT_COUNTERS_COLLECTION = "counters"; - - private MongoClient mongoClient; - private MongoDatabase database; - private MongoCollection ticketsCollection; - private MongoCollection countersCollection; - - /** - * Constructor - */ - public MongoTicketRepository() { - connect(); - } - - /** - * Constructor accepting parameters - */ - public MongoTicketRepository(String dbName, String ticketsCollectionName, - String countersCollectionName) { - connect(dbName, ticketsCollectionName, countersCollectionName); - } - - /** - * Connect to database with default parameters - */ - public void connect() { - connect(DEFAULT_DB, DEFAULT_TICKETS_COLLECTION, DEFAULT_COUNTERS_COLLECTION); - } - - /** - * Connect to database with given parameters - */ - public void connect(String dbName, String ticketsCollectionName, - String countersCollectionName) { - if (mongoClient != null) { - mongoClient.close(); - } - mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); - database = mongoClient.getDatabase(dbName); - ticketsCollection = database.getCollection(ticketsCollectionName); - countersCollection = database.getCollection(countersCollectionName); - if (countersCollection.count() <= 0) { - initCounters(); - } - } - - private void initCounters() { - Document doc = new Document("_id", "ticketId").append("seq", 1); - countersCollection.insertOne(doc); - } - - /** - * @return next ticket id - */ - public int getNextId() { - Document find = new Document("_id", "ticketId"); - Document increase = new Document("seq", 1); - Document update = new Document("$inc", increase); - Document result = countersCollection.findOneAndUpdate(find, update); - return result.getInteger("seq"); - } - - /** - * @return mongo client - */ - public MongoClient getMongoClient() { - return mongoClient; - } - - /** - * - * @return mongo database - */ - public MongoDatabase getMongoDatabase() { - return database; - } - - /** - * - * @return tickets collection - */ - public MongoCollection getTicketsCollection() { - return ticketsCollection; - } - - /** - * - * @return counters collection - */ - public MongoCollection getCountersCollection() { - return countersCollection; - } - - @Override - public Optional findById(LotteryTicketId id) { - Document find = new Document("ticketId", id.getId()); - List results = ticketsCollection.find(find).limit(1).into(new ArrayList()); - if (results.size() > 0) { - LotteryTicket lotteryTicket = docToTicket(results.get(0)); - return Optional.of(lotteryTicket); - } else { - return Optional.empty(); - } - } - - @Override - public Optional save(LotteryTicket ticket) { - int ticketId = getNextId(); - Document doc = new Document("ticketId", ticketId); - doc.put("email", ticket.getPlayerDetails().getEmail()); - doc.put("bank", ticket.getPlayerDetails().getBankAccount()); - doc.put("phone", ticket.getPlayerDetails().getPhoneNumber()); - doc.put("numbers", ticket.getNumbers().getNumbersAsString()); - ticketsCollection.insertOne(doc); - return Optional.of(new LotteryTicketId(ticketId)); - } - - @Override - public Map findAll() { - Map map = new HashMap<>(); - List docs = ticketsCollection.find(new Document()).into(new ArrayList()); - for (Document doc: docs) { - LotteryTicket lotteryTicket = docToTicket(doc); - map.put(lotteryTicket.getId(), lotteryTicket); - } - return map; - } - - @Override - public void deleteAll() { - ticketsCollection.deleteMany(new Document()); - } - - private LotteryTicket docToTicket(Document doc) { - PlayerDetails playerDetails = new PlayerDetails(doc.getString("email"), doc.getString("bank"), - doc.getString("phone")); - int[] numArray = Arrays.asList(doc.getString("numbers").split(",")).stream().mapToInt(Integer::parseInt).toArray(); - Set numbers = new HashSet<>(); - for (int num: numArray) { - numbers.add(num); - } - LotteryNumbers lotteryNumbers = LotteryNumbers.create(numbers); - return new LotteryTicket(new LotteryTicketId(doc.getInteger("ticketId")), playerDetails, lotteryNumbers); - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java deleted file mode 100644 index b8681b57ecde..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java +++ /dev/null @@ -1,90 +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.hexagonal.domain; - -import com.google.inject.Inject; -import com.iluwatar.hexagonal.banking.WireTransfers; -import com.iluwatar.hexagonal.database.LotteryTicketRepository; -import com.iluwatar.hexagonal.eventlog.LotteryEventLog; - -import java.util.Map; - -/** - * - * Lottery administration implementation - * - */ -public class LotteryAdministration { - - private final LotteryTicketRepository repository; - private final LotteryEventLog notifications; - private final WireTransfers wireTransfers; - - /** - * Constructor - */ - @Inject - public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog notifications, - WireTransfers wireTransfers) { - this.repository = repository; - this.notifications = notifications; - this.wireTransfers = wireTransfers; - } - - /** - * Get all the lottery tickets submitted for lottery - */ - public Map getAllSubmittedTickets() { - return repository.findAll(); - } - - /** - * Draw lottery numbers - */ - public LotteryNumbers performLottery() { - LotteryNumbers numbers = LotteryNumbers.createRandom(); - Map tickets = getAllSubmittedTickets(); - for (LotteryTicketId id : tickets.keySet()) { - LotteryTicketCheckResult result = LotteryUtils.checkTicketForPrize(repository, id, numbers); - if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { - boolean transferred = wireTransfers.transferFunds(LotteryConstants.PRIZE_AMOUNT, - LotteryConstants.SERVICE_BANK_ACCOUNT, tickets.get(id).getPlayerDetails().getBankAccount()); - if (transferred) { - notifications.ticketWon(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); - } else { - notifications.prizeError(tickets.get(id).getPlayerDetails(), LotteryConstants.PRIZE_AMOUNT); - } - } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { - notifications.ticketDidNotWin(tickets.get(id).getPlayerDetails()); - } - } - return numbers; - } - - /** - * Begin new lottery round - */ - public void resetLottery() { - repository.deleteAll(); - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java deleted file mode 100644 index a688647fad22..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java +++ /dev/null @@ -1,175 +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.hexagonal.domain; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.PrimitiveIterator; -import java.util.Random; -import java.util.Set; - -/** - * - * Value object representing lottery numbers. This lottery uses sets of 4 numbers. The numbers must be unique and - * between 1 and 20. - * - */ -public class LotteryNumbers { - - private final Set numbers; - - public static final int MIN_NUMBER = 1; - public static final int MAX_NUMBER = 20; - public static final int NUM_NUMBERS = 4; - - /** - * Constructor. Creates random lottery numbers. - */ - private LotteryNumbers() { - numbers = new HashSet<>(); - generateRandomNumbers(); - } - - /** - * Constructor. Uses given numbers. - */ - private LotteryNumbers(Set givenNumbers) { - numbers = new HashSet<>(); - numbers.addAll(givenNumbers); - } - - /** - * @return random LotteryNumbers - */ - public static LotteryNumbers createRandom() { - return new LotteryNumbers(); - } - - /** - * @return given LotteryNumbers - */ - public static LotteryNumbers create(Set givenNumbers) { - return new LotteryNumbers(givenNumbers); - } - - /** - * @return lottery numbers - */ - public Set getNumbers() { - return Collections.unmodifiableSet(numbers); - } - - /** - * @return numbers as comma separated string - */ - public String getNumbersAsString() { - List list = new ArrayList<>(); - list.addAll(numbers); - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < NUM_NUMBERS; i++) { - builder.append(list.get(i)); - if (i < NUM_NUMBERS - 1) { - builder.append(","); - } - } - return builder.toString(); - } - - /** - * Generates 4 unique random numbers between 1-20 into numbers set. - */ - private void generateRandomNumbers() { - numbers.clear(); - RandomNumberGenerator generator = new RandomNumberGenerator(MIN_NUMBER, MAX_NUMBER); - while (numbers.size() < NUM_NUMBERS) { - int num = generator.nextInt(); - if (!numbers.contains(num)) { - numbers.add(num); - } - } - } - - @Override - public String toString() { - return "LotteryNumbers{" + "numbers=" + numbers + '}'; - } - - /** - * - * Helper class for generating random numbers. - * - */ - private static class RandomNumberGenerator { - - private PrimitiveIterator.OfInt randomIterator; - - /** - * Initialize a new random number generator that generates random numbers in the range [min, max] - * - * @param min the min value (inclusive) - * @param max the max value (inclusive) - */ - public RandomNumberGenerator(int min, int max) { - randomIterator = new Random().ints(min, max + 1).iterator(); - } - - /** - * @return a random number in the range (min, max) - */ - public int nextInt() { - return randomIterator.nextInt(); - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((numbers == null) ? 0 : numbers.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - LotteryNumbers other = (LotteryNumbers) obj; - if (numbers == null) { - if (other.numbers != null) { - return false; - } - } else if (!numbers.equals(other.numbers)) { - return false; - } - return true; - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java deleted file mode 100644 index 7afa76503b4b..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java +++ /dev/null @@ -1,77 +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.hexagonal.domain; - -import com.google.inject.Inject; -import com.iluwatar.hexagonal.banking.WireTransfers; -import com.iluwatar.hexagonal.database.LotteryTicketRepository; -import com.iluwatar.hexagonal.eventlog.LotteryEventLog; - -import java.util.Optional; - -/** - * - * Implementation for lottery service - * - */ -public class LotteryService { - - private final LotteryTicketRepository repository; - private final LotteryEventLog notifications; - private final WireTransfers wireTransfers; - - /** - * Constructor - */ - @Inject - public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifications, - WireTransfers wireTransfers) { - this.repository = repository; - this.notifications = notifications; - this.wireTransfers = wireTransfers; - } - - /** - * Submit lottery ticket to participate in the lottery - */ - public Optional submitTicket(LotteryTicket ticket) { - boolean result = wireTransfers.transferFunds(LotteryConstants.TICKET_PRIZE, - ticket.getPlayerDetails().getBankAccount(), LotteryConstants.SERVICE_BANK_ACCOUNT); - if (!result) { - notifications.ticketSubmitError(ticket.getPlayerDetails()); - return Optional.empty(); - } - Optional optional = repository.save(ticket); - if (optional.isPresent()) { - notifications.ticketSubmitted(ticket.getPlayerDetails()); - } - return optional; - } - - /** - * Check if lottery ticket has won - */ - public LotteryTicketCheckResult checkTicketForPrize(LotteryTicketId id, LotteryNumbers winningNumbers) { - return LotteryUtils.checkTicketForPrize(repository, id, winningNumbers); - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java deleted file mode 100644 index 2c5340b63b2c..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java +++ /dev/null @@ -1,115 +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.hexagonal.domain; - -/** - * - * Immutable value object representing lottery ticket. - * - */ -public class LotteryTicket { - - private LotteryTicketId id; - private final PlayerDetails playerDetails; - private final LotteryNumbers lotteryNumbers; - - /** - * Constructor. - */ - public LotteryTicket(LotteryTicketId id, PlayerDetails details, LotteryNumbers numbers) { - this.id = id; - playerDetails = details; - lotteryNumbers = numbers; - } - - /** - * @return player details - */ - public PlayerDetails getPlayerDetails() { - return playerDetails; - } - - /** - * @return lottery numbers - */ - public LotteryNumbers getNumbers() { - return lotteryNumbers; - } - - /** - * @return id - */ - public LotteryTicketId getId() { - return id; - } - - /** - * set id - */ - public void setId(LotteryTicketId id) { - this.id = id; - } - - @Override - public String toString() { - return playerDetails.toString() + " " + lotteryNumbers.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((lotteryNumbers == null) ? 0 : lotteryNumbers.hashCode()); - result = prime * result + ((playerDetails == null) ? 0 : playerDetails.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - LotteryTicket other = (LotteryTicket) obj; - if (lotteryNumbers == null) { - if (other.lotteryNumbers != null) { - return false; - } - } else if (!lotteryNumbers.equals(other.lotteryNumbers)) { - return false; - } - if (playerDetails == null) { - if (other.playerDetails != null) { - return false; - } - } else if (!playerDetails.equals(other.playerDetails)) { - return false; - } - return true; - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java deleted file mode 100644 index a5b455354370..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java +++ /dev/null @@ -1,93 +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.hexagonal.domain; - -/** - * - * Represents lottery ticket check result. - * - */ -public class LotteryTicketCheckResult { - - /** - * Enumeration of Type of Outcomes of a Lottery - */ - public enum CheckResult { WIN_PRIZE, NO_PRIZE, TICKET_NOT_SUBMITTED } - - private final CheckResult checkResult; - private final int prizeAmount; - - /** - * Constructor. - */ - public LotteryTicketCheckResult(CheckResult result) { - checkResult = result; - prizeAmount = 0; - } - - /** - * Constructor. - */ - public LotteryTicketCheckResult(CheckResult result, int amount) { - checkResult = result; - prizeAmount = amount; - } - - /** - * @return check result - */ - public CheckResult getResult() { - return checkResult; - } - - /** - * @return prize amount - */ - public int getPrizeAmount() { - return prizeAmount; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((checkResult == null) ? 0 : checkResult.hashCode()); - result = prime * result + prizeAmount; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - LotteryTicketCheckResult other = (LotteryTicketCheckResult) obj; - return checkResult == other.checkResult && prizeAmount == other.prizeAmount; - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java deleted file mode 100644 index 838fdb32b843..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java +++ /dev/null @@ -1,70 +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.hexagonal.domain; - -/** - * Lottery ticked id - */ -public class LotteryTicketId { - - private static volatile int numAllocated; - private final int id; - - public LotteryTicketId() { - this.id = numAllocated + 1; - numAllocated++; - } - - public LotteryTicketId(int id) { - this.id = id; - } - - public int getId() { - return id; - } - - @Override - public String toString() { - return String.format("%d", id); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - LotteryTicketId that = (LotteryTicketId) o; - - return id == that.id; - - } - - @Override - public int hashCode() { - return id; - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java deleted file mode 100644 index 2f3c3be222a0..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.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.hexagonal.domain; - -import com.iluwatar.hexagonal.database.LotteryTicketRepository; - -import java.util.Optional; - -/** - * Lottery utilities - */ -public class LotteryUtils { - - private LotteryUtils() { - } - - /** - * Checks if lottery ticket has won - */ - public static LotteryTicketCheckResult checkTicketForPrize(LotteryTicketRepository repository, LotteryTicketId id, - LotteryNumbers winningNumbers) { - Optional optional = repository.findById(id); - if (optional.isPresent()) { - if (optional.get().getNumbers().equals(winningNumbers)) { - return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.WIN_PRIZE, 1000); - } else { - return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.NO_PRIZE); - } - } else { - return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.TICKET_NOT_SUBMITTED); - } - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java deleted file mode 100644 index 6f47d6cf5a0d..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java +++ /dev/null @@ -1,118 +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.hexagonal.domain; - -/** - * - * Immutable value object containing lottery player details. - * - */ -public class PlayerDetails { - - private final String emailAddress; - private final String bankAccountNumber; - private final String phoneNumber; - - /** - * Constructor. - */ - public PlayerDetails(String email, String bankAccount, String phone) { - emailAddress = email; - bankAccountNumber = bankAccount; - phoneNumber = phone; - } - - /** - * @return email - */ - public String getEmail() { - return emailAddress; - } - - /** - * @return bank account number - */ - public String getBankAccount() { - return bankAccountNumber; - } - - /** - * @return phone number - */ - public String getPhoneNumber() { - return phoneNumber; - } - - @Override - public String toString() { - return "PlayerDetails{" + "emailAddress='" + emailAddress + '\'' - + ", bankAccountNumber='" + bankAccountNumber + '\'' - + ", phoneNumber='" + phoneNumber + '\'' + '}'; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((bankAccountNumber == null) ? 0 : bankAccountNumber.hashCode()); - result = prime * result + ((emailAddress == null) ? 0 : emailAddress.hashCode()); - result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PlayerDetails other = (PlayerDetails) obj; - if (bankAccountNumber == null) { - if (other.bankAccountNumber != null) { - return false; - } - } else if (!bankAccountNumber.equals(other.bankAccountNumber)) { - return false; - } - if (emailAddress == null) { - if (other.emailAddress != null) { - return false; - } - } else if (!emailAddress.equals(other.emailAddress)) { - return false; - } - if (phoneNumber == null) { - if (other.phoneNumber != null) { - return false; - } - } else if (!phoneNumber.equals(other.phoneNumber)) { - return false; - } - return true; - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java deleted file mode 100644 index fdc907305161..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java +++ /dev/null @@ -1,154 +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.hexagonal.eventlog; - -import com.iluwatar.hexagonal.domain.PlayerDetails; -import com.mongodb.MongoClient; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import org.bson.Document; - -/** - * Mongo based event log - */ -public class MongoEventLog implements LotteryEventLog { - - private static final String DEFAULT_DB = "lotteryDB"; - private static final String DEFAULT_EVENTS_COLLECTION = "events"; - - private MongoClient mongoClient; - private MongoDatabase database; - private MongoCollection eventsCollection; - - private StdOutEventLog stdOutEventLog = new StdOutEventLog(); - - /** - * Constructor - */ - public MongoEventLog() { - connect(); - } - - /** - * Constructor accepting parameters - */ - public MongoEventLog(String dbName, String eventsCollectionName) { - connect(dbName, eventsCollectionName); - } - - /** - * Connect to database with default parameters - */ - public void connect() { - connect(DEFAULT_DB, DEFAULT_EVENTS_COLLECTION); - } - - /** - * Connect to database with given parameters - */ - public void connect(String dbName, String eventsCollectionName) { - if (mongoClient != null) { - mongoClient.close(); - } - mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); - database = mongoClient.getDatabase(dbName); - eventsCollection = database.getCollection(eventsCollectionName); - } - - /** - * @return mongo client - */ - public MongoClient getMongoClient() { - return mongoClient; - } - - /** - * - * @return mongo database - */ - public MongoDatabase getMongoDatabase() { - return database; - } - - /** - * - * @return accounts collection - */ - public MongoCollection getEventsCollection() { - return eventsCollection; - } - - - @Override - public void ticketSubmitted(PlayerDetails details) { - Document document = new Document("email", details.getEmail()); - document.put("phone", details.getPhoneNumber()); - document.put("bank", details.getBankAccount()); - document.put("message", "Lottery ticket was submitted and bank account was charged for 3 credits."); - eventsCollection.insertOne(document); - stdOutEventLog.ticketSubmitted(details); - } - - @Override - public void ticketSubmitError(PlayerDetails details) { - Document document = new Document("email", details.getEmail()); - document.put("phone", details.getPhoneNumber()); - document.put("bank", details.getBankAccount()); - document.put("message", "Lottery ticket could not be submitted because lack of funds."); - eventsCollection.insertOne(document); - stdOutEventLog.ticketSubmitError(details); - } - - @Override - public void ticketDidNotWin(PlayerDetails details) { - Document document = new Document("email", details.getEmail()); - document.put("phone", details.getPhoneNumber()); - document.put("bank", details.getBankAccount()); - document.put("message", "Lottery ticket was checked and unfortunately did not win this time."); - eventsCollection.insertOne(document); - stdOutEventLog.ticketDidNotWin(details); - } - - @Override - public void ticketWon(PlayerDetails details, int prizeAmount) { - Document document = new Document("email", details.getEmail()); - document.put("phone", details.getPhoneNumber()); - document.put("bank", details.getBankAccount()); - document.put("message", String.format("Lottery ticket won! The bank account was deposited with %d credits.", - prizeAmount)); - eventsCollection.insertOne(document); - stdOutEventLog.ticketWon(details, prizeAmount); - } - - @Override - public void prizeError(PlayerDetails details, int prizeAmount) { - Document document = new Document("email", details.getEmail()); - document.put("phone", details.getPhoneNumber()); - document.put("bank", details.getBankAccount()); - document.put("message", String.format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.", - prizeAmount)); - eventsCollection.insertOne(document); - stdOutEventLog.prizeError(details, prizeAmount); - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java deleted file mode 100644 index 6d5af3280b21..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java +++ /dev/null @@ -1,64 +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.hexagonal.eventlog; - -import com.iluwatar.hexagonal.domain.PlayerDetails; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Standard output event log - */ -public class StdOutEventLog implements LotteryEventLog { - - private static final Logger LOGGER = LoggerFactory.getLogger(StdOutEventLog.class); - - @Override - public void ticketSubmitted(PlayerDetails details) { - LOGGER.info("Lottery ticket for {} was submitted. Bank account {} was charged for 3 credits.", - details.getEmail(), details.getBankAccount()); - } - - @Override - public void ticketDidNotWin(PlayerDetails details) { - LOGGER.info("Lottery ticket for {} was checked and unfortunately did not win this time.", details.getEmail()); - } - - @Override - public void ticketWon(PlayerDetails details, int prizeAmount) { - LOGGER.info("Lottery ticket for {} has won! The bank account {} was deposited with {} credits.", - details.getEmail(), details.getBankAccount(), prizeAmount); - } - - @Override - public void prizeError(PlayerDetails details, int prizeAmount) { - LOGGER.error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of {} failed.", - details.getEmail(), prizeAmount); - } - - @Override - public void ticketSubmitError(PlayerDetails details) { - LOGGER.error("Lottery ticket for {} could not be submitted because the credit transfer of 3 credits failed.", - details.getEmail()); - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java deleted file mode 100644 index f8de9b5518fe..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java +++ /dev/null @@ -1,58 +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.hexagonal.mongo; - -import java.io.FileInputStream; -import java.util.Properties; - -/** - * Mongo connection properties loader - */ -public class MongoConnectionPropertiesLoader { - - private static final String DEFAULT_HOST = "localhost"; - private static final int DEFAULT_PORT = 27017; - - /** - * Try to load connection properties from file. - * Fall back to default connection properties. - */ - public static void load() { - String host = DEFAULT_HOST; - int port = DEFAULT_PORT; - String path = System.getProperty("hexagonal.properties.path"); - Properties properties = new Properties(); - if (path != null) { - try (FileInputStream fin = new FileInputStream(path)) { - properties.load(fin); - host = properties.getProperty("mongo-host"); - port = Integer.parseInt(properties.getProperty("mongo-port")); - } catch (Exception e) { - // error occurred, use default properties - e.printStackTrace(); - } - } - System.setProperty("mongo-host", host); - System.setProperty("mongo-port", String.format("%d", port)); - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java deleted file mode 100644 index 23d409ff4ba2..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java +++ /dev/null @@ -1,109 +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.hexagonal.sampledata; - -import com.iluwatar.hexagonal.banking.InMemoryBank; -import com.iluwatar.hexagonal.domain.LotteryConstants; -import com.iluwatar.hexagonal.domain.LotteryNumbers; -import com.iluwatar.hexagonal.domain.LotteryService; -import com.iluwatar.hexagonal.domain.LotteryTicket; -import com.iluwatar.hexagonal.domain.LotteryTicketId; -import com.iluwatar.hexagonal.domain.PlayerDetails; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -/** - * Utilities for creating sample lottery tickets - */ -public class SampleData { - - private static final List PLAYERS; - - static { - PLAYERS = new ArrayList<>(); - PLAYERS.add(new PlayerDetails("john@google.com", "312-342", "+3242434242")); - PLAYERS.add(new PlayerDetails("mary@google.com", "234-987", "+23452346")); - PLAYERS.add(new PlayerDetails("steve@google.com", "833-836", "+63457543")); - PLAYERS.add(new PlayerDetails("wayne@google.com", "319-826", "+24626")); - PLAYERS.add(new PlayerDetails("johnie@google.com", "983-322", "+3635635")); - PLAYERS.add(new PlayerDetails("andy@google.com", "934-734", "+0898245")); - PLAYERS.add(new PlayerDetails("richard@google.com", "536-738", "+09845325")); - PLAYERS.add(new PlayerDetails("kevin@google.com", "453-936", "+2423532")); - PLAYERS.add(new PlayerDetails("arnold@google.com", "114-988", "+5646346524")); - PLAYERS.add(new PlayerDetails("ian@google.com", "663-765", "+928394235")); - PLAYERS.add(new PlayerDetails("robin@google.com", "334-763", "+35448")); - PLAYERS.add(new PlayerDetails("ted@google.com", "735-964", "+98752345")); - PLAYERS.add(new PlayerDetails("larry@google.com", "734-853", "+043842423")); - PLAYERS.add(new PlayerDetails("calvin@google.com", "334-746", "+73294135")); - PLAYERS.add(new PlayerDetails("jacob@google.com", "444-766", "+358042354")); - PLAYERS.add(new PlayerDetails("edwin@google.com", "895-345", "+9752435")); - PLAYERS.add(new PlayerDetails("mary@google.com", "760-009", "+34203542")); - PLAYERS.add(new PlayerDetails("lolita@google.com", "425-907", "+9872342")); - PLAYERS.add(new PlayerDetails("bruno@google.com", "023-638", "+673824122")); - PLAYERS.add(new PlayerDetails("peter@google.com", "335-886", "+5432503945")); - PLAYERS.add(new PlayerDetails("warren@google.com", "225-946", "+9872341324")); - PLAYERS.add(new PlayerDetails("monica@google.com", "265-748", "+134124")); - PLAYERS.add(new PlayerDetails("ollie@google.com", "190-045", "+34453452")); - PLAYERS.add(new PlayerDetails("yngwie@google.com", "241-465", "+9897641231")); - PLAYERS.add(new PlayerDetails("lars@google.com", "746-936", "+42345298345")); - PLAYERS.add(new PlayerDetails("bobbie@google.com", "946-384", "+79831742")); - PLAYERS.add(new PlayerDetails("tyron@google.com", "310-992", "+0498837412")); - PLAYERS.add(new PlayerDetails("tyrell@google.com", "032-045", "+67834134")); - PLAYERS.add(new PlayerDetails("nadja@google.com", "000-346", "+498723")); - PLAYERS.add(new PlayerDetails("wendy@google.com", "994-989", "+987324454")); - PLAYERS.add(new PlayerDetails("luke@google.com", "546-634", "+987642435")); - PLAYERS.add(new PlayerDetails("bjorn@google.com", "342-874", "+7834325")); - PLAYERS.add(new PlayerDetails("lisa@google.com", "024-653", "+980742154")); - PLAYERS.add(new PlayerDetails("anton@google.com", "834-935", "+876423145")); - PLAYERS.add(new PlayerDetails("bruce@google.com", "284-936", "+09843212345")); - PLAYERS.add(new PlayerDetails("ray@google.com", "843-073", "+678324123")); - PLAYERS.add(new PlayerDetails("ron@google.com", "637-738", "+09842354")); - PLAYERS.add(new PlayerDetails("xavier@google.com", "143-947", "+375245")); - PLAYERS.add(new PlayerDetails("harriet@google.com", "842-404", "+131243252")); - InMemoryBank wireTransfers = new InMemoryBank(); - Random random = new Random(); - for (int i = 0; i < PLAYERS.size(); i++) { - wireTransfers.setFunds(PLAYERS.get(i).getBankAccount(), - random.nextInt(LotteryConstants.PLAYER_MAX_SALDO)); - } - } - - /** - * Inserts lottery tickets into the database based on the sample data - */ - public static void submitTickets(LotteryService lotteryService, int numTickets) { - for (int i = 0; i < numTickets; i++) { - LotteryTicket ticket = new LotteryTicket(new LotteryTicketId(), - getRandomPlayerDetails(), LotteryNumbers.createRandom()); - lotteryService.submitTicket(ticket); - } - } - - private static PlayerDetails getRandomPlayerDetails() { - Random random = new Random(); - int idx = random.nextInt(PLAYERS.size()); - return PLAYERS.get(idx); - } -} diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java deleted file mode 100644 index f7f7b274ded6..000000000000 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java +++ /dev/null @@ -1,164 +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.hexagonal.service; - -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.iluwatar.hexagonal.banking.WireTransfers; -import com.iluwatar.hexagonal.domain.LotteryNumbers; -import com.iluwatar.hexagonal.domain.LotteryService; -import com.iluwatar.hexagonal.domain.LotteryTicket; -import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult; -import com.iluwatar.hexagonal.domain.LotteryTicketId; -import com.iluwatar.hexagonal.domain.PlayerDetails; -import com.iluwatar.hexagonal.module.LotteryModule; -import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashSet; -import java.util.Optional; -import java.util.Scanner; -import java.util.Set; - -/** - * Console interface for lottery players - */ -public class ConsoleLottery { - - private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleLottery.class); - - /** - * Program entry point - */ - public static void main(String[] args) { - MongoConnectionPropertiesLoader.load(); - Injector injector = Guice.createInjector(new LotteryModule()); - LotteryService service = injector.getInstance(LotteryService.class); - WireTransfers bank = injector.getInstance(WireTransfers.class); - try (final Scanner scanner = new Scanner(System.in)) { - boolean exit = false; - while (!exit) { - printMainMenu(); - String cmd = readString(scanner); - if ("1".equals(cmd)) { - queryLotteryAccountFunds(bank, scanner); - } else if ("2".equals(cmd)) { - addFundsToLotteryAccount(bank, scanner); - } else if ("3".equals(cmd)) { - submitTicket(service, scanner); - } else if ("4".equals(cmd)) { - checkTicket(service, scanner); - } else if ("5".equals(cmd)) { - exit = true; - } else { - LOGGER.info("Unknown command"); - } - } - } - } - - private static void checkTicket(LotteryService service, Scanner scanner) { - LOGGER.info("What is the ID of the lottery ticket?"); - String id = readString(scanner); - LOGGER.info("Give the 4 comma separated winning numbers?"); - String numbers = readString(scanner); - try { - String[] parts = numbers.split(","); - Set winningNumbers = new HashSet<>(); - for (int i = 0; i < 4; i++) { - winningNumbers.add(Integer.parseInt(parts[i])); - } - LotteryTicketCheckResult result = service.checkTicketForPrize( - new LotteryTicketId(Integer.parseInt(id)), LotteryNumbers.create(winningNumbers)); - if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { - LOGGER.info("Congratulations! The lottery ticket has won!"); - } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { - LOGGER.info("Unfortunately the lottery ticket did not win."); - } else { - LOGGER.info("Such lottery ticket has not been submitted."); - } - } catch (Exception e) { - LOGGER.info("Failed checking the lottery ticket - please try again."); - } - } - - private static void submitTicket(LotteryService service, Scanner scanner) { - LOGGER.info("What is your email address?"); - String email = readString(scanner); - LOGGER.info("What is your bank account number?"); - String account = readString(scanner); - LOGGER.info("What is your phone number?"); - String phone = readString(scanner); - PlayerDetails details = new PlayerDetails(email, account, phone); - LOGGER.info("Give 4 comma separated lottery numbers?"); - String numbers = readString(scanner); - try { - String[] parts = numbers.split(","); - Set chosen = new HashSet<>(); - for (int i = 0; i < 4; i++) { - chosen.add(Integer.parseInt(parts[i])); - } - LotteryNumbers lotteryNumbers = LotteryNumbers.create(chosen); - LotteryTicket lotteryTicket = new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers); - Optional id = service.submitTicket(lotteryTicket); - if (id.isPresent()) { - LOGGER.info("Submitted lottery ticket with id: {}", id.get()); - } else { - LOGGER.info("Failed submitting lottery ticket - please try again."); - } - } catch (Exception e) { - LOGGER.info("Failed submitting lottery ticket - please try again."); - } - } - - private static void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner) { - LOGGER.info("What is the account number?"); - String account = readString(scanner); - LOGGER.info("How many credits do you want to deposit?"); - String amount = readString(scanner); - bank.setFunds(account, Integer.parseInt(amount)); - LOGGER.info("The account {} now has {} credits.", account, bank.getFunds(account)); - } - - private static void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner) { - LOGGER.info("What is the account number?"); - String account = readString(scanner); - LOGGER.info("The account {} has {} credits.", account, bank.getFunds(account)); - } - - private static void printMainMenu() { - LOGGER.info(""); - LOGGER.info("### Lottery Service Console ###"); - LOGGER.info("(1) Query lottery account funds"); - LOGGER.info("(2) Add funds to lottery account"); - LOGGER.info("(3) Submit ticket"); - LOGGER.info("(4) Check ticket"); - LOGGER.info("(5) Exit"); - } - - private static String readString(Scanner scanner) { - System.out.print("> "); - return scanner.next(); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java deleted file mode 100644 index d034ee865455..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java +++ /dev/null @@ -1,37 +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.hexagonal; - -import org.junit.jupiter.api.Test; - -/** - * Unit test for simple App. - */ -public class AppTest { - - @Test - public void testApp() { - String[] args = {}; - App.main(args); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java deleted file mode 100644 index d3589b0c7b5e..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java +++ /dev/null @@ -1,69 +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.hexagonal.banking; - -import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; -import com.mongodb.MongoClient; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Tests for Mongo banking adapter - */ -@Disabled -public class MongoBankTest { - - private static final String TEST_DB = "lotteryDBTest"; - private static final String TEST_ACCOUNTS_COLLECTION = "testAccounts"; - - private MongoBank mongoBank; - - @BeforeEach - public void init() { - MongoConnectionPropertiesLoader.load(); - MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); - mongoClient.dropDatabase(TEST_DB); - mongoClient.close(); - mongoBank = new MongoBank(TEST_DB, TEST_ACCOUNTS_COLLECTION); - } - - @Test - public void testSetup() { - assertEquals(0, mongoBank.getAccountsCollection().count()); - } - - @Test - public void testFundTransfers() { - assertEquals(0, mongoBank.getFunds("000-000")); - mongoBank.setFunds("000-000", 10); - assertEquals(10, mongoBank.getFunds("000-000")); - assertEquals(0, mongoBank.getFunds("111-111")); - mongoBank.transferFunds(9, "000-000", "111-111"); - assertEquals(1, mongoBank.getFunds("000-000")); - assertEquals(9, mongoBank.getFunds("111-111")); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java deleted file mode 100644 index f14caa94f238..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java +++ /dev/null @@ -1,61 +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.hexagonal.database; - -import java.util.Optional; - -import com.iluwatar.hexagonal.domain.LotteryTicket; -import com.iluwatar.hexagonal.domain.LotteryTicketId; -import com.iluwatar.hexagonal.test.LotteryTestUtils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * - * Tests for {@link LotteryTicketRepository} - * - */ -public class InMemoryTicketRepositoryTest { - - private final LotteryTicketRepository repository = new InMemoryTicketRepository(); - - @BeforeEach - public void clear() { - repository.deleteAll(); - } - - @Test - public void testCrudOperations() { - LotteryTicketRepository repository = new InMemoryTicketRepository(); - assertEquals(repository.findAll().size(), 0); - LotteryTicket ticket = LotteryTestUtils.createLotteryTicket(); - Optional id = repository.save(ticket); - assertTrue(id.isPresent()); - assertEquals(repository.findAll().size(), 1); - Optional optionalTicket = repository.findById(id.get()); - assertTrue(optionalTicket.isPresent()); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java deleted file mode 100644 index 08dcc51c3c93..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java +++ /dev/null @@ -1,97 +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.hexagonal.database; - -import com.iluwatar.hexagonal.domain.LotteryNumbers; -import com.iluwatar.hexagonal.domain.LotteryTicket; -import com.iluwatar.hexagonal.domain.LotteryTicketId; -import com.iluwatar.hexagonal.domain.PlayerDetails; -import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; -import com.mongodb.MongoClient; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests for Mongo based ticket repository - */ -@Disabled -public class MongoTicketRepositoryTest { - - private static final String TEST_DB = "lotteryTestDB"; - private static final String TEST_TICKETS_COLLECTION = "lotteryTestTickets"; - private static final String TEST_COUNTERS_COLLECTION = "testCounters"; - - private MongoTicketRepository repository; - - @BeforeEach - public void init() { - MongoConnectionPropertiesLoader.load(); - MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); - mongoClient.dropDatabase(TEST_DB); - mongoClient.close(); - repository = new MongoTicketRepository(TEST_DB, TEST_TICKETS_COLLECTION, - TEST_COUNTERS_COLLECTION); - } - - @Test - public void testSetup() { - assertTrue(repository.getCountersCollection().count() == 1); - assertTrue(repository.getTicketsCollection().count() == 0); - } - - @Test - public void testNextId() { - assertEquals(1, repository.getNextId()); - assertEquals(2, repository.getNextId()); - assertEquals(3, repository.getNextId()); - } - - @Test - public void testCrudOperations() { - // create new lottery ticket and save it - PlayerDetails details = new PlayerDetails("foo@bar.com", "123-123", "07001234"); - LotteryNumbers random = LotteryNumbers.createRandom(); - LotteryTicket original = new LotteryTicket(new LotteryTicketId(), details, random); - Optional saved = repository.save(original); - assertEquals(1, repository.getTicketsCollection().count()); - assertTrue(saved.isPresent()); - // fetch the saved lottery ticket from database and check its contents - Optional found = repository.findById(saved.get()); - assertTrue(found.isPresent()); - LotteryTicket ticket = found.get(); - assertEquals("foo@bar.com", ticket.getPlayerDetails().getEmail()); - assertEquals("123-123", ticket.getPlayerDetails().getBankAccount()); - assertEquals("07001234", ticket.getPlayerDetails().getPhoneNumber()); - assertEquals(original.getNumbers(), ticket.getNumbers()); - // clear the collection - repository.deleteAll(); - assertEquals(0, repository.getTicketsCollection().count()); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java deleted file mode 100644 index b823bc3c7a8b..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java +++ /dev/null @@ -1,79 +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.hexagonal.domain; - -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.HashSet; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * - * Unit tests for {@link LotteryNumbers} - * - */ -public class LotteryNumbersTest { - - @Test - public void testGivenNumbers() { - LotteryNumbers numbers = LotteryNumbers.create( - new HashSet<>(Arrays.asList(1, 2, 3, 4))); - assertEquals(numbers.getNumbers().size(), 4); - assertTrue(numbers.getNumbers().contains(1)); - assertTrue(numbers.getNumbers().contains(2)); - assertTrue(numbers.getNumbers().contains(3)); - assertTrue(numbers.getNumbers().contains(4)); - } - - @Test - public void testNumbersCantBeModified() { - LotteryNumbers numbers = LotteryNumbers.create( - new HashSet<>(Arrays.asList(1, 2, 3, 4))); - assertThrows(UnsupportedOperationException.class, () -> { - numbers.getNumbers().add(5); - }); - } - - @Test - public void testRandomNumbers() { - LotteryNumbers numbers = LotteryNumbers.createRandom(); - assertEquals(numbers.getNumbers().size(), LotteryNumbers.NUM_NUMBERS); - } - - @Test - public void testEquals() { - LotteryNumbers numbers1 = LotteryNumbers.create( - new HashSet<>(Arrays.asList(1, 2, 3, 4))); - LotteryNumbers numbers2 = LotteryNumbers.create( - new HashSet<>(Arrays.asList(1, 2, 3, 4))); - assertTrue(numbers1.equals(numbers2)); - LotteryNumbers numbers3 = LotteryNumbers.create( - new HashSet<>(Arrays.asList(11, 12, 13, 14))); - assertFalse(numbers1.equals(numbers3)); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java deleted file mode 100644 index 2290b7d49424..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java +++ /dev/null @@ -1,113 +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.hexagonal.domain; - -import com.google.inject.Guice; -import com.google.inject.Inject; -import com.google.inject.Injector; -import com.iluwatar.hexagonal.banking.WireTransfers; -import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; -import com.iluwatar.hexagonal.module.LotteryTestingModule; -import com.iluwatar.hexagonal.test.LotteryTestUtils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * - * Test the lottery system - * - */ -public class LotteryTest { - - private Injector injector; - @Inject - private LotteryAdministration administration; - @Inject - private LotteryService service; - @Inject - private WireTransfers wireTransfers; - - public LotteryTest() { - this.injector = Guice.createInjector(new LotteryTestingModule()); - } - - @BeforeEach - public void setup() { - injector.injectMembers(this); - // add funds to the test player's bank account - wireTransfers.setFunds("123-12312", 100); - } - - @Test - public void testLottery() { - // admin resets the lottery - administration.resetLottery(); - assertEquals(administration.getAllSubmittedTickets().size(), 0); - - // players submit the lottery tickets - Optional ticket1 = service.submitTicket(LotteryTestUtils.createLotteryTicket("cvt@bbb.com", - "123-12312", "+32425255", new HashSet<>(Arrays.asList(1, 2, 3, 4)))); - assertTrue(ticket1.isPresent()); - Optional ticket2 = service.submitTicket(LotteryTestUtils.createLotteryTicket("ant@bac.com", - "123-12312", "+32423455", new HashSet<>(Arrays.asList(11, 12, 13, 14)))); - assertTrue(ticket2.isPresent()); - Optional ticket3 = service.submitTicket(LotteryTestUtils.createLotteryTicket("arg@boo.com", - "123-12312", "+32421255", new HashSet<>(Arrays.asList(6, 8, 13, 19)))); - assertTrue(ticket3.isPresent()); - assertEquals(administration.getAllSubmittedTickets().size(), 3); - - // perform lottery - LotteryNumbers winningNumbers = administration.performLottery(); - - // cheat a bit for testing sake, use winning numbers to submit another ticket - Optional ticket4 = service.submitTicket(LotteryTestUtils.createLotteryTicket("lucky@orb.com", - "123-12312", "+12421255", winningNumbers.getNumbers())); - assertTrue(ticket4.isPresent()); - assertEquals(administration.getAllSubmittedTickets().size(), 4); - - // check winners - Map tickets = administration.getAllSubmittedTickets(); - for (LotteryTicketId id: tickets.keySet()) { - LotteryTicketCheckResult checkResult = service.checkTicketForPrize(id, winningNumbers); - assertTrue(checkResult.getResult() != CheckResult.TICKET_NOT_SUBMITTED); - if (checkResult.getResult().equals(CheckResult.WIN_PRIZE)) { - assertTrue(checkResult.getPrizeAmount() > 0); - } else if (checkResult.getResult().equals(CheckResult.WIN_PRIZE)) { - assertEquals(checkResult.getPrizeAmount(), 0); - } - } - - // check another ticket that has not been submitted - LotteryTicketCheckResult checkResult = service.checkTicketForPrize(new LotteryTicketId(), winningNumbers); - assertTrue(checkResult.getResult() == CheckResult.TICKET_NOT_SUBMITTED); - assertEquals(checkResult.getPrizeAmount(), 0); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java deleted file mode 100644 index 4ded94bc4d9a..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java +++ /dev/null @@ -1,46 +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.hexagonal.domain; - -import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -/** - * - * Unit tests for {@link LotteryTicketCheckResult} - * - */ -public class LotteryTicketCheckResultTest { - - @Test - public void testEquals() { - LotteryTicketCheckResult result1 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); - LotteryTicketCheckResult result2 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); - assertEquals(result1, result2); - LotteryTicketCheckResult result3 = new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 300000); - assertFalse(result1.equals(result3)); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java deleted file mode 100644 index 6bcaea4f035c..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java +++ /dev/null @@ -1,45 +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.hexagonal.domain; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests for lottery ticket id - */ -public class LotteryTicketIdTest { - - @Test - public void testEquals() { - LotteryTicketId ticketId1 = new LotteryTicketId(); - LotteryTicketId ticketId2 = new LotteryTicketId(); - LotteryTicketId ticketId3 = new LotteryTicketId(); - assertFalse(ticketId1.equals(ticketId2)); - assertFalse(ticketId2.equals(ticketId3)); - LotteryTicketId ticketId4 = new LotteryTicketId(ticketId1.getId()); - assertTrue(ticketId1.equals(ticketId4)); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java deleted file mode 100644 index 2c0332458ddb..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java +++ /dev/null @@ -1,52 +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.hexagonal.domain; - -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.HashSet; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -/** - * Test Lottery Tickets for equality - */ -public class LotteryTicketTest { - - @Test - public void testEquals() { - PlayerDetails details1 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); - LotteryNumbers numbers1 = LotteryNumbers.create(new HashSet(Arrays.asList(1, 2, 3, 4))); - LotteryTicket ticket1 = new LotteryTicket(new LotteryTicketId(), details1, numbers1); - PlayerDetails details2 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); - LotteryNumbers numbers2 = LotteryNumbers.create(new HashSet(Arrays.asList(1, 2, 3, 4))); - LotteryTicket ticket2 = new LotteryTicket(new LotteryTicketId(), details2, numbers2); - assertEquals(ticket1, ticket2); - PlayerDetails details3 = new PlayerDetails("elsa@foo.bar", "1223-121212", "+49332322"); - LotteryNumbers numbers3 = LotteryNumbers.create(new HashSet(Arrays.asList(1, 2, 3, 8))); - LotteryTicket ticket3 = new LotteryTicket(new LotteryTicketId(), details3, numbers3); - assertFalse(ticket1.equals(ticket3)); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java deleted file mode 100644 index 4d49fcae51ea..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java +++ /dev/null @@ -1,45 +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.hexagonal.domain; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -/** - * - * Unit tests for {@link PlayerDetails} - * - */ -public class PlayerDetailsTest { - - @Test - public void testEquals() { - PlayerDetails details1 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); - PlayerDetails details2 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); - assertEquals(details1, details2); - PlayerDetails details3 = new PlayerDetails("john@foo.bar", "16412-123439", "+34323432"); - assertFalse(details1.equals(details3)); - } -} diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java deleted file mode 100644 index 06942a0329c6..000000000000 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java +++ /dev/null @@ -1,84 +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.hexagonal.eventlog; - -import com.iluwatar.hexagonal.domain.PlayerDetails; -import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; -import com.mongodb.MongoClient; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Tests for Mongo event log - */ -@Disabled -public class MongoEventLogTest { - - private static final String TEST_DB = "lotteryDBTest"; - private static final String TEST_EVENTS_COLLECTION = "testEvents"; - - private MongoEventLog mongoEventLog; - - @BeforeEach - public void init() { - MongoConnectionPropertiesLoader.load(); - MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); - mongoClient.dropDatabase(TEST_DB); - mongoClient.close(); - mongoEventLog = new MongoEventLog(TEST_DB, TEST_EVENTS_COLLECTION); - } - - @Test - public void testSetup() { - assertEquals(0, mongoEventLog.getEventsCollection().count()); - } - - @Test - public void testFundTransfers() { - PlayerDetails playerDetails = new PlayerDetails("john@wayne.com", "000-000", "03432534543"); - mongoEventLog.prizeError(playerDetails, 1000); - assertEquals(1, mongoEventLog.getEventsCollection().count()); - mongoEventLog.prizeError(playerDetails, 1000); - assertEquals(2, mongoEventLog.getEventsCollection().count()); - mongoEventLog.ticketDidNotWin(playerDetails); - assertEquals(3, mongoEventLog.getEventsCollection().count()); - mongoEventLog.ticketDidNotWin(playerDetails); - assertEquals(4, mongoEventLog.getEventsCollection().count()); - mongoEventLog.ticketSubmitError(playerDetails); - assertEquals(5, mongoEventLog.getEventsCollection().count()); - mongoEventLog.ticketSubmitError(playerDetails); - assertEquals(6, mongoEventLog.getEventsCollection().count()); - mongoEventLog.ticketSubmitted(playerDetails); - assertEquals(7, mongoEventLog.getEventsCollection().count()); - mongoEventLog.ticketSubmitted(playerDetails); - assertEquals(8, mongoEventLog.getEventsCollection().count()); - mongoEventLog.ticketWon(playerDetails, 1000); - assertEquals(9, mongoEventLog.getEventsCollection().count()); - mongoEventLog.ticketWon(playerDetails, 1000); - assertEquals(10, mongoEventLog.getEventsCollection().count()); - } -} diff --git a/identity-map/README.md b/identity-map/README.md new file mode 100644 index 000000000000..a63e11423fa2 --- /dev/null +++ b/identity-map/README.md @@ -0,0 +1,221 @@ +--- +title: "Identity Map Pattern in Java: Managing Object Identity for Efficiency" +shortTitle: Identity Map +description: "Learn about the Identity Map pattern in Java. This design pattern prevents duplicate objects in memory, improving performance and consistency in your applications. Explore implementation examples, benefits, and best practices." +category: Behavioral +language: en +tag: + - Data access + - Decoupling + - Enterprise patterns + - Object mapping + - Persistence + - Performance +--- + +## Intent of Identity Map Design Pattern + +The Identity Map design pattern in Java aims to ensure that each object gets loaded only once by keeping every loaded object in a map, enhancing database performance and memory management. + +## Detailed Explanation of Identity Map Pattern with Real-World Examples + +Real-world example + +> Imagine you are organizing a conference and have a registration desk where every attendee must check in. This scenario illustrates the Identity Map pattern in Java which prevents duplicate objects. To avoid unnecessary delays and confusion, each attendee's details are entered into a computer system the first time they check in. If the same attendee comes to the desk again, the system quickly retrieves their details without requiring them to re-submit the same information. This ensures each attendee's information is handled efficiently and consistently, similar to how the Identity Map pattern ensures that an object is loaded only once and reused throughout the application. + +In plain words + +> The Identity Map design pattern ensures that each unique object is loaded only once and reused from a central registry, preventing duplicate objects in an application's memory. + +Wikipedia says + +> In the design of DBMS, the identity map pattern is a database access design pattern used to improve performance by providing a context-specific, in-memory cache to prevent duplicate retrieval of the same object data from the database. + +Sequence diagram + +![Identity Map sequence diagram](./etc/identity-map-sequence-diagram.png) + +## Programmatic Example of Identity Map Pattern in Java + +For the purpose of this demonstration in Java programming, assume we have already created a database instance, showcasing the Identity Map pattern to avoid duplicate objects in memory. + +Let's first look at the implementation of `Person` entity, and it's fields: + +```java +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@Getter +@Setter +@AllArgsConstructor +public final class Person implements Serializable { + + private static final long serialVersionUID = 1L; + + @EqualsAndHashCode.Include + private int personNationalId; + private String name; + private long phoneNum; + + @Override + public String toString() { + return "Person ID is : " + personNationalId + " ; Person Name is : " + name + " ; Phone Number is :" + phoneNum; + } +} + +``` + +The following is the implementation of the `PersonFinder` which is the entity that the user will utilize in order to search for a record in our database. It has the relevant DB attached to it. It also maintains an `IdentityMap` to store the recently read records. + +```java +@Slf4j +@Getter +@Setter +public class PersonFinder { + private static final long serialVersionUID = 1L; + // Access to the Identity Map + private IdentityMap identityMap = new IdentityMap(); + private PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + + public Person getPerson(int key) { + // Try to find person in the identity map + Person person = this.identityMap.getPerson(key); + if (person != null) { + LOGGER.info("Person found in the Map"); + return person; + } else { + // Try to find person in the database + person = this.db.find(key); + if (person != null) { + this.identityMap.addPerson(person); + LOGGER.info("Person found in DB."); + return person; + } + LOGGER.info("Person with this ID does not exist."); + return null; + } + } +} + +``` + +The identity map field in the above class is simply an abstraction of a hashMap with **personNationalId** as the keys and the corresponding person object as the value. Here is its implementation: + +```java +@Slf4j +@Getter +public class IdentityMap { + private Map personMap = new HashMap<>(); + + public void addPerson(Person person) { + if (!personMap.containsKey(person.getPersonNationalId())) { + personMap.put(person.getPersonNationalId(), person); + } else { // Ensure that addPerson does not update a record. This situation will never arise in our implementation. Added only for testing purposes. + LOGGER.info("Key already in Map"); + } + } + + public Person getPerson(int id) { + Person person = personMap.get(id); + if (person == null) { + LOGGER.info("ID not in Map."); + } + return person; + } + + public int size() { + if (personMap == null) { + return 0; + } + return personMap.size(); + } +} +``` + +Now, let's see how the identity map works in our `App`'s `main` function. + +```java +public static void main(String[] args) { + + // Dummy Persons + Person person1 = new Person(1, "John", 27304159); + Person person2 = new Person(2, "Thomas", 42273631); + Person person3 = new Person(3, "Arthur", 27489171); + Person person4 = new Person(4, "Finn", 20499078); + Person person5 = new Person(5, "Michael", 40599078); + + // Init database + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + db.insert(person1); + db.insert(person2); + db.insert(person3); + db.insert(person4); + db.insert(person5); + + // Init a personFinder + PersonFinder finder = new PersonFinder(); + finder.setDb(db); + + // Find persons in DataBase not the map. + LOGGER.info(finder.getPerson(2).toString()); + LOGGER.info(finder.getPerson(4).toString()); + LOGGER.info(finder.getPerson(5).toString()); + // Find the person in the map. + LOGGER.info(finder.getPerson(2).toString()); +} +``` + +Running the example produces the following console output: + +``` +11:19:43.775 [main] INFO com.iluwatar.identitymap.IdentityMap -- ID not in Map. +11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonDbSimulatorImplementation -- Person ID is : 2 ; Person Name is : Thomas ; Phone Number is :42273631 +11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonFinder -- Person found in DB. +11:19:43.780 [main] INFO com.iluwatar.identitymap.App -- Person ID is : 2 ; Person Name is : Thomas ; Phone Number is :42273631 +11:19:43.780 [main] INFO com.iluwatar.identitymap.IdentityMap -- ID not in Map. +11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonDbSimulatorImplementation -- Person ID is : 4 ; Person Name is : Finn ; Phone Number is :20499078 +11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonFinder -- Person found in DB. +11:19:43.780 [main] INFO com.iluwatar.identitymap.App -- Person ID is : 4 ; Person Name is : Finn ; Phone Number is :20499078 +11:19:43.780 [main] INFO com.iluwatar.identitymap.IdentityMap -- ID not in Map. +11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonDbSimulatorImplementation -- Person ID is : 5 ; Person Name is : Michael ; Phone Number is :40599078 +11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonFinder -- Person found in DB. +11:19:43.780 [main] INFO com.iluwatar.identitymap.App -- Person ID is : 5 ; Person Name is : Michael ; Phone Number is :40599078 +11:19:43.780 [main] INFO com.iluwatar.identitymap.IdentityMap -- Person ID is : 2 ; Person Name is : Thomas ; Phone Number is :42273631 +11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonFinder -- Person found in the Map +11:19:43.780 [main] INFO com.iluwatar.identitymap.App -- Person ID is : 2 ; Person Name is : Thomas ; Phone Number is :42273631 +``` + +## When to Use the Identity Map Pattern in Java + +The Identity Map design pattern is used in Java applications where multiple accesses to the same data occur within a single session or transaction, ensuring efficient object mapping and consistency. + +## Identity Map Pattern Java Tutorials + +* [Identity Map Pattern (Source Code Examples)](https://www.sourcecodeexamples.net/2018/04/identity-map-pattern.html) + +## Real-World Applications of Identity Map Pattern in Java + +* ORM (Object-Relational Mapping) frameworks in Java often implement Identity Maps to handle database interactions more efficiently, demonstrating the pattern’s importance in Java design patterns. +* Enterprise applications to maintain consistent data states across different business processes. + +## Benefits and Trade-offs of Identity Map Pattern + +Benefits: + +* Reduces memory usage by ensuring that only one copy of each object resides in memory. +* Prevents inconsistencies during updates, as all parts of the application refer to the same instance. +* Improves performance by avoiding repeated database reads for the same data. + +Trade-offs: + +* Increases complexity in object management and persistence logic. +* Can lead to stale data if not managed correctly, especially in concurrent environments. + +## Related Java Design Patterns + +* [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): Separates persistence logic from domain logic. Identity Map can be used by a Data Mapper to ensure that each object is loaded only once, enhancing performance and data consistency. +* [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Coordinates the actions of multiple objects by keeping track of changes and handling transactional consistency. Identity Map is used within the Unit of Work to track the objects being affected by a transaction. + +## References and Credits + +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) +* [Java Persistence with Hibernate](https://amzn.to/4aUfyhd) +* [Pro Java EE Spring Patterns: Best Practices and Design Strategies Implementing Java EE Patterns with the Spring Framework](https://amzn.to/49YQN24) diff --git a/identity-map/etc/IdentityMap.png b/identity-map/etc/IdentityMap.png new file mode 100644 index 000000000000..1bac10ebf294 Binary files /dev/null and b/identity-map/etc/IdentityMap.png differ diff --git a/identity-map/etc/identity-map-sequence-diagram.png b/identity-map/etc/identity-map-sequence-diagram.png new file mode 100644 index 000000000000..41011f30d266 Binary files /dev/null and b/identity-map/etc/identity-map-sequence-diagram.png differ diff --git a/identity-map/etc/identity-map.urm.puml b/identity-map/etc/identity-map.urm.puml new file mode 100644 index 000000000000..cdbdbd8f23a8 --- /dev/null +++ b/identity-map/etc/identity-map.urm.puml @@ -0,0 +1,67 @@ +@startuml +package com.iluwatar.identitymap { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class IdentityMap { + - LOGGER : Logger {static} + - personMap : Map + + IdentityMap() + + addPerson(person : Person) + + getPerson(id : int) : Person + + getPersonMap() : Map + + size() : int + } + class Person { + - name : String + - personNationalId : int + - phoneNum : long + - serialVersionUID : long {static} + + Person(personNationalId : int, name : String, phoneNum : long) + + equals(o : Object) : boolean + + getName() : String + + getPersonNationalId() : int + + getPhoneNum() : long + + hashCode() : int + + setName(name : String) + + setPersonNationalId(personNationalId : int) + + setPhoneNum(phoneNum : long) + + toString() : String + } + interface PersonDbSimulator { + + delete(int) {abstract} + + find(int) : Person {abstract} + + insert(Person) {abstract} + + update(Person) {abstract} + } + class PersonDbSimulatorImplementation { + ~ ID_STR : String {static} + - LOGGER : Logger {static} + ~ NOT_IN_DATA_BASE : String {static} + - personList : List + + PersonDbSimulatorImplementation() + + delete(id : int) + + find(personNationalID : int) : Person + + insert(person : Person) + + size() : int + + update(person : Person) + } + class PersonFinder { + - LOGGER : Logger {static} + - db : PersonDbSimulatorImplementation + - identityMap : IdentityMap + + PersonFinder() + + getDB() : PersonDbSimulatorImplementation + + getIdentityMap() : IdentityMap + + getPerson(key : int) : Person + + setDb(db : PersonDbSimulatorImplementation) + + setIdentityMap(identityMap : IdentityMap) + } +} +PersonFinder --> "-db" PersonDbSimulatorImplementation +PersonFinder --> "-identityMap" IdentityMap +PersonDbSimulatorImplementation --> "-personList" Person +PersonDbSimulatorImplementation ..|> PersonDbSimulator +@enduml \ No newline at end of file diff --git a/identity-map/pom.xml b/identity-map/pom.xml new file mode 100644 index 000000000000..cf151c1ffb0a --- /dev/null +++ b/identity-map/pom.xml @@ -0,0 +1,72 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + identity-map + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.identitymap.App + + + + + + + + + diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/App.java b/identity-map/src/main/java/com/iluwatar/identitymap/App.java new file mode 100644 index 000000000000..e3538f4b3f83 --- /dev/null +++ b/identity-map/src/main/java/com/iluwatar/identitymap/App.java @@ -0,0 +1,72 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +import lombok.extern.slf4j.Slf4j; + +/** + * The basic idea behind the Identity Map is to have a series of maps containing objects that have + * been pulled from the database. The below example demonstrates the identity map pattern by + * creating a sample DB. Since only 1 DB has been created we only have 1 map corresponding to it for + * the purpose of this demo. When you load an object from the database, you first check the map. If + * there’s an object in it that corresponds to the one you’re loading, you return it. If not, you go + * to the database, putting the objects on the map for future reference as you load them. + */ +@Slf4j +public class App { + /** + * Program entry point. + * + * @param args command line args. + */ + public static void main(String[] args) { + + // Dummy Persons + Person person1 = new Person(1, "John", 27304159); + Person person2 = new Person(2, "Thomas", 42273631); + Person person3 = new Person(3, "Arthur", 27489171); + Person person4 = new Person(4, "Finn", 20499078); + Person person5 = new Person(5, "Michael", 40599078); + + // Init database + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + db.insert(person1); + db.insert(person2); + db.insert(person3); + db.insert(person4); + db.insert(person5); + + // Init a personFinder + PersonFinder finder = new PersonFinder(); + finder.setDb(db); + + // Find persons in DataBase not the map. + LOGGER.info(finder.getPerson(2).toString()); + LOGGER.info(finder.getPerson(4).toString()); + LOGGER.info(finder.getPerson(5).toString()); + // Find the person in the map. + LOGGER.info(finder.getPerson(2).toString()); + } +} diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/IdNotFoundException.java b/identity-map/src/main/java/com/iluwatar/identitymap/IdNotFoundException.java new file mode 100644 index 000000000000..9a02108545a1 --- /dev/null +++ b/identity-map/src/main/java/com/iluwatar/identitymap/IdNotFoundException.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +/** Using Runtime Exception to control the flow in case Person Id doesn't exist. */ +public class IdNotFoundException extends RuntimeException { + public IdNotFoundException(final String message) { + super(message); + } +} diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/IdentityMap.java b/identity-map/src/main/java/com/iluwatar/identitymap/IdentityMap.java new file mode 100644 index 000000000000..7543cfb0bc61 --- /dev/null +++ b/identity-map/src/main/java/com/iluwatar/identitymap/IdentityMap.java @@ -0,0 +1,73 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +import java.util.HashMap; +import java.util.Map; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +/** + * This class stores the map into which we will be caching records after loading them from a + * DataBase. Stores the records as a Hash Map with the personNationalIDs as keys. + */ +@Slf4j +@Getter +public class IdentityMap { + private Map personMap = new HashMap<>(); + + /** Add person to the map. */ + public void addPerson(Person person) { + if (!personMap.containsKey(person.getPersonNationalId())) { + personMap.put(person.getPersonNationalId(), person); + } else { // Ensure that addPerson does not update a record. This situation will never arise in + // our implementation. Added only for testing purposes. + LOGGER.info("Key already in Map"); + } + } + + /** + * Get Person with given id. + * + * @param id : personNationalId as requested by user. + */ + public Person getPerson(int id) { + Person person = personMap.get(id); + if (person == null) { + LOGGER.info("ID not in Map."); + return null; + } + LOGGER.info(person.toString()); + return person; + } + + /** Get the size of the map. */ + public int size() { + if (personMap == null) { + return 0; + } + return personMap.size(); + } +} diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/Person.java b/identity-map/src/main/java/com/iluwatar/identitymap/Person.java new file mode 100644 index 000000000000..bc14bff50451 --- /dev/null +++ b/identity-map/src/main/java/com/iluwatar/identitymap/Person.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +import java.io.Serial; +import java.io.Serializable; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +/** Person definition. */ +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@Getter +@Setter +@AllArgsConstructor +public final class Person implements Serializable { + + @Serial private static final long serialVersionUID = 1L; + + @EqualsAndHashCode.Include private int personNationalId; + private String name; + private long phoneNum; + + @Override + public String toString() { + + return "Person ID is : " + + personNationalId + + " ; Person Name is : " + + name + + " ; Phone Number is :" + + phoneNum; + } +} diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulator.java b/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulator.java new file mode 100644 index 000000000000..8a2d7481ddd2 --- /dev/null +++ b/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulator.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +/** Simulator interface for Person DB. */ +public interface PersonDbSimulator { + Person find(int personNationalId); + + void insert(Person person); + + void update(Person person); + + void delete(int personNationalId); +} diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulatorImplementation.java b/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulatorImplementation.java new file mode 100644 index 000000000000..e6c4be3eb89b --- /dev/null +++ b/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulatorImplementation.java @@ -0,0 +1,111 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import lombok.extern.slf4j.Slf4j; + +/** + * This is a sample database implementation. The database is in the form of an arraylist which + * stores records of different persons. The personNationalId acts as the primary key for a record. + * Operations : -> find (look for object with a particular ID) -> insert (insert record for a new + * person into the database) -> update (update the record of a person). To do this, create a new + * person instance with the same ID as the record you want to update. Then call this method with + * that person as an argument. -> delete (delete the record for a particular ID) + */ +@Slf4j +public class PersonDbSimulatorImplementation implements PersonDbSimulator { + + // This simulates a table in the database. To extend logic to multiple tables just add more lists + // to the implementation. + private List personList = new ArrayList<>(); + static final String NOT_IN_DATA_BASE = " not in DataBase"; + static final String ID_STR = "ID : "; + + @Override + public Person find(int personNationalId) throws IdNotFoundException { + Optional elem = + personList.stream().filter(p -> p.getPersonNationalId() == personNationalId).findFirst(); + if (elem.isEmpty()) { + throw new IdNotFoundException(ID_STR + personNationalId + NOT_IN_DATA_BASE); + } + LOGGER.info(elem.get().toString()); + return elem.get(); + } + + @Override + public void insert(Person person) { + Optional elem = + personList.stream() + .filter(p -> p.getPersonNationalId() == person.getPersonNationalId()) + .findFirst(); + if (elem.isPresent()) { + LOGGER.info("Record already exists."); + return; + } + personList.add(person); + } + + @Override + public void update(Person person) throws IdNotFoundException { + Optional elem = + personList.stream() + .filter(p -> p.getPersonNationalId() == person.getPersonNationalId()) + .findFirst(); + if (elem.isPresent()) { + elem.get().setName(person.getName()); + elem.get().setPhoneNum(person.getPhoneNum()); + LOGGER.info("Record updated successfully"); + return; + } + throw new IdNotFoundException(ID_STR + person.getPersonNationalId() + NOT_IN_DATA_BASE); + } + + /** + * Delete the record corresponding to given ID from the DB. + * + * @param id : personNationalId for person whose record is to be deleted. + */ + public void delete(int id) throws IdNotFoundException { + Optional elem = + personList.stream().filter(p -> p.getPersonNationalId() == id).findFirst(); + if (elem.isPresent()) { + personList.remove(elem.get()); + LOGGER.info("Record deleted successfully."); + return; + } + throw new IdNotFoundException(ID_STR + id + NOT_IN_DATA_BASE); + } + + /** Return the size of the database. */ + public int size() { + if (personList == null) { + return 0; + } + return personList.size(); + } +} diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/PersonFinder.java b/identity-map/src/main/java/com/iluwatar/identitymap/PersonFinder.java new file mode 100644 index 000000000000..35cbcf84ea67 --- /dev/null +++ b/identity-map/src/main/java/com/iluwatar/identitymap/PersonFinder.java @@ -0,0 +1,70 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + +/** + * Any object of this class stores a DataBase and an Identity Map. When we try to look for a key we + * first check if it has been cached in the Identity Map and return it if it is indeed in the map. + * If that is not the case then go to the DataBase, get the record, store it in the Identity Map and + * then return the record. Now if we look for the record again we will find it in the table itself + * which will make lookup faster. + */ +@Slf4j +@Getter +@Setter +public class PersonFinder { + private static final long serialVersionUID = 1L; + // Access to the Identity Map + private IdentityMap identityMap = new IdentityMap(); + private PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + + /** + * get person corresponding to input ID. + * + * @param key : personNationalId to look for. + */ + public Person getPerson(int key) { + // Try to find person in the identity map + Person person = this.identityMap.getPerson(key); + if (person != null) { + LOGGER.info("Person found in the Map"); + return person; + } else { + // Try to find person in the database + person = this.db.find(key); + if (person != null) { + this.identityMap.addPerson(person); + LOGGER.info("Person found in DB."); + return person; + } + LOGGER.info("Person with this ID does not exist."); + return null; + } + } +} diff --git a/identity-map/src/test/java/com/iluwatar/identitymap/AppTest.java b/identity-map/src/test/java/com/iluwatar/identitymap/AppTest.java new file mode 100644 index 000000000000..8ef0e78d6078 --- /dev/null +++ b/identity-map/src/test/java/com/iluwatar/identitymap/AppTest.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/identity-map/src/test/java/com/iluwatar/identitymap/IdentityMapTest.java b/identity-map/src/test/java/com/iluwatar/identitymap/IdentityMapTest.java new file mode 100644 index 000000000000..98289e6d5ec7 --- /dev/null +++ b/identity-map/src/test/java/com/iluwatar/identitymap/IdentityMapTest.java @@ -0,0 +1,77 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class IdentityMapTest { + @Test + void addToMap() { + // new instance of an identity map(not connected to any DB here) + IdentityMap idMap = new IdentityMap(); + // Dummy person instances + Person person1 = new Person(11, "Michael", 27304159); + Person person2 = new Person(22, "John", 42273631); + Person person3 = new Person(33, "Arthur", 27489171); + Person person4 = new Person(44, "Finn", 20499078); + // id already in map + Person person5 = new Person(11, "Michael", 40599078); + // All records go into identity map + idMap.addPerson(person1); + idMap.addPerson(person2); + idMap.addPerson(person3); + idMap.addPerson(person4); + idMap.addPerson(person5); + // Test no duplicate in our Map. + Assertions.assertEquals(4, idMap.size(), "Size of the map is incorrect"); + // Test record not updated by add method. + Assertions.assertEquals( + 27304159, idMap.getPerson(11).getPhoneNum(), "Incorrect return value for phone number"); + } + + @Test + void testGetFromMap() { + // new instance of an identity map(not connected to any DB here) + IdentityMap idMap = new IdentityMap(); + // Dummy person instances + Person person1 = new Person(11, "Michael", 27304159); + Person person2 = new Person(22, "John", 42273631); + Person person3 = new Person(33, "Arthur", 27489171); + Person person4 = new Person(44, "Finn", 20499078); + Person person5 = new Person(55, "Michael", 40599078); + // All records go into identity map + idMap.addPerson(person1); + idMap.addPerson(person2); + idMap.addPerson(person3); + idMap.addPerson(person4); + idMap.addPerson(person5); + // Test for dummy persons in the map + Assertions.assertEquals(person1, idMap.getPerson(11), "Incorrect person record returned"); + Assertions.assertEquals(person4, idMap.getPerson(44), "Incorrect person record returned"); + // Test for person with given id not in map + Assertions.assertNull(idMap.getPerson(1), "Incorrect person record returned"); + } +} diff --git a/identity-map/src/test/java/com/iluwatar/identitymap/PersonDbSimulatorImplementationTest.java b/identity-map/src/test/java/com/iluwatar/identitymap/PersonDbSimulatorImplementationTest.java new file mode 100644 index 000000000000..7861cb2f6200 --- /dev/null +++ b/identity-map/src/test/java/com/iluwatar/identitymap/PersonDbSimulatorImplementationTest.java @@ -0,0 +1,127 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class PersonDbSimulatorImplementationTest { + @Test + void testInsert() { + // DataBase initialization. + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + Assertions.assertEquals(0, db.size(), "Size of null database should be 0"); + // Dummy persons. + Person person1 = new Person(1, "Thomas", 27304159); + Person person2 = new Person(2, "John", 42273631); + Person person3 = new Person(3, "Arthur", 27489171); + db.insert(person1); + db.insert(person2); + db.insert(person3); + // Test size after insertion. + Assertions.assertEquals(3, db.size(), "Incorrect size for database."); + Person person4 = new Person(4, "Finn", 20499078); + Person person5 = new Person(5, "Michael", 40599078); + db.insert(person4); + db.insert(person5); + // Test size after more insertions. + Assertions.assertEquals(5, db.size(), "Incorrect size for database."); + Person person5duplicate = new Person(5, "Kevin", 89589122); + db.insert(person5duplicate); + // Test size after attempt to insert record with duplicate key. + Assertions.assertEquals(5, db.size(), "Incorrect size for data base"); + } + + @Test + void findNotInDb() { + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + Person person1 = new Person(1, "Thomas", 27304159); + Person person2 = new Person(2, "John", 42273631); + db.insert(person1); + db.insert(person2); + // Test if IdNotFoundException is thrown where expected. + Assertions.assertThrows(IdNotFoundException.class, () -> db.find(3)); + } + + @Test + void findInDb() { + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + Person person1 = new Person(1, "Thomas", 27304159); + Person person2 = new Person(2, "John", 42273631); + db.insert(person1); + db.insert(person2); + Assertions.assertEquals(person2, db.find(2), "Record that was found was incorrect."); + } + + @Test + void updateNotInDb() { + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + Person person1 = new Person(1, "Thomas", 27304159); + Person person2 = new Person(2, "John", 42273631); + db.insert(person1); + db.insert(person2); + Person person3 = new Person(3, "Micheal", 25671234); + // Test if IdNotFoundException is thrown when person with ID 3 is not in DB. + Assertions.assertThrows(IdNotFoundException.class, () -> db.update(person3)); + } + + @Test + void updateInDb() { + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + Person person1 = new Person(1, "Thomas", 27304159); + Person person2 = new Person(2, "John", 42273631); + db.insert(person1); + db.insert(person2); + Person person = new Person(2, "Thomas", 42273690); + db.update(person); + Assertions.assertEquals(person, db.find(2), "Incorrect update."); + } + + @Test + void deleteNotInDb() { + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + Person person1 = new Person(1, "Thomas", 27304159); + Person person2 = new Person(2, "John", 42273631); + db.insert(person1); + db.insert(person2); + // Test if IdNotFoundException is thrown when person with this ID not in DB. + Assertions.assertThrows(IdNotFoundException.class, () -> db.delete(3)); + } + + @Test + void deleteInDb() { + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + Person person1 = new Person(1, "Thomas", 27304159); + Person person2 = new Person(2, "John", 42273631); + db.insert(person1); + db.insert(person2); + // delete the record. + db.delete(1); + // test size of database after deletion. + Assertions.assertEquals(1, db.size(), "Size after deletion is incorrect."); + // try to find deleted record in db. + Assertions.assertThrows(IdNotFoundException.class, () -> db.find(1)); + } +} diff --git a/identity-map/src/test/java/com/iluwatar/identitymap/PersonFinderTest.java b/identity-map/src/test/java/com/iluwatar/identitymap/PersonFinderTest.java new file mode 100644 index 000000000000..9257a3b0a28c --- /dev/null +++ b/identity-map/src/test/java/com/iluwatar/identitymap/PersonFinderTest.java @@ -0,0 +1,118 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class PersonFinderTest { + @Test + void personFoundInDB() { + // personFinderInstance + PersonFinder personFinder = new PersonFinder(); + // init database for our personFinder + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + // Dummy persons + Person person1 = new Person(1, "John", 27304159); + Person person2 = new Person(2, "Thomas", 42273631); + Person person3 = new Person(3, "Arthur", 27489171); + Person person4 = new Person(4, "Finn", 20499078); + Person person5 = new Person(5, "Michael", 40599078); + // Add data to the database. + db.insert(person1); + db.insert(person2); + db.insert(person3); + db.insert(person4); + db.insert(person5); + personFinder.setDb(db); + + Assertions.assertEquals( + person1, personFinder.getPerson(1), "Find person returns incorrect record."); + Assertions.assertEquals( + person3, personFinder.getPerson(3), "Find person returns incorrect record."); + Assertions.assertEquals( + person2, personFinder.getPerson(2), "Find person returns incorrect record."); + Assertions.assertEquals( + person5, personFinder.getPerson(5), "Find person returns incorrect record."); + Assertions.assertEquals( + person4, personFinder.getPerson(4), "Find person returns incorrect record."); + } + + @Test + void personFoundInIdMap() { + // personFinderInstance + PersonFinder personFinder = new PersonFinder(); + // init database for our personFinder + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + // Dummy persons + Person person1 = new Person(1, "John", 27304159); + Person person2 = new Person(2, "Thomas", 42273631); + Person person3 = new Person(3, "Arthur", 27489171); + Person person4 = new Person(4, "Finn", 20499078); + Person person5 = new Person(5, "Michael", 40599078); + // Add data to the database. + db.insert(person1); + db.insert(person2); + db.insert(person3); + db.insert(person4); + db.insert(person5); + personFinder.setDb(db); + // Assure key is not in the ID map. + Assertions.assertFalse(personFinder.getIdentityMap().getPersonMap().containsKey(3)); + // Assure key is in the database. + Assertions.assertEquals(person3, personFinder.getPerson(3), "Finder returns incorrect record."); + // Assure that the record for this key is cached in the Map now. + Assertions.assertTrue(personFinder.getIdentityMap().getPersonMap().containsKey(3)); + // Find the record again. This time it will be found in the map. + Assertions.assertEquals(person3, personFinder.getPerson(3), "Finder returns incorrect record."); + } + + @Test + void personNotFoundInDB() { + PersonFinder personFinder = new PersonFinder(); + // init database for our personFinder + PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + personFinder.setDb(db); + Assertions.assertThrows(IdNotFoundException.class, () -> personFinder.getPerson(1)); + // Dummy persons + Person person1 = new Person(1, "John", 27304159); + Person person2 = new Person(2, "Thomas", 42273631); + Person person3 = new Person(3, "Arthur", 27489171); + Person person4 = new Person(4, "Finn", 20499078); + Person person5 = new Person(5, "Michael", 40599078); + db.insert(person1); + db.insert(person2); + db.insert(person3); + db.insert(person4); + db.insert(person5); + personFinder.setDb(db); + // Assure that the database has been updated. + Assertions.assertEquals(person4, personFinder.getPerson(4), "Find returns incorrect record"); + // Assure key is in DB now. + Assertions.assertDoesNotThrow(() -> personFinder.getPerson(1)); + // Assure key not in DB. + Assertions.assertThrows(IdNotFoundException.class, () -> personFinder.getPerson(6)); + } +} diff --git a/identity-map/src/test/java/com/iluwatar/identitymap/PersonTest.java b/identity-map/src/test/java/com/iluwatar/identitymap/PersonTest.java new file mode 100644 index 000000000000..8199daaa2a62 --- /dev/null +++ b/identity-map/src/test/java/com/iluwatar/identitymap/PersonTest.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.identitymap; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class PersonTest { + @Test + void testEquality() { + // dummy persons. + Person person1 = new Person(1, "Harry", 989950022); + Person person2 = new Person(2, "Kane", 989920011); + Assertions.assertNotEquals(person1, person2, "Incorrect equality condition"); + // person with duplicate nationalID. + Person person3 = new Person(2, "John", 789012211); + // If nationalID is equal then persons are equal(even if name or phoneNum are different). + // This situation will never arise in this implementation. Only for testing. + Assertions.assertEquals(person2, person3, "Incorrect inequality condition"); + } +} diff --git a/intercepting-filter/README.md b/intercepting-filter/README.md index 7d53472a077f..c6f6723f534f 100644 --- a/intercepting-filter/README.md +++ b/intercepting-filter/README.md @@ -1,33 +1,164 @@ --- -layout: pattern -title: Intercepting Filter -folder: intercepting-filter -permalink: /patterns/intercepting-filter/ -categories: Behavioral -tags: - - Java - - Difficulty-Intermediate +title: "Intercepting Filter Pattern in Java: Enhancing Request Processing in Web Applications" +shortTitle: Intercepting Filter +description: "Learn about the Intercepting Filter Pattern in Java. Discover how to design, implement, and use this pattern to enhance web request handling with practical examples and detailed explanations." +category: Architectural +language: en +tag: + - API design + - Decoupling + - Layered architecture + - Performance + - Security + - Web development --- -## Intent -Provide pluggable filters to conduct necessary pre-processing and -post-processing to requests from a client to a target - -![alt text](./etc/intercepting-filter.png "Intercepting Filter") - -## Applicability +## Intent of Intercepting Filter Design Pattern + +The Intercepting Filter Pattern in Java is a powerful design pattern that allows for efficient web request handling. This pattern enables the application of multiple filters in a filter chain to process and modify requests and responses. + +## Detailed Explanation of Intercepting Filter Pattern with Real-World Examples + +Real-world example + +> Consider entering a secure office building where you pass through several checkpoints: a security desk checks your ID, a metal detector ensures safety, and a registration desk logs your visit. Each checkpoint acts like a filter in the Intercepting Filter pattern, processing and validating your entry step-by-step, similar to how filters handle different aspects of web requests and responses in a software system. + +In plain words + +> The Intercepting Filter design pattern allows you to define processing steps (filters) that execute sequentially to handle and modify web requests and responses before they reach the application or are sent to the client. + +Wikipedia says + +> Intercepting Filter is a Java pattern which creates pluggable filters to process common services in a standard manner without requiring changes to core request processing code. + +Architecture diagram + +![Intercepting Filter Architecture Diagram](./etc/intercepting-filter-architecture-diagram.png) + +## Programmatic Example of Intercepting Filter Pattern in Java + +In this article, we delve into the Intercepting Filter Pattern and provide a Java example to illustrate its use. This pattern is essential for Java web development, offering a modular approach to handling common services such as logging, authentication, and data compression. + +The Java implementation of the Intercepting Filter Pattern includes classes like `FilterManager` and `Client`, which facilitate the management and application of filters. Each filter in the chain performs specific tasks, ensuring a clean and efficient design. + +The `App` class is the entry point of the application. It creates an instance of `FilterManager`, adds various filters to it, and sets it to a `Client`. + +```java +public class App { + + public static void main(String[] args) { + var filterManager = new FilterManager(); + filterManager.addFilter(new NameFilter()); + filterManager.addFilter(new ContactFilter()); + filterManager.addFilter(new AddressFilter()); + filterManager.addFilter(new DepositFilter()); + filterManager.addFilter(new OrderFilter()); + + var client = new Client(); + client.setFilterManager(filterManager); + } +} +``` + +The `FilterManager` class manages the filters and applies them to the requests. + +```java +public class FilterManager { + private final List filters = new ArrayList<>(); + + public void addFilter(Filter filter) { + filters.add(filter); + } + + public void filterRequest(String request) { + for (Filter filter : filters) { + filter.execute(request); + } + } +} +``` + +The `Client` class sends the request to the `FilterManager`. + +```java +public class Client { + private FilterManager filterManager; + + public void setFilterManager(FilterManager filterManager) { + this.filterManager = filterManager; + } + + public void sendRequest(String request) { + filterManager.filterRequest(request); + } +} +``` + +The `Filter` interface and its implementations (`NameFilter`, `ContactFilter`, `AddressFilter`, `DepositFilter`, `OrderFilter`) define the filters that can be applied to the requests. + +```java +public interface Filter { + void execute(String request); +} + +public class NameFilter extends AbstractFilter { + + @Override + public String execute(Order order) { + var result = super.execute(order); + var name = order.getName(); + if (name == null || name.isEmpty() || name.matches(".*[^\\w|\\s]+.*")) { + return result + "Invalid name! "; + } else { + return result; + } + } +} + +// Other Filter implementations... +``` + +In this example, the `App` class sets up a `FilterManager` with various filters and assigns it to a `Client`. When the `Client` sends a request, the `FilterManager` applies all the filters to the request. This is a basic example of the Intercepting Filter pattern, where common processing tasks are encapsulated in filters and applied to requests in a standard manner. + +## When to Use the Intercepting Filter Pattern in Java + Use the Intercepting Filter pattern when -* a system uses pre-processing or post-processing requests -* a system should do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers -* you want a modular approach to configuring pre-processing and post-processing schemes +* In Java web applications to manage cross-cutting concerns. +* When you need to apply pre-processing and post-processing steps to requests and responses, typically in web applications. +* Suitable for handling cross-cutting concerns such as logging, authentication, data compression, and encryption transparently. + +## Intercepting Filter Pattern Java Tutorials + +* [Introduction to Intercepting Filter Pattern in Java (Baeldung)](https://www.baeldung.com/intercepting-filter-pattern-in-java) +* [Design Pattern - Intercepting Filter Pattern (TutorialsPoint)](http://www.tutorialspoint.com/design_pattern/intercepting_filter_pattern.htm) -## Real world examples +## Real-World Applications of Intercepting Filter Pattern in Java +* Frameworks like Spring MVC and web servers such as Apache Tomcat utilize the Intercepting Filter Pattern to enhance Java web development. This pattern's ability to centralize control and streamline web request handling makes it a go-to choice for developers. * [javax.servlet.FilterChain](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/FilterChain.html) and [javax.servlet.Filter](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/Filter.html) -* [Struts 2 - Interceptors](https://struts.apache.org/docs/interceptors.html) +* [Struts 2 - Interceptors](https://struts.apache.org/core-developers/interceptors.html) + +## Benefits and Trade-offs of Intercepting Filter Pattern + +Benefits: + +* Promotes separation of concerns by allowing filters to be independently developed, tested, and reused. +* Enhances flexibility through configurable filter chains. +* Simplifies application maintenance by centralizing control in filter management. + +Trade-offs: + +* Introducing many filters can lead to performance overhead due to the processing of each request and response through multiple filters. +* Debugging and tracing the request flow through multiple filters can be complex. + +## Related Java Design Patterns + +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Filters in the Intercepting Filter pattern can be considered as decorators that add additional responsibilities to request handling. They modify the request/response without altering their fundamental behavior. +* [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Filters are linked in a chain, where each filter processes the request or response and optionally passes it to the next filter in the chain, similar to how responsibilities are passed along in the Chain of Responsibility pattern. -## Credits +## References and Credits -* [TutorialsPoint - Intercepting Filter](http://www.tutorialspoint.com/design_pattern/intercepting_filter_pattern.htm) -* [Presentation Tier Patterns](http://www.javagyan.com/tutorials/corej2eepatterns/presentation-tier-patterns) +* [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/intercepting-filter/etc/intercepting-filter-architecture-diagram.png b/intercepting-filter/etc/intercepting-filter-architecture-diagram.png new file mode 100644 index 000000000000..f70c0ec0c441 Binary files /dev/null and b/intercepting-filter/etc/intercepting-filter-architecture-diagram.png differ diff --git a/intercepting-filter/etc/intercepting-filter.urm.puml b/intercepting-filter/etc/intercepting-filter.urm.puml new file mode 100644 index 000000000000..6e565fd668c9 --- /dev/null +++ b/intercepting-filter/etc/intercepting-filter.urm.puml @@ -0,0 +1,88 @@ +@startuml +package com.iluwatar.intercepting.filter { + abstract class AbstractFilter { + - next : Filter + + AbstractFilter() + + AbstractFilter(next : Filter) + + execute(order : Order) : String + + getLast() : Filter + + getNext() : Filter + + setNext(filter : Filter) + } + class AddressFilter { + + AddressFilter() + + execute(order : Order) : String + } + class App { + + App() + + main(args : String[]) {static} + } + class ContactFilter { + + ContactFilter() + + execute(order : Order) : String + } + class DepositFilter { + + DepositFilter() + + execute(order : Order) : String + } + interface Filter { + + execute(Order) : String {abstract} + + getLast() : Filter {abstract} + + getNext() : Filter {abstract} + + setNext(Filter) {abstract} + } + class FilterChain { + - chain : Filter + + FilterChain() + + addFilter(filter : Filter) + + execute(order : Order) : String + } + class FilterManager { + - filterChain : FilterChain + + FilterManager() + + addFilter(filter : Filter) + + filterRequest(order : Order) : String + } + class NameFilter { + + NameFilter() + + execute(order : Order) : String + } + class Order { + - address : String + - contactNumber : String + - depositNumber : String + - name : String + - orderItem : String + + Order() + + Order(name : String, contactNumber : String, address : String, depositNumber : String, order : String) + + getAddress() : String + + getContactNumber() : String + + getDepositNumber() : String + + getName() : String + + getOrderItem() : String + + setAddress(address : String) + + setContactNumber(contactNumber : String) + + setDepositNumber(depositNumber : String) + + setName(name : String) + + setOrderItem(order : String) + } + class OrderFilter { + + OrderFilter() + + execute(order : Order) : String + } + ~class DListener { + ~ DListener() + + actionPerformed(e : ActionEvent) + } +} +AbstractFilter --> "-next" Filter +DListener --+ Target +FilterManager --> "-filterChain" FilterChain +FilterChain --> "-chain" Filter +AbstractFilter ..|> Filter +AddressFilter --|> AbstractFilter +ContactFilter --|> AbstractFilter +DepositFilter --|> AbstractFilter +NameFilter --|> AbstractFilter +OrderFilter --|> AbstractFilter +@enduml \ No newline at end of file diff --git a/intercepting-filter/pom.xml b/intercepting-filter/pom.xml index 658dba671cbe..9cd786bd5817 100644 --- a/intercepting-filter/pom.xml +++ b/intercepting-filter/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT intercepting-filter - - org.junit.jupiter - junit-jupiter-api - test - org.junit.jupiter junit-jupiter-engine @@ -54,4 +50,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.intercepting.filter.App + + + + + + + + diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java index 2e48f73b28a0..7803ef878571 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,10 +24,7 @@ */ package com.iluwatar.intercepting.filter; -/** - * Base class for order processing filters. Handles chain management. - * - */ +/** Base class for order processing filters. Handles chain management. */ public abstract class AbstractFilter implements Filter { private Filter next; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java index 1ba7ee8d391c..0f8aeeb5567e 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,15 +27,12 @@ /** * Concrete implementation of filter This filter is responsible for checking/filtering the input in * the address field. - * - * @author joshzambales - * */ public class AddressFilter extends AbstractFilter { @Override public String execute(Order order) { - String result = super.execute(order); + var result = super.execute(order); if (order.getAddress() == null || order.getAddress().isEmpty()) { return result + "Invalid address! "; } else { diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java index 1315f1318eb7..53559ede1a78 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,7 +25,6 @@ package com.iluwatar.intercepting.filter; /** - * * When a request enters a Web application, it often must pass several entrance tests prior to the * main processing stage. For example, - Has the client been authenticated? - Does the client have a * valid session? - Is the client's IP address from a trusted network? - Does the request path @@ -31,39 +32,35 @@ * the browser type of the client? Some of these checks are tests, resulting in a yes or no answer * that determines whether processing will continue. Other checks manipulate the incoming data * stream into a form suitable for processing. - *

    - * The classic solution consists of a series of conditional checks, with any failed check aborting - * the request. Nested if/else statements are a standard strategy, but this solution leads to code - * fragility and a copy-and-paste style of programming, because the flow of the filtering and the - * action of the filters is compiled into the application. - *

    - * The key to solving this problem in a flexible and unobtrusive manner is to have a simple + * + *

    The classic solution consists of a series of conditional checks, with any failed check + * aborting the request. Nested if/else statements are a standard strategy, but this solution leads + * to code fragility and a copy-and-paste style of programming, because the flow of the filtering + * and the action of the filters is compiled into the application. + * + *

    The key to solving this problem in a flexible and unobtrusive manner is to have a simple * mechanism for adding and removing processing components, in which each component completes a * specific filtering action. This is the Intercepting Filter pattern in action. - *

    - * In this example we check whether the order request is valid through pre-processing done via - * {@link Filter}. Each field has its own corresponding {@link Filter} - *

    - * - * @author joshzambales * + *

    In this example we check whether the order request is valid through pre-processing done via + * {@link Filter}. Each field has its own corresponding {@link Filter}. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - FilterManager filterManager = new FilterManager(); + var filterManager = new FilterManager(); filterManager.addFilter(new NameFilter()); filterManager.addFilter(new ContactFilter()); filterManager.addFilter(new AddressFilter()); filterManager.addFilter(new DepositFilter()); filterManager.addFilter(new OrderFilter()); - Client client = new Client(); + var client = new Client(); client.setFilterManager(filterManager); } } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java index 60b888dc7c1b..96f2e2acdc6f 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -24,7 +26,9 @@ import java.awt.BorderLayout; import java.awt.GridLayout; - +import java.awt.event.ActionEvent; +import java.io.Serial; +import java.util.Arrays; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; @@ -33,42 +37,38 @@ import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; /** - * The Client class is responsible for handling the input and running them through filters inside the - * {@link FilterManager}. - * - * This is where {@link Filter}s come to play as the client pre-processes the request before being displayed in the - * {@link Target}. - * - * @author joshzambales + * The Client class is responsible for handling the input and running them through filters inside + * the {@link FilterManager}. * + *

    This is where {@link Filter}s come to play as the client pre-processes the request before + * being displayed in the {@link Target}. */ public class Client extends JFrame { // NOSONAR - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; private transient FilterManager filterManager; - private JLabel jl; - private JTextField[] jtFields; - private JTextArea[] jtAreas; - private JButton clearButton; - private JButton processButton; + private final JLabel jl; + private final JTextField[] jtFields; + private final JTextArea[] jtAreas; + private final JButton clearButton; + private final JButton processButton; - /** - * Constructor - */ + /** Constructor. */ public Client() { super("Client System"); - setDefaultCloseOperation(EXIT_ON_CLOSE); + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(300, 300); jl = new JLabel("RUNNING..."); jtFields = new JTextField[3]; - for (int i = 0; i < 3; i++) { + for (var i = 0; i < 3; i++) { jtFields[i] = new JTextField(); } jtAreas = new JTextArea[2]; - for (int i = 0; i < 2; i++) { + for (var i = 0; i < 2; i++) { jtAreas[i] = new JTextArea(); } clearButton = new JButton("Clear"); @@ -79,7 +79,7 @@ public Client() { private void setup() { setLayout(new BorderLayout()); - JPanel panel = new JPanel(); + var panel = new JPanel(); add(jl, BorderLayout.SOUTH); add(panel, BorderLayout.CENTER); panel.setLayout(new GridLayout(6, 2)); @@ -96,20 +96,13 @@ private void setup() { panel.add(clearButton); panel.add(processButton); - clearButton.addActionListener(e -> { - for (JTextArea i : jtAreas) { - i.setText(""); - } - for (JTextField i : jtFields) { - i.setText(""); - } - }); + clearButton.addActionListener( + e -> { + Arrays.stream(jtAreas).forEach(i -> i.setText("")); + Arrays.stream(jtFields).forEach(i -> i.setText("")); + }); - processButton.addActionListener(e -> { - Order order = new Order(jtFields[0].getText(), jtFields[1].getText(), jtAreas[0].getText(), jtFields[2].getText(), - jtAreas[1].getText()); - jl.setText(sendRequest(order)); - }); + processButton.addActionListener(this::actionPerformed); JRootPane rootPane = SwingUtilities.getRootPane(processButton); rootPane.setDefaultButton(processButton); @@ -123,4 +116,14 @@ public void setFilterManager(FilterManager filterManager) { public String sendRequest(Order order) { return filterManager.filterRequest(order); } + + private void actionPerformed(ActionEvent e) { + var fieldText1 = jtFields[0].getText(); + var fieldText2 = jtFields[1].getText(); + var areaText1 = jtAreas[0].getText(); + var fieldText3 = jtFields[2].getText(); + var areaText2 = jtAreas[1].getText(); + var order = new Order(fieldText1, fieldText2, areaText1, fieldText3, areaText2); + jl.setText(sendRequest(order)); + } } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java index 52a0487c49aa..14b4914444d5 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,19 +27,17 @@ /** * Concrete implementation of filter This filter checks for the contact field in which it checks if * the input consist of numbers and it also checks if the input follows the length constraint (11 - * digits) - * - * @author joshzambales - * + * digits). */ public class ContactFilter extends AbstractFilter { @Override public String execute(Order order) { - String result = super.execute(order); - if (order.getContactNumber() == null || order.getContactNumber().isEmpty() - || order.getContactNumber().matches(".*[^\\d]+.*") - || order.getContactNumber().length() != 11) { + var result = super.execute(order); + var contactNumber = order.getContactNumber(); + if (contactNumber == null + || contactNumber.matches(".*[^\\d]+.*") + || contactNumber.length() != 11) { return result + "Invalid contact number! "; } else { return result; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java index cc06c339d995..2c13d831e5ac 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,14 @@ */ package com.iluwatar.intercepting.filter; -/** - * Concrete implementation of filter This checks for the deposit code - * - * @author joshzambales - * - */ +/** Concrete implementation of filter This checks for the deposit code. */ public class DepositFilter extends AbstractFilter { @Override public String execute(Order order) { - String result = super.execute(order); - if (order.getDepositNumber() == null || order.getDepositNumber().isEmpty()) { + var result = super.execute(order); + var depositNumber = order.getDepositNumber(); + if (depositNumber == null || depositNumber.isEmpty()) { return result + "Invalid deposit number! "; } else { return result; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java index 0cf2a1b6f7c0..fcadf86a7a4a 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,29 +27,18 @@ /** * Filters perform certain tasks prior or after execution of request by request handler. In this * case, before the request is handled by the target, the request undergoes through each Filter - * - * @author joshzambales - * */ public interface Filter { - /** - * Execute order processing filter. - */ + /** Execute order processing filter. */ String execute(Order order); - /** - * Set next filter in chain after this. - */ + /** Set next filter in chain after this. */ void setNext(Filter filter); - /** - * Get next filter in chain after this. - */ + /** Get next filter in chain after this. */ Filter getNext(); - /** - * Get last filter in the chain. - */ + /** Get last filter in the chain. */ Filter getLast(); } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java index 1e0c0de35d97..1fc27095a341 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,12 @@ */ package com.iluwatar.intercepting.filter; - -/** - * Filter Chain carries multiple filters and help to execute them in defined order on target. - * - * @author joshzambales - */ +/** Filter Chain carries multiple filters and help to execute them in defined order on target. */ public class FilterChain { private Filter chain; - - /** - * Adds filter - */ + /** Adds filter. */ public void addFilter(Filter filter) { if (chain == null) { chain = filter; @@ -44,9 +38,7 @@ public void addFilter(Filter filter) { } } - /** - * Execute filter chain - */ + /** Execute filter chain. */ public String execute(Order order) { if (chain != null) { return chain.execute(order); diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java index e9897ec9233e..93303dd9ad60 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,15 +24,10 @@ */ package com.iluwatar.intercepting.filter; -/** - * Filter Manager manages the filters and {@link FilterChain}. - * - * @author joshzambales - * - */ +/** Filter Manager manages the filters and {@link FilterChain}. */ public class FilterManager { - private FilterChain filterChain; + private final FilterChain filterChain; public FilterManager() { filterChain = new FilterChain(); diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java index 7efb181bb1a0..19f80a4eec08 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,17 +27,14 @@ /** * Concrete implementation of filter. This filter checks if the input in the Name field is valid. * (alphanumeric) - * - * @author joshzambales - * */ public class NameFilter extends AbstractFilter { @Override public String execute(Order order) { - String result = super.execute(order); - if (order.getName() == null || order.getName().isEmpty() - || order.getName().matches(".*[^\\w|\\s]+.*")) { + var result = super.execute(order); + var name = order.getName(); + if (name == null || name.isEmpty() || name.matches(".*[^\\w|\\s]+.*")) { return result + "Invalid name! "; } else { return result; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java index c298986527b2..576b26a4c3e1 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,10 +24,16 @@ */ package com.iluwatar.intercepting.filter; -/** - * Order class carries the order data. - * - */ +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** Order class carries the order data. */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor public class Order { private String name; @@ -33,57 +41,4 @@ public class Order { private String address; private String depositNumber; private String orderItem; - - public Order() {} - - /** - * Constructor - */ - public Order(String name, String contactNumber, String address, String depositNumber, String order) { - this.name = name; - this.contactNumber = contactNumber; - this.address = address; - this.depositNumber = depositNumber; - this.orderItem = order; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getContactNumber() { - return contactNumber; - } - - public void setContactNumber(String contactNumber) { - this.contactNumber = contactNumber; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getDepositNumber() { - return depositNumber; - } - - public void setDepositNumber(String depositNumber) { - this.depositNumber = depositNumber; - } - - public String getOrderItem() { - return orderItem; - } - - public void setOrderItem(String order) { - this.orderItem = order; - } } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java index bc9ff7d90414..f3eed5f1a1a1 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,14 @@ */ package com.iluwatar.intercepting.filter; -/** - * Concrete implementation of filter. This checks for the order field. - * - * @author joshzambales - * - */ +/** Concrete implementation of filter. This checks for the order field. */ public class OrderFilter extends AbstractFilter { @Override public String execute(Order order) { - String result = super.execute(order); - if (order.getOrderItem() == null || order.getOrderItem().isEmpty()) { + var result = super.execute(order); + var orderItem = order.getOrderItem(); + if (orderItem == null || orderItem.isEmpty()) { return result + "Invalid order! "; } else { return result; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java index 6652d1eb49cb..92b76745e1c9 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -26,41 +28,34 @@ import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - +import java.io.Serial; +import java.util.stream.IntStream; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; -import javax.swing.JRootPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; import javax.swing.table.DefaultTableModel; -/** - * This is where the requests are displayed after being validated by filters. - * - * @author mjoshzambales - * - */ -public class Target extends JFrame { //NOSONAR +/** This is where the requests are displayed after being validated by filters. */ +public class Target extends JFrame { // NOSONAR - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; - private JTable jt; - private JScrollPane jsp; - private DefaultTableModel dtm; - private JButton del; + private final JTable jt; + private final DefaultTableModel dtm; + private final JButton del; - /** - * Constructor - */ + /** Constructor. */ public Target() { super("Order System"); - setDefaultCloseOperation(EXIT_ON_CLOSE); + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(640, 480); dtm = - new DefaultTableModel(new Object[] {"Name", "Contact Number", "Address", "Deposit Number", - "Order"}, 0); + new DefaultTableModel( + new Object[] {"Name", "Contact Number", "Address", "Deposit Number", "Order"}, 0); jt = new JTable(dtm); del = new JButton("Delete"); setup(); @@ -68,18 +63,18 @@ public Target() { private void setup() { setLayout(new BorderLayout()); - JPanel bot = new JPanel(); + var bot = new JPanel(); add(jt.getTableHeader(), BorderLayout.NORTH); bot.setLayout(new BorderLayout()); bot.add(del, BorderLayout.EAST); add(bot, BorderLayout.SOUTH); - jsp = new JScrollPane(jt); + var jsp = new JScrollPane(jt); jsp.setPreferredSize(new Dimension(500, 250)); add(jsp, BorderLayout.CENTER); - del.addActionListener(new DListener()); + del.addActionListener(new TargetListener()); - JRootPane rootPane = SwingUtilities.getRootPane(del); + var rootPane = SwingUtilities.getRootPane(del); rootPane.setDefaultButton(del); setVisible(true); } @@ -88,17 +83,15 @@ public void execute(String[] request) { dtm.addRow(new Object[] {request[0], request[1], request[2], request[3], request[4]}); } - class DListener implements ActionListener { + class TargetListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { - int temp = jt.getSelectedRow(); + var temp = jt.getSelectedRow(); if (temp == -1) { return; } - int temp2 = jt.getSelectedRowCount(); - for (int i = 0; i < temp2; i++) { - dtm.removeRow(temp); - } + var temp2 = jt.getSelectedRowCount(); + IntStream.range(0, temp2).forEach(i -> dtm.removeRow(temp)); } } } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java index fb6cfb7e452c..27e5aaba2e05 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.intercepting.filter; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test. - * - */ -public class AppTest { +/** Application test. */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java index 74259c152a22..969386c823cc 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,39 +24,35 @@ */ package com.iluwatar.intercepting.filter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -/** - * Date: 12/13/15 - 3:01 PM - * - * @author Jeroen Meulemeester - */ -public class FilterManagerTest { +import org.junit.jupiter.api.Test; + +/** FilterManagerTest */ +class FilterManagerTest { @Test - public void testFilterRequest() throws Exception { - final Target target = mock(Target.class); - final FilterManager filterManager = new FilterManager(); + void testFilterRequest() { + final var target = mock(Target.class); + final var filterManager = new FilterManager(); assertEquals("RUNNING...", filterManager.filterRequest(mock(Order.class))); - verifyZeroInteractions(target); + verifyNoMoreInteractions(target); } @Test - public void testAddFilter() throws Exception { - final Target target = mock(Target.class); - final FilterManager filterManager = new FilterManager(); + void testAddFilter() { + final var target = mock(Target.class); + final var filterManager = new FilterManager(); - verifyZeroInteractions(target); + verifyNoMoreInteractions(target); - final Filter filter = mock(Filter.class); + final var filter = mock(Filter.class); when(filter.execute(any(Order.class))).thenReturn("filter"); filterManager.addFilter(filter); @@ -63,6 +61,6 @@ public void testAddFilter() throws Exception { assertEquals("filter", filterManager.filterRequest(order)); verify(filter, times(1)).execute(any(Order.class)); - verifyZeroInteractions(target, filter, order); + verifyNoMoreInteractions(target, filter, order); } -} \ No newline at end of file +} diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java index 43170af426f9..60b12a9302e7 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,25 +24,20 @@ */ package com.iluwatar.intercepting.filter; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import java.util.ArrayList; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; -/** - * Date: 12/13/15 - 2:17 PM - * - * @author Jeroen Meulemeester - */ -public class FilterTest { +import java.util.List; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** FilterTest */ +class FilterTest { - private static final Order PERFECT_ORDER = new Order("name", "12345678901", "addr", "dep", "order"); + private static final Order PERFECT_ORDER = + new Order("name", "12345678901", "addr", "dep", "order"); private static final Order WRONG_ORDER = new Order("name", "12345678901", "addr", "dep", ""); private static final Order WRONG_DEPOSIT = new Order("name", "12345678901", "addr", "", "order"); private static final Order WRONG_ADDRESS = new Order("name", "12345678901", "", "dep", "order"); @@ -48,58 +45,51 @@ public class FilterTest { private static final Order WRONG_NAME = new Order("", "12345678901", "addr", "dep", "order"); static List getTestData() { - final List testData = new ArrayList<>(); - testData.add(new Object[]{new NameFilter(), PERFECT_ORDER, ""}); - testData.add(new Object[]{new NameFilter(), WRONG_NAME, "Invalid name!"}); - testData.add(new Object[]{new NameFilter(), WRONG_CONTACT, ""}); - testData.add(new Object[]{new NameFilter(), WRONG_ADDRESS, ""}); - testData.add(new Object[]{new NameFilter(), WRONG_DEPOSIT, ""}); - testData.add(new Object[]{new NameFilter(), WRONG_ORDER, ""}); - - testData.add(new Object[]{new ContactFilter(), PERFECT_ORDER, ""}); - testData.add(new Object[]{new ContactFilter(), WRONG_NAME, ""}); - testData.add(new Object[]{new ContactFilter(), WRONG_CONTACT, "Invalid contact number!"}); - testData.add(new Object[]{new ContactFilter(), WRONG_ADDRESS, ""}); - testData.add(new Object[]{new ContactFilter(), WRONG_DEPOSIT, ""}); - testData.add(new Object[]{new ContactFilter(), WRONG_ORDER, ""}); - - testData.add(new Object[]{new AddressFilter(), PERFECT_ORDER, ""}); - testData.add(new Object[]{new AddressFilter(), WRONG_NAME, ""}); - testData.add(new Object[]{new AddressFilter(), WRONG_CONTACT, ""}); - testData.add(new Object[]{new AddressFilter(), WRONG_ADDRESS, "Invalid address!"}); - testData.add(new Object[]{new AddressFilter(), WRONG_DEPOSIT, ""}); - testData.add(new Object[]{new AddressFilter(), WRONG_ORDER, ""}); - - testData.add(new Object[]{new DepositFilter(), PERFECT_ORDER, ""}); - testData.add(new Object[]{new DepositFilter(), WRONG_NAME, ""}); - testData.add(new Object[]{new DepositFilter(), WRONG_CONTACT, ""}); - testData.add(new Object[]{new DepositFilter(), WRONG_ADDRESS, ""}); - testData.add(new Object[]{new DepositFilter(), WRONG_DEPOSIT, "Invalid deposit number!"}); - testData.add(new Object[]{new DepositFilter(), WRONG_ORDER, ""}); - - testData.add(new Object[]{new OrderFilter(), PERFECT_ORDER, ""}); - testData.add(new Object[]{new OrderFilter(), WRONG_NAME, ""}); - testData.add(new Object[]{new OrderFilter(), WRONG_CONTACT, ""}); - testData.add(new Object[]{new OrderFilter(), WRONG_ADDRESS, ""}); - testData.add(new Object[]{new OrderFilter(), WRONG_DEPOSIT, ""}); - testData.add(new Object[]{new OrderFilter(), WRONG_ORDER, "Invalid order!"}); - - return testData; + return List.of( + new Object[] {new NameFilter(), PERFECT_ORDER, ""}, + new Object[] {new NameFilter(), WRONG_NAME, "Invalid name!"}, + new Object[] {new NameFilter(), WRONG_CONTACT, ""}, + new Object[] {new NameFilter(), WRONG_ADDRESS, ""}, + new Object[] {new NameFilter(), WRONG_DEPOSIT, ""}, + new Object[] {new NameFilter(), WRONG_ORDER, ""}, + new Object[] {new ContactFilter(), PERFECT_ORDER, ""}, + new Object[] {new ContactFilter(), WRONG_NAME, ""}, + new Object[] {new ContactFilter(), WRONG_CONTACT, "Invalid contact number!"}, + new Object[] {new ContactFilter(), WRONG_ADDRESS, ""}, + new Object[] {new ContactFilter(), WRONG_DEPOSIT, ""}, + new Object[] {new ContactFilter(), WRONG_ORDER, ""}, + new Object[] {new AddressFilter(), PERFECT_ORDER, ""}, + new Object[] {new AddressFilter(), WRONG_NAME, ""}, + new Object[] {new AddressFilter(), WRONG_CONTACT, ""}, + new Object[] {new AddressFilter(), WRONG_ADDRESS, "Invalid address!"}, + new Object[] {new AddressFilter(), WRONG_DEPOSIT, ""}, + new Object[] {new AddressFilter(), WRONG_ORDER, ""}, + new Object[] {new DepositFilter(), PERFECT_ORDER, ""}, + new Object[] {new DepositFilter(), WRONG_NAME, ""}, + new Object[] {new DepositFilter(), WRONG_CONTACT, ""}, + new Object[] {new DepositFilter(), WRONG_ADDRESS, ""}, + new Object[] {new DepositFilter(), WRONG_DEPOSIT, "Invalid deposit number!"}, + new Object[] {new DepositFilter(), WRONG_ORDER, ""}, + new Object[] {new OrderFilter(), PERFECT_ORDER, ""}, + new Object[] {new OrderFilter(), WRONG_NAME, ""}, + new Object[] {new OrderFilter(), WRONG_CONTACT, ""}, + new Object[] {new OrderFilter(), WRONG_ADDRESS, ""}, + new Object[] {new OrderFilter(), WRONG_DEPOSIT, ""}, + new Object[] {new OrderFilter(), WRONG_ORDER, "Invalid order!"}); } @ParameterizedTest @MethodSource("getTestData") - public void testExecute(Filter filter, Order order, String expectedResult) throws Exception { - final String result = filter.execute(order); + void testExecute(Filter filter, Order order, String expectedResult) { + final var result = filter.execute(order); assertNotNull(result); assertEquals(expectedResult, result.trim()); } @ParameterizedTest @MethodSource("getTestData") - public void testNext(Filter filter) throws Exception { + void testNext(Filter filter) { assertNull(filter.getNext()); assertSame(filter, filter.getLast()); } - } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java index 3b03e45998a6..3cb6ed3c8acf 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,52 +24,47 @@ */ package com.iluwatar.intercepting.filter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Date: 12/13/15 - 2:57 PM - * - * @author Jeroen Meulemeester - */ -public class OrderTest { +import org.junit.jupiter.api.Test; + +/** OrderTest */ +class OrderTest { private static final String EXPECTED_VALUE = "test"; @Test - public void testSetName() throws Exception { - final Order order = new Order(); + void testSetName() { + final var order = new Order(); order.setName(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getName()); } @Test - public void testSetContactNumber() throws Exception { - final Order order = new Order(); + void testSetContactNumber() { + final var order = new Order(); order.setContactNumber(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getContactNumber()); } @Test - public void testSetAddress() throws Exception { - final Order order = new Order(); + void testSetAddress() { + final var order = new Order(); order.setAddress(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getAddress()); } @Test - public void testSetDepositNumber() throws Exception { - final Order order = new Order(); + void testSetDepositNumber() { + final var order = new Order(); order.setDepositNumber(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getDepositNumber()); } @Test - public void testSetOrder() throws Exception { - final Order order = new Order(); + void testSetOrder() { + final var order = new Order(); order.setOrderItem(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getOrderItem()); } - } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/TargetTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/TargetTest.java new file mode 100644 index 000000000000..c202020f7f55 --- /dev/null +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/TargetTest.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.intercepting.filter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** TargetTest */ +class TargetTest { + + @Test + void testSetup() { + final var target = new Target(); + assertEquals(target.getSize().getWidth(), Double.valueOf(640)); + assertEquals(target.getSize().getHeight(), Double.valueOf(480)); + assertTrue(target.isVisible()); + } +} diff --git a/interpreter/README.md b/interpreter/README.md index be65179627c9..9e9dd54397f8 100644 --- a/interpreter/README.md +++ b/interpreter/README.md @@ -1,37 +1,217 @@ --- -layout: pattern -title: Interpreter -folder: interpreter -permalink: /patterns/interpreter/ -categories: Behavioral -tags: - - Java - - Gang Of Four - - Difficulty-Intermediate +title: "Interpreter Pattern in Java: Building Custom Parsers for Java Applications" +shortTitle: Interpreter +description: "Explore the Interpreter Design Pattern in Java with real-world examples, class diagrams, and step-by-step implementation. Learn when and how to use this powerful behavioral pattern." +category: Behavioral +language: en +tag: + - Abstraction + - Data transformation + - Decoupling + - Domain + - Gang of Four + - Polymorphism + - Runtime --- -## Intent -Given a language, define a representation for its grammar along -with an interpreter that uses the representation to interpret sentences in the -language. +## Intent of Interpreter Design Pattern -![alt text](./etc/interpreter_1.png "Interpreter") +The Interpreter design pattern is used to define a grammatical representation for a language and provides an interpreter to handle this grammar. This pattern is useful in scenarios where a specific set of rules or grammar needs to be interpreted and acted upon, such as in arithmetic expressions or scripting languages. -## Applicability -Use the Interpreter pattern when there is a language to -interpret, and you can represent statements in the language as abstract syntax -trees. The Interpreter pattern works best when +## Detailed Explanation of Interpreter Pattern with Real-World Examples -* the grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases. They can interpret expressions without building abstract syntax trees, which can save space and possibly time -* efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable +Real-world example + +> Consider a calculator application designed to interpret and calculate expressions entered by users. The application uses the Interpreter pattern in Java to parse and evaluate arithmetic expressions such as "5 + 3 * 2". Here, the Interpreter translates each part of the expression into objects that represent numbers and operations. These objects follow a defined grammar that allows the application to understand and compute the result correctly based on the rules of arithmetic. Each element of the expression corresponds to a class in the program's structure, simplifying the parsing and evaluation process for any inputted arithmetic formula. + +In plain words + +> The Interpreter design pattern defines a representation for a language's grammar along with an interpreter that uses the representation to interpret sentences in the language. + +Wikipedia says + +> In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client. + +Sequence diagram + +![Interpreter sequence diagram](./etc/interpreter-sequence-diagram.png) + +## Programmatic Example of Interpreter Pattern in Java + +To be able to interpret basic math in Java, we need a hierarchy of expressions. The `Expression` class is the base, and concrete implementations like `NumberExpression` handle specific parts of the grammar. The Interpreter pattern in Java simplifies parsing and evaluating arithmetic expressions by translating them into a structured format that the application can process. + +```java +public abstract class Expression { + + public abstract int interpret(); + + @Override + public abstract String toString(); +} +``` + +The simplest of the expressions is the `NumberExpression` that contains only a single integer number. + +```java +public class NumberExpression extends Expression { + + private final int number; + + public NumberExpression(int number) { + this.number = number; + } + + public NumberExpression(String s) { + this.number = Integer.parseInt(s); + } + + @Override + public int interpret() { + return number; + } + + @Override + public String toString() { + return "number"; + } +} +``` + +The more complex expressions are operations such as `PlusExpression`, `MinusExpression`, and `MultiplyExpression`. Here's the first of them, the others are similar. + +```java +public class PlusExpression extends Expression { + + private final Expression leftExpression; + private final Expression rightExpression; + + public PlusExpression(Expression leftExpression, Expression rightExpression) { + this.leftExpression = leftExpression; + this.rightExpression = rightExpression; + } + + @Override + public int interpret() { + return leftExpression.interpret() + rightExpression.interpret(); + } + + @Override + public String toString() { + return "+"; + } +} +``` + +Now, we are able to show the interpreter pattern in action parsing some simple math. + +```java +@Slf4j +public class App { + + public static void main(String[] args) { + + // the halfling kids are learning some basic math at school + // define the math string we want to parse + final var tokenString = "4 3 2 - 1 + *"; + + // the stack holds the parsed expressions + var stack = new Stack(); + + // tokenize the string and go through them one by one + var tokenList = tokenString.split(" "); + for (var s : tokenList) { + if (isOperator(s)) { + // when an operator is encountered we expect that the numbers can be popped from the top of + // the stack + var rightExpression = stack.pop(); + var leftExpression = stack.pop(); + LOGGER.info("popped from stack left: {} right: {}", + leftExpression.interpret(), rightExpression.interpret()); + var operator = getOperatorInstance(s, leftExpression, rightExpression); + LOGGER.info("operator: {}", operator); + var result = operator.interpret(); + // the operation result is pushed on top of the stack + var resultExpression = new NumberExpression(result); + stack.push(resultExpression); + LOGGER.info("push result to stack: {}", resultExpression.interpret()); + } else { + // numbers are pushed on top of the stack + var i = new NumberExpression(s); + stack.push(i); + LOGGER.info("push to stack: {}", i.interpret()); + } + } + // in the end, the final result lies on top of the stack + LOGGER.info("result: {}", stack.pop().interpret()); + } + + public static boolean isOperator(String s) { + return s.equals("+") || s.equals("-") || s.equals("*"); + } + + public static Expression getOperatorInstance(String s, Expression left, Expression right) { + return switch (s) { + case "+" -> new PlusExpression(left, right); + case "-" -> new MinusExpression(left, right); + default -> new MultiplyExpression(left, right); + }; + } +} + ``` + +Executing the program produces the following console output. + +``` +13:33:15.437 [main] INFO com.iluwatar.interpreter.App -- push to stack: 4 +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push to stack: 3 +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push to stack: 2 +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- popped from stack left: 3 right: 2 +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- operator: - +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push result to stack: 1 +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push to stack: 1 +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- popped from stack left: 1 right: 1 +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- operator: + +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push result to stack: 2 +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- popped from stack left: 4 right: 2 +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- operator: * +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push result to stack: 8 +13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- result: 8 +``` + +## When to Use the Interpreter Pattern in Java + +Use the Interpreter design pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when + +* The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases. They can interpret expressions without building abstract syntax trees, which can save space and possibly time. +* Efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable. + +## Real-World Applications of Interpreter Pattern in Java -## Real world examples * [java.util.Pattern](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) * [java.text.Normalizer](http://docs.oracle.com/javase/8/docs/api/java/text/Normalizer.html) * All subclasses of [java.text.Format](http://docs.oracle.com/javase/8/docs/api/java/text/Format.html) * [javax.el.ELResolver](http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html) +* SQL parsers in various database management systems. + +## Benefits and Trade-offs of Interpreter Pattern + +Benefits: + +* Adds new operations to interpret expressions easily without changing the grammar or classes of data. +* Implements grammar directly in the language, making it easy to modify or extend. + +Trade-offs: + +* Can become complex and inefficient for large grammars. +* Each rule in the grammar results in a class, leading to a large number of classes for complex grammars. + +## Related Java Design Patterns +* [Composite](https://java-design-patterns.com/patterns/composite/): Often used together, where the Interpreter pattern leverages the Composite pattern to represent the grammar as a tree structure. +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Useful for sharing state to reduce memory usage in the Interpreter pattern, particularly for interpreters that deal with repetitive elements in a language. -## Credits +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/interpreter/etc/interpreter-sequence-diagram.png b/interpreter/etc/interpreter-sequence-diagram.png new file mode 100644 index 000000000000..fbee04524724 Binary files /dev/null and b/interpreter/etc/interpreter-sequence-diagram.png differ diff --git a/interpreter/etc/interpreter.urm.puml b/interpreter/etc/interpreter.urm.puml new file mode 100644 index 000000000000..e79ad1989588 --- /dev/null +++ b/interpreter/etc/interpreter.urm.puml @@ -0,0 +1,51 @@ +@startuml +package com.iluwatar.interpreter { + class App { + - LOGGER : Logger {static} + + App() + + getOperatorInstance(s : String, left : Expression, right : Expression) : Expression {static} + + isOperator(s : String) : boolean {static} + + main(args : String[]) {static} + } + abstract class Expression { + + Expression() + + interpret() : int {abstract} + + toString() : String {abstract} + } + class MinusExpression { + - leftExpression : Expression + - rightExpression : Expression + + MinusExpression(leftExpression : Expression, rightExpression : Expression) + + interpret() : int + + toString() : String + } + class MultiplyExpression { + - leftExpression : Expression + - rightExpression : Expression + + MultiplyExpression(leftExpression : Expression, rightExpression : Expression) + + interpret() : int + + toString() : String + } + class NumberExpression { + - number : int + + NumberExpression(number : int) + + NumberExpression(s : String) + + interpret() : int + + toString() : String + } + class PlusExpression { + - leftExpression : Expression + - rightExpression : Expression + + PlusExpression(leftExpression : Expression, rightExpression : Expression) + + interpret() : int + + toString() : String + } +} +MultiplyExpression --> "-leftExpression" Expression +MinusExpression --> "-leftExpression" Expression +PlusExpression --> "-leftExpression" Expression +MinusExpression --|> Expression +MultiplyExpression --|> Expression +NumberExpression --|> Expression +PlusExpression --|> Expression +@enduml \ No newline at end of file diff --git a/interpreter/pom.xml b/interpreter/pom.xml index 1e61dfb487fd..86c45ce224b2 100644 --- a/interpreter/pom.xml +++ b/interpreter/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT interpreter - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.interpreter.App + + + + + + + + diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/App.java b/interpreter/src/main/java/com/iluwatar/interpreter/App.java index 7404f9757bf3..7f0c0b2444b2 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/App.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,79 +24,91 @@ */ package com.iluwatar.interpreter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Stack; +import lombok.extern.slf4j.Slf4j; /** - * * The Interpreter pattern is a design pattern that specifies how to evaluate sentences in a * language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a * specialized computer language. The syntax tree of a sentence in the language is an instance of * the composite pattern and is used to evaluate (interpret) the sentence for a client. - *

    - * In this example we use the Interpreter pattern to break sentences into expressions ( - * {@link Expression}) that can be evaluated and as a whole form the result. - * + * + *

    In this example we use the Interpreter pattern to break sentences into expressions ({@link + * Expression}) that can be evaluated and as a whole form the result. + * + *

    Expressions can be evaluated using prefix, infix or postfix notations This sample uses + * postfix, where operator comes after the operands. */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * * Program entry point. - *

    - * Expressions can be evaluated using prefix, infix or postfix notations This sample uses postfix, - * where operator comes after the operands - * - * @param args command line args - * + * + * @param args program arguments */ public static void main(String[] args) { - String tokenString = "4 3 2 - 1 + *"; - Stack stack = new Stack<>(); - String[] tokenList = tokenString.split(" "); - for (String s : tokenList) { + // the halfling kids are learning some basic math at school + // define the math string we want to parse + final var tokenString = "4 3 2 - 1 + *"; + + // the stack holds the parsed expressions + var stack = new Stack(); + + // tokenize the string and go through them one by one + var tokenList = tokenString.split(" "); + for (var s : tokenList) { if (isOperator(s)) { - Expression rightExpression = stack.pop(); - Expression leftExpression = stack.pop(); - LOGGER.info("popped from stack left: {} right: {}", - leftExpression.interpret(), rightExpression.interpret()); - Expression operator = getOperatorInstance(s, leftExpression, rightExpression); + // when an operator is encountered we expect that the numbers can be popped from the top of + // the stack + var rightExpression = stack.pop(); + var leftExpression = stack.pop(); + LOGGER.info( + "popped from stack left: {} right: {}", + leftExpression.interpret(), + rightExpression.interpret()); + var operator = getOperatorInstance(s, leftExpression, rightExpression); LOGGER.info("operator: {}", operator); - int result = operator.interpret(); - NumberExpression resultExpression = new NumberExpression(result); + var result = operator.interpret(); + // the operation result is pushed on top of the stack + var resultExpression = new NumberExpression(result); stack.push(resultExpression); LOGGER.info("push result to stack: {}", resultExpression.interpret()); } else { - Expression i = new NumberExpression(s); + // numbers are pushed on top of the stack + var i = new NumberExpression(s); stack.push(i); LOGGER.info("push to stack: {}", i.interpret()); } } + // in the end, the final result lies on top of the stack LOGGER.info("result: {}", stack.pop().interpret()); } + /** + * Checks whether the input parameter is an operator. + * + * @param s input string + * @return true if the input parameter is an operator + */ public static boolean isOperator(String s) { return s.equals("+") || s.equals("-") || s.equals("*"); } /** - * Get expression for string + * Returns correct expression based on the parameters. + * + * @param s input string + * @param left expression + * @param right expression + * @return expression */ public static Expression getOperatorInstance(String s, Expression left, Expression right) { - switch (s) { - case "+": - return new PlusExpression(left, right); - case "-": - return new MinusExpression(left, right); - case "*": - return new MultiplyExpression(left, right); - default: - return new MultiplyExpression(left, right); - } + return switch (s) { + case "+" -> new PlusExpression(left, right); + case "-" -> new MinusExpression(left, right); + default -> new MultiplyExpression(left, right); + }; } } diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java b/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java index bea4d40517b4..44b4ea278b0c 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.interpreter; -/** - * - * Expression - * - */ +/** Expression. */ public abstract class Expression { public abstract int interpret(); diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java index b3f2299c34ad..c6d7f55812f1 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,15 +24,11 @@ */ package com.iluwatar.interpreter; -/** - * - * MinusExpression - * - */ +/** MinusExpression. */ public class MinusExpression extends Expression { - private Expression leftExpression; - private Expression rightExpression; + private final Expression leftExpression; + private final Expression rightExpression; public MinusExpression(Expression leftExpression, Expression rightExpression) { this.leftExpression = leftExpression; @@ -46,5 +44,4 @@ public int interpret() { public String toString() { return "-"; } - } diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java index 809b5331cf53..a5c1efe4fb63 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,15 +24,11 @@ */ package com.iluwatar.interpreter; -/** - * - * MultiplyExpression - * - */ +/** MultiplyExpression. */ public class MultiplyExpression extends Expression { - private Expression leftExpression; - private Expression rightExpression; + private final Expression leftExpression; + private final Expression rightExpression; public MultiplyExpression(Expression leftExpression, Expression rightExpression) { this.leftExpression = leftExpression; @@ -46,5 +44,4 @@ public int interpret() { public String toString() { return "*"; } - } diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java index 2309d3190be9..31a632c3469a 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,14 +24,10 @@ */ package com.iluwatar.interpreter; -/** - * - * NumberExpression - * - */ +/** NumberExpression. */ public class NumberExpression extends Expression { - private int number; + private final int number; public NumberExpression(int number) { this.number = number; diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java index 56c68b9db0bf..4109f397d8ef 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,15 +24,11 @@ */ package com.iluwatar.interpreter; -/** - * - * PlusExpression - * - */ +/** PlusExpression. */ public class PlusExpression extends Expression { - private Expression leftExpression; - private Expression rightExpression; + private final Expression leftExpression; + private final Expression rightExpression; public PlusExpression(Expression leftExpression, Expression rightExpression) { this.leftExpression = leftExpression; diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java index 547c0fa13f0e..4c72970c9742 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.interpreter; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java index a9a4f11d8968..80d76416e43d 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,27 +24,22 @@ */ package com.iluwatar.interpreter; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; -import java.util.List; import java.util.function.BiFunction; import java.util.function.IntBinaryOperator; import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** - * Date: 12/14/15 - 11:48 AM - * * Test Case for Expressions + * * @param Type of Expression - * @author Jeroen Meulemeester */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public abstract class ExpressionTest { @@ -54,22 +51,18 @@ public abstract class ExpressionTest { * @return A stream with test entries */ static Stream prepareParameters(final IntBinaryOperator resultCalc) { - final List testData = new ArrayList<>(); - for (int i = -10; i < 10; i++) { - for (int j = -10; j < 10; j++) { - testData.add(Arguments.of( - new NumberExpression(i), - new NumberExpression(j), - resultCalc.applyAsInt(i, j) - )); + final var testData = new ArrayList(); + for (var i = -10; i < 10; i++) { + for (var j = -10; j < 10; j++) { + testData.add( + Arguments.of( + new NumberExpression(i), new NumberExpression(j), resultCalc.applyAsInt(i, j))); } } return testData.stream(); } - /** - * The expected {@link E#toString()} response - */ + /** The expected {@link E#toString()} response */ private final String expectedToString; /** @@ -81,11 +74,11 @@ static Stream prepareParameters(final IntBinaryOperator resultCalc) { * Create a new test instance with the given parameters and expected results * * @param expectedToString The expected {@link E#toString()} response - * @param factory Factory, used to create a new test object instance + * @param factory Factory, used to create a new test object instance */ - ExpressionTest(final String expectedToString, - final BiFunction factory - ) { + ExpressionTest( + final String expectedToString, + final BiFunction factory) { this.expectedToString = expectedToString; this.factory = factory; } @@ -97,24 +90,20 @@ static Stream prepareParameters(final IntBinaryOperator resultCalc) { */ public abstract Stream expressionProvider(); - /** - * Verify if the expression calculates the correct result when calling {@link E#interpret()} - */ + /** Verify if the expression calculates the correct result when calling {@link E#interpret()} */ @ParameterizedTest @MethodSource("expressionProvider") - public void testInterpret(NumberExpression first, NumberExpression second, int result) { - final E expression = factory.apply(first, second); + void testInterpret(NumberExpression first, NumberExpression second, int result) { + final var expression = factory.apply(first, second); assertNotNull(expression); assertEquals(result, expression.interpret()); } - /** - * Verify if the expression has the expected {@link E#toString()} value - */ + /** Verify if the expression has the expected {@link E#toString()} value */ @ParameterizedTest @MethodSource("expressionProvider") - public void testToString(NumberExpression first, NumberExpression second) { - final E expression = factory.apply(first, second); + void testToString(NumberExpression first, NumberExpression second) { + final var expression = factory.apply(first, second); assertNotNull(expression); assertEquals(expectedToString, expression.toString()); } diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java index 276b934c37d3..d773a89707a6 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,16 +24,11 @@ */ package com.iluwatar.interpreter; +import java.util.stream.Stream; import org.junit.jupiter.params.provider.Arguments; -import java.util.stream.Stream; - -/** - * Date: 12/14/15 - 12:08 PM - * - * @author Jeroen Meulemeester - */ -public class MinusExpressionTest extends ExpressionTest { +/** MinusExpressionTest */ +class MinusExpressionTest extends ExpressionTest { /** * Create a new set of test entries with the expected result @@ -43,11 +40,8 @@ public Stream expressionProvider() { return prepareParameters((f, s) -> f - s); } - /** - * Create a new test instance using the given test parameters and expected result - */ + /** Create a new test instance using the given test parameters and expected result */ public MinusExpressionTest() { super("-", MinusExpression::new); } - -} \ No newline at end of file +} diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java index e5f4e61ee261..6d73341a3f93 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,16 +24,11 @@ */ package com.iluwatar.interpreter; -import org.junit.jupiter.params.provider.Arguments; - import java.util.stream.Stream; +import org.junit.jupiter.params.provider.Arguments; -/** - * Date: 12/14/15 - 12:08 PM - * - * @author Jeroen Meulemeester - */ -public class MultiplyExpressionTest extends ExpressionTest { +/** MultiplyExpressionTest */ +class MultiplyExpressionTest extends ExpressionTest { /** * Create a new set of test entries with the expected result @@ -43,12 +40,8 @@ public Stream expressionProvider() { return prepareParameters((f, s) -> f * s); } - /** - * Create a new test instance using the given test parameters and expected result - * - */ + /** Create a new test instance using the given test parameters and expected result */ public MultiplyExpressionTest() { super("*", MultiplyExpression::new); } - -} \ No newline at end of file +} diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java index cc7c82e7ed7c..9d917c03abcb 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,15 @@ */ package com.iluwatar.interpreter; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Date: 12/14/15 - 12:08 PM - * - * @author Jeroen Meulemeester - */ -public class NumberExpressionTest extends ExpressionTest { +/** NumberExpressionTest */ +class NumberExpressionTest extends ExpressionTest { /** * Create a new set of test entries with the expected result @@ -47,9 +44,7 @@ public Stream expressionProvider() { return prepareParameters((f, s) -> f); } - /** - * Create a new test instance using the given test parameters and expected result - */ + /** Create a new test instance using the given test parameters and expected result */ public NumberExpressionTest() { super("number", (f, s) -> f); } @@ -59,11 +54,10 @@ public NumberExpressionTest() { */ @ParameterizedTest @MethodSource("expressionProvider") - public void testFromString(NumberExpression first) throws Exception { - final int expectedValue = first.interpret(); - final String testStringValue = String.valueOf(expectedValue); - final NumberExpression numberExpression = new NumberExpression(testStringValue); + void testFromString(NumberExpression first) { + final var expectedValue = first.interpret(); + final var testStringValue = String.valueOf(expectedValue); + final var numberExpression = new NumberExpression(testStringValue); assertEquals(expectedValue, numberExpression.interpret()); } - -} \ No newline at end of file +} diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java index 9687b5399a02..a93f27c84abd 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,16 +24,11 @@ */ package com.iluwatar.interpreter; +import java.util.stream.Stream; import org.junit.jupiter.params.provider.Arguments; -import java.util.stream.Stream; - -/** - * Date: 12/14/15 - 12:08 PM - * - * @author Jeroen Meulemeester - */ -public class PlusExpressionTest extends ExpressionTest { +/** PlusExpressionTest */ +class PlusExpressionTest extends ExpressionTest { /** * Create a new set of test entries with the expected result @@ -40,14 +37,11 @@ public class PlusExpressionTest extends ExpressionTest { */ @Override public Stream expressionProvider() { - return prepareParameters((f, s) -> f + s); + return prepareParameters(Integer::sum); } - /** - * Create a new test instance using the given test parameters and expected result - */ + /** Create a new test instance using the given test parameters and expected result */ public PlusExpressionTest() { super("+", PlusExpression::new); } - -} \ No newline at end of file +} diff --git a/iterator/README.md b/iterator/README.md index 723e7f03cd20..bda2afde9e6e 100644 --- a/iterator/README.md +++ b/iterator/README.md @@ -1,36 +1,256 @@ --- -layout: pattern -title: Iterator -folder: iterator -permalink: /patterns/iterator/ -categories: Behavioral -tags: - - Java - - Difficulty-Beginner - - Gang Of Four +title: "Iterator Pattern in Java: Mastering Sequential Element Access" +shortTitle: Iterator +description: "Learn how to implement the Iterator Design Pattern in Java. Access elements of a collection sequentially without exposing its underlying structure. Explore real-world examples, code snippets, and benefits of using iterators." +category: Behavioral +language: en +tag: + - Data access + - Data transformation + - Decoupling + - Gang of Four + - Object composition + - Polymorphism --- ## Also known as -Cursor -## Intent -Provide a way to access the elements of an aggregate object -sequentially without exposing its underlying representation. +* Cursor -![alt text](./etc/iterator_1.png "Iterator") +## Intent of Iterator Design Pattern -## Applicability -Use the Iterator pattern +The Iterator Design Pattern in Java provides a way to access elements of an aggregate object sequentially without exposing its underlying representation. This behavioral pattern is crucial for efficient collection traversal. -* to access an aggregate object's contents without exposing its internal representation -* to support multiple traversals of aggregate objects -* to provide a uniform interface for traversing different aggregate structures +## Detailed Explanation of Iterator Pattern with Real-World Examples -## Real world examples +Real-world example +> Imagine visiting a library with a vast collection of books organized in different sections such as fiction, non-fiction, science, etc. Instead of searching through every shelf yourself, the librarian provides you with a specific guidebook or a digital catalog for each section. This guidebook acts as an "iterator," allowing you to go through the books section by section, or even skip to specific types of books, without needing to know how the books are organized on the shelves. Each guidebook handles the traversal through its section, providing a consistent and efficient way to access the books, much like how the Iterator design pattern offers a uniform method to traverse different data structures in a software application. + +In plain words + +> The Java Iterator Design Pattern provides a method to sequentially access elements of a collection without exposing its underlying structure. This pattern is widely used in Java programming for efficient data access. + +Wikipedia says + +> In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. + +Sequence diagram + +![Iterator sequence diagram](./etc/iterator-sequence-diagram.png) + +## Programmatic Example of Iterator Pattern in Java + +The main class in our Java Iterator Design Pattern example is the `TreasureChest` that contains items. This demonstrates how to implement and use iterators for efficient collection traversal in Java. + +```java +public class TreasureChest { + + private final List items; + + public TreasureChest() { + items = List.of( + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); + } + + public Iterator iterator(ItemType itemType) { + return new TreasureChestItemIterator(this, itemType); + } + + public List getItems() { + return new ArrayList<>(items); + } +} +``` + +Here's the `Item` class: + +```java +public class Item { + + private ItemType type; + private final String name; + + public Item(ItemType type, String name) { + this.setType(type); + this.name = name; + } + + @Override + public String toString() { + return name; + } + + public ItemType getType() { + return type; + } + + public final void setType(ItemType type) { + this.type = type; + } +} + +public enum ItemType { + + ANY, WEAPON, RING, POTION + +} +``` + +The `Iterator` interface is extremely simple. + +```java +public interface Iterator { + + boolean hasNext(); + + T next(); +} +``` + +In the following example, we demonstrate different kinds of iterators. + +```java +@Slf4j +public class App { + + private static final TreasureChest TREASURE_CHEST = new TreasureChest(); + + private static void demonstrateTreasureChestIteratorForType(ItemType itemType) { + LOGGER.info("------------------------"); + LOGGER.info("Item Iterator for ItemType " + itemType + ": "); + var itemIterator = TREASURE_CHEST.iterator(itemType); + while (itemIterator.hasNext()) { + LOGGER.info(itemIterator.next().toString()); + } + } + + private static void demonstrateBstIterator() { + LOGGER.info("------------------------"); + LOGGER.info("BST Iterator: "); + var root = buildIntegerBst(); + var bstIterator = new BstIterator<>(root); + while (bstIterator.hasNext()) { + LOGGER.info("Next node: " + bstIterator.next().getVal()); + } + } + + private static TreeNode buildIntegerBst() { + var root = new TreeNode<>(8); + + root.insert(3); + root.insert(10); + root.insert(1); + root.insert(6); + root.insert(14); + root.insert(4); + root.insert(7); + root.insert(13); + + return root; + } + + public static void main(String[] args) { + demonstrateTreasureChestIteratorForType(RING); + demonstrateTreasureChestIteratorForType(POTION); + demonstrateTreasureChestIteratorForType(WEAPON); + demonstrateTreasureChestIteratorForType(ANY); + demonstrateBstIterator(); + } +} +``` + +Program output: + +``` +13:36:37.087 [main] INFO com.iluwatar.iterator.App -- ------------------------ +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType RING: +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of shadows +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of armor +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- ------------------------ +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType POTION: +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of courage +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of wisdom +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of blood +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of rust +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of healing +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- ------------------------ +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType WEAPON: +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Sword of silver +1 +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Steel halberd +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Dagger of poison +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- ------------------------ +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType ANY: +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of courage +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of shadows +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of wisdom +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of blood +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Sword of silver +1 +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of rust +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of healing +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of armor +13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Steel halberd +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Dagger of poison +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- ------------------------ +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- BST Iterator: +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 1 +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 3 +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 4 +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 6 +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 7 +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 8 +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 10 +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 13 +13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 14 +``` + +## When to Use the Iterator Pattern in Java + +Use the Iterator design pattern in Java + +* To access an aggregate object's contents without exposing its internal representation. +* To support multiple traversals of aggregate objects. +* To provide a uniform interface for traversing different aggregate structures. + +## Iterator Pattern Java Tutorials + +* [Java - How to Use Iterator? (TutorialsPoint)](http://www.tutorialspoint.com/java/java_using_iterator.htm) + +## Real-World Applications of Iterator Pattern in Java + +* Java Collections Framework utilizes iterators extensively to allow different ways to traverse through collections. +* Databases often use iterators to navigate through data records fetched through SQL queries. * [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html) * [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html) -## Credits +## Benefits and Trade-offs of Iterator Pattern + +Benefits: + +* Reduces the coupling between data structures and algorithms used for iteration. +* Provides a uniform interface for iterating over various types of data structures, enhancing code reusability and flexibility. + +Trade-offs: + +* Overhead of using an iterator object may slightly reduce performance compared to direct traversal methods. +* Complex aggregate structures may require complex iterators that can be difficult to manage or extend. + +## Related Java Design Patterns + +* [Composite](https://java-design-patterns.com/patterns/composite/): Iterators are often used to traverse Composite trees. +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Used to create appropriate iterators for different data structures. +* [Visitor](https://java-design-patterns.com/patterns/visitor/): Can be used with Iterator to apply operations over elements of an object structure. + +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/iterator/etc/bst.jpg b/iterator/etc/bst.jpg new file mode 100644 index 000000000000..f7ed6af8271e Binary files /dev/null and b/iterator/etc/bst.jpg differ diff --git a/iterator/etc/iterator-sequence-diagram.png b/iterator/etc/iterator-sequence-diagram.png new file mode 100644 index 000000000000..ce887054c132 Binary files /dev/null and b/iterator/etc/iterator-sequence-diagram.png differ diff --git a/iterator/etc/iterator.ucls b/iterator/etc/iterator.ucls index 440f9a28bb00..d36dad95d48b 100644 --- a/iterator/etc/iterator.ucls +++ b/iterator/etc/iterator.ucls @@ -1,7 +1,7 @@ - - - - - diff --git a/iterator/etc/iterator.urm.puml b/iterator/etc/iterator.urm.puml new file mode 100644 index 000000000000..59cb93be26b6 --- /dev/null +++ b/iterator/etc/iterator.urm.puml @@ -0,0 +1,85 @@ +@startuml +package com.iluwatar.iterator { + class App { + - LOGGER : Logger {static} + - TREASURE_CHEST : TreasureChest {static} + + App() + - buildIntegerBst() : TreeNode {static} + - demonstrateBstIterator() {static} + - demonstrateTreasureChestIteratorForType(itemType : ItemType) {static} + + main(args : String[]) {static} + } + interface Iterator { + + hasNext() : boolean {abstract} + + next() : T {abstract} + } +} +package com.iluwatar.iterator.bst { + class BstIterator> { + - pathStack : ArrayDeque>> + + BstIterator>(root : TreeNode>) + + hasNext() : boolean + + next() : TreeNode> + - pushPathToNextSmallest(node : TreeNode>) + } + class TreeNode> { + - left : TreeNode> + - right : TreeNode> + - val : T extends Comparable + + TreeNode>(val : T extends Comparable) + + getLeft() : TreeNode> + - getParentNodeOfValueToBeInserted(valToInsert : T extends Comparable) : TreeNode> + + getRight() : TreeNode> + + getVal() : T extends Comparable + + insert(valToInsert : T extends Comparable) + - insertNewChild(valToInsert : T extends Comparable) + - isGreaterThan(val : T extends Comparable) : boolean + - isLessThanOrEqualTo(val : T extends Comparable) : boolean + - setLeft(left : TreeNode>) + - setRight(right : TreeNode>) + + toString() : String + - traverseOneLevelDown(value : T extends Comparable) : TreeNode> + } +} +package com.iluwatar.iterator.list { + class Item { + - name : String + - type : ItemType + + Item(type : ItemType, name : String) + + getType() : ItemType + + setType(type : ItemType) + + toString() : String + } + enum ItemType { + + ANY {static} + + POTION {static} + + RING {static} + + WEAPON {static} + + valueOf(name : String) : ItemType {static} + + values() : ItemType[] {static} + } + class TreasureChest { + - items : List + + TreasureChest() + + getItems() : List + + iterator(itemType : ItemType) : Iterator + } + class TreasureChestItemIterator { + - chest : TreasureChest + - idx : int + - type : ItemType + + TreasureChestItemIterator(chest : TreasureChest, type : ItemType) + - findNextIdx() : int + + hasNext() : boolean + + next() : Item + } +} +TreasureChestItemIterator --> "-type" ItemType +TreeNode --> "-left" TreeNode +TreasureChestItemIterator --> "-chest" TreasureChest +TreasureChest --> "-items" Item +Item --> "-type" ItemType +App --> "-TREASURE_CHEST" TreasureChest +BstIterator ..|> Iterator +TreasureChestItemIterator ..|> Iterator +@enduml \ No newline at end of file diff --git a/iterator/pom.xml b/iterator/pom.xml index 6581b8224003..4578eed1baa0 100644 --- a/iterator/pom.xml +++ b/iterator/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT iterator - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.iterator.App + + + + + + + + diff --git a/iterator/src/main/java/com/iluwatar/iterator/App.java b/iterator/src/main/java/com/iluwatar/iterator/App.java index d283347cba23..c7221ae0d813 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/App.java +++ b/iterator/src/main/java/com/iluwatar/iterator/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,55 +24,75 @@ */ package com.iluwatar.iterator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static com.iluwatar.iterator.list.ItemType.ANY; +import static com.iluwatar.iterator.list.ItemType.POTION; +import static com.iluwatar.iterator.list.ItemType.RING; +import static com.iluwatar.iterator.list.ItemType.WEAPON; + +import com.iluwatar.iterator.bst.BstIterator; +import com.iluwatar.iterator.bst.TreeNode; +import com.iluwatar.iterator.list.ItemType; +import com.iluwatar.iterator.list.TreasureChest; +import lombok.extern.slf4j.Slf4j; /** - * * The Iterator pattern is a design pattern in which an iterator is used to traverse a container and * access the container's elements. The Iterator pattern decouples algorithms from containers. - *

    - * In this example the Iterator ({@link ItemIterator}) adds abstraction layer on top of a collection + * + *

    In this example the Iterator ({@link Iterator}) adds abstraction layer on top of a collection * ({@link TreasureChest}). This way the collection can change its internal implementation without * affecting its clients. - * */ +@Slf4j 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) { - TreasureChest chest = new TreasureChest(); + private static final TreasureChest TREASURE_CHEST = new TreasureChest(); - ItemIterator ringIterator = chest.iterator(ItemType.RING); - while (ringIterator.hasNext()) { - LOGGER.info(ringIterator.next().toString()); + private static void demonstrateTreasureChestIteratorForType(ItemType itemType) { + LOGGER.info("------------------------"); + LOGGER.info("Item Iterator for ItemType " + itemType + ": "); + var itemIterator = TREASURE_CHEST.iterator(itemType); + while (itemIterator.hasNext()) { + LOGGER.info(itemIterator.next().toString()); } + } - LOGGER.info("----------"); - - ItemIterator potionIterator = chest.iterator(ItemType.POTION); - while (potionIterator.hasNext()) { - LOGGER.info(potionIterator.next().toString()); + private static void demonstrateBstIterator() { + LOGGER.info("------------------------"); + LOGGER.info("BST Iterator: "); + var root = buildIntegerBst(); + var bstIterator = new BstIterator<>(root); + while (bstIterator.hasNext()) { + LOGGER.info("Next node: " + bstIterator.next().getVal()); } + } - LOGGER.info("----------"); + private static TreeNode buildIntegerBst() { + var root = new TreeNode<>(8); - ItemIterator weaponIterator = chest.iterator(ItemType.WEAPON); - while (weaponIterator.hasNext()) { - LOGGER.info(weaponIterator.next().toString()); - } + root.insert(3); + root.insert(10); + root.insert(1); + root.insert(6); + root.insert(14); + root.insert(4); + root.insert(7); + root.insert(13); - LOGGER.info("----------"); + return root; + } - ItemIterator it = chest.iterator(ItemType.ANY); - while (it.hasNext()) { - LOGGER.info(it.next().toString()); - } + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + demonstrateTreasureChestIteratorForType(RING); + demonstrateTreasureChestIteratorForType(POTION); + demonstrateTreasureChestIteratorForType(WEAPON); + demonstrateTreasureChestIteratorForType(ANY); + + demonstrateBstIterator(); } } diff --git a/iterator/src/main/java/com/iluwatar/iterator/Item.java b/iterator/src/main/java/com/iluwatar/iterator/Item.java deleted file mode 100644 index 47bc11354d43..000000000000 --- a/iterator/src/main/java/com/iluwatar/iterator/Item.java +++ /dev/null @@ -1,52 +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.iterator; - -/** - * - * Item - * - */ -public class Item { - - private ItemType type; - private String name; - - public Item(ItemType type, String name) { - this.setType(type); - this.name = name; - } - - @Override - public String toString() { - return name; - } - - public ItemType getType() { - return type; - } - - public final void setType(ItemType type) { - this.type = type; - } -} diff --git a/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java deleted file mode 100644 index 0eab2f075334..000000000000 --- a/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java +++ /dev/null @@ -1,35 +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.iterator; - -/** - * - * ItemIterator interface. - * - */ -public interface ItemIterator { - - boolean hasNext(); - - Item next(); -} diff --git a/iterator/src/main/java/com/iluwatar/iterator/Iterator.java b/iterator/src/main/java/com/iluwatar/iterator/Iterator.java new file mode 100644 index 000000000000..ed1e4a7c457e --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/Iterator.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.iterator; + +/** + * Iterator interface to be implemented by iterators over various data structures. + * + * @param generically typed for various objects + */ +public interface Iterator { + + boolean hasNext(); + + T next(); +} diff --git a/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java b/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java deleted file mode 100644 index 4b9959269fa3..000000000000 --- a/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java +++ /dev/null @@ -1,67 +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.iterator; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * TreasureChest, the collection class. - * - */ -public class TreasureChest { - - private List items; - - /** - * Constructor - */ - public TreasureChest() { - items = new ArrayList<>(); - items.add(new Item(ItemType.POTION, "Potion of courage")); - items.add(new Item(ItemType.RING, "Ring of shadows")); - items.add(new Item(ItemType.POTION, "Potion of wisdom")); - items.add(new Item(ItemType.POTION, "Potion of blood")); - items.add(new Item(ItemType.WEAPON, "Sword of silver +1")); - items.add(new Item(ItemType.POTION, "Potion of rust")); - items.add(new Item(ItemType.POTION, "Potion of healing")); - items.add(new Item(ItemType.RING, "Ring of armor")); - items.add(new Item(ItemType.WEAPON, "Steel halberd")); - items.add(new Item(ItemType.WEAPON, "Dagger of poison")); - } - - ItemIterator iterator(ItemType itemType) { - return new TreasureChestItemIterator(this, itemType); - } - - /** - * Get all items - */ - public List getItems() { - List list = new ArrayList<>(); - list.addAll(items); - return list; - } - -} diff --git a/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java b/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java new file mode 100644 index 000000000000..a027a286265f --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java @@ -0,0 +1,86 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.iterator.bst; + +import com.iluwatar.iterator.Iterator; +import java.util.ArrayDeque; +import java.util.NoSuchElementException; + +/** + * An in-order implementation of a BST Iterator. For example, given a BST with Integer values, + * expect to retrieve TreeNodes according to the Integer's natural ordering (1, 2, 3...) + * + * @param This Iterator has been implemented with generic typing to allow for TreeNodes of + * different value types + */ +public class BstIterator> implements Iterator> { + + private final ArrayDeque> pathStack; + + public BstIterator(TreeNode root) { + pathStack = new ArrayDeque<>(); + pushPathToNextSmallest(root); + } + + /** + * This BstIterator manages to use O(h) extra space, where h is the height of the tree It achieves + * this by maintaining a stack of the nodes to handle (pushing all left nodes first), before + * handling self or right node. + * + * @param node TreeNode that acts as root of the subtree we're interested in. + */ + private void pushPathToNextSmallest(TreeNode node) { + while (node != null) { + pathStack.push(node); + node = node.getLeft(); + } + } + + /** + * Checks if there exists next element. + * + * @return true if this iterator has a "next" element + */ + @Override + public boolean hasNext() { + return !pathStack.isEmpty(); + } + + /** + * Gets the next element. + * + * @return TreeNode next. The next element according to our in-order traversal of the given BST + * @throws NoSuchElementException if this iterator does not have a next element + */ + @Override + public TreeNode next() throws NoSuchElementException { + if (pathStack.isEmpty()) { + throw new NoSuchElementException(); + } + var next = pathStack.pop(); + pushPathToNextSmallest(next.getRight()); + return next; + } +} diff --git a/iterator/src/main/java/com/iluwatar/iterator/bst/README.md b/iterator/src/main/java/com/iluwatar/iterator/bst/README.md new file mode 100644 index 000000000000..07bcbf84f094 --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/bst/README.md @@ -0,0 +1,87 @@ +# BSTIterator + +An implementation of the Iterator design pattern, for the Binary Search Tree data structure. A great +explanation of BSTs can be found in this +[video tutorial](https://www.youtube.com/watch?v=i_Q0v_Ct5lY). + +### What It Does + +This iterator assumes that the given binary search tree inserts nodes of smaller +value to the left, and nodes of larger value to the right of current node. Accordingly, +this iterator will return nodes according to "In Order" binary tree traversal. +This means that given a binary search tree like the following, the iterator would +return values in order: 1, 3, 4, 6, 7, 8, 10, 13, 14. + +![BST](../../../../../../../etc/bst.jpg "Binary Search Tree") + +### How It's Done + +**The trivial solution** to a binary search tree iterator would be to construct a List (or similar +linear data structure) when you construct the BSTIterator. This would require traversing the entire +BST, adding each node value to your list as you go. The downside to the trivial solution is twofold. +You're front loading the work by requiring the BSTIterator's constructor to traverse the entire tree, +and you're taking up more memory by maintaining (worst case) every node in the tree in a separate +data structure. In Big O terms, here are the costs, where n is the number of nodes in the tree: +* Constructor Run Time: O(n) +* `next()` Run Time: O(1) +* `hasNext()` Run Time: O(1) +* Extra Space: O(n) + +**A better solution** is to maintain _only_ the path to the next smallest node. For instance, given +the BST above, when you first create your BSTIterator, instead of traversing the entire tree, you +would navigate to the next smallest node (in this case, 1), pushing nodes onto a stack along the way. +Your BSTIterator Constructor would look like: +``` +private ArrayDeque pathStack; + +public BSTIterator(TreeNode root) { + pathStack = new ArrayDeque<>(); + pushPathToNextSmallest(root); +} + +private void pushPathToNextSmallest(TreeNode node) { + while (node != null) { + pathStack.push(node); + node = node.getLeft(); + } +} +``` + +After the constructor is called our BST, your `pathStack` would look like this: + +1\ +3\ +8 + +This way, you're certain of what the next smallest node is because it lives on top of your path +stack. In order to maintain the integrity of this path stack, when you call `next()` and pop a +node off the stack, you must check to see if it has a right child. If it does, then you must follow the right +child's path to the next smallest node (pushing onto your path stack as you go). Given our above example, +calling `next()` on our BSTIterator twice would return node "3". Node "3" has a right child, indicating +a path to a node smaller than 3's parent. In this case, you would push node "6" onto the stack, +and node "4" onto the stack. `next()` would look like this: + +``` +public TreeNode next() throws IllegalStateException { + // If the user calls next() and hasNext() is false + if (pathStack.isEmpty()) { + throw new IllegalStateException(); + } + var next = pathStack.pop(); + // follow right child to next smallest node + pushPathToNextSmallest(next.getRight()); + return next; +} +``` + +**Key Concept:** The path to the smallest node of a given subtree is navigating straight to the +leftmost node of that subtree. + +In Big O terms, here are the costs for our improved solution, where h is the height of the tree: +* Constructor Run Time: O(h) +* `next()` Amortized Run Time: O(1) +* `hasNext()` Run Time: O(1) +* Extra Space: O(h) + +As you can see, this solution more evenly distributes the work. It yields the same amortized +runtime for `next()`, reduces the run time of the constructor, and uses less extra space. diff --git a/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java b/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java new file mode 100644 index 000000000000..a24f98d58bcd --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java @@ -0,0 +1,128 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.iterator.bst; + +import lombok.Getter; +import lombok.Setter; + +/** + * TreeNode Class, representing one node in a Binary Search Tree. Allows for a generically typed + * value. + * + * @param generically typed to accept various data types for the val property + */ +public class TreeNode> { + + private final T val; + + @Getter @Setter private TreeNode left; + + @Getter @Setter private TreeNode right; + + /** + * Creates a TreeNode with a given value, and null children. + * + * @param val The value of the given node + */ + public TreeNode(T val) { + this.val = val; + this.left = null; + this.right = null; + } + + public T getVal() { + return val; + } + + /** + * Inserts new TreeNode based on a given value into the subtree represented by self. + * + * @param valToInsert The value to insert as a new TreeNode + */ + public void insert(T valToInsert) { + var parent = getParentNodeOfValueToBeInserted(valToInsert); + parent.insertNewChild(valToInsert); + } + + /** + * Fetch the Parent TreeNode for a given value to insert into the BST. + * + * @param valToInsert Value of the new TreeNode to be inserted + * @return Parent TreeNode of `valToInsert` + */ + private TreeNode getParentNodeOfValueToBeInserted(T valToInsert) { + TreeNode parent = null; + var curr = this; + + while (curr != null) { + parent = curr; + curr = curr.traverseOneLevelDown(valToInsert); + } + + return parent; + } + + /** + * Returns left or right child of self based on a value that would be inserted; maintaining the + * integrity of the BST. + * + * @param value The value of the TreeNode that would be inserted beneath self + * @return The child TreeNode of self which represents the subtree where `value` would be inserted + */ + private TreeNode traverseOneLevelDown(T value) { + if (this.isGreaterThan(value)) { + return this.left; + } + return this.right; + } + + /** + * Add a new Child TreeNode of given value to self. WARNING: This method is destructive (will + * overwrite existing tree structure, if any), and should be called only by this class's insert() + * method. + * + * @param valToInsert Value of the new TreeNode to be inserted + */ + private void insertNewChild(T valToInsert) { + if (this.isLessThanOrEqualTo(valToInsert)) { + this.setRight(new TreeNode<>(valToInsert)); + } else { + this.setLeft(new TreeNode<>(valToInsert)); + } + } + + private boolean isGreaterThan(T val) { + return this.val.compareTo(val) > 0; + } + + private boolean isLessThanOrEqualTo(T val) { + return this.val.compareTo(val) < 1; + } + + @Override + public String toString() { + return val.toString(); + } +} diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/Item.java b/iterator/src/main/java/com/iluwatar/iterator/list/Item.java new file mode 100644 index 000000000000..0188078a1b02 --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/list/Item.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.iterator.list; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +/** Item. */ +@AllArgsConstructor +public class Item { + + @Getter @Setter private ItemType type; + private final String name; + + @Override + public String toString() { + return name; + } +} diff --git a/iterator/src/main/java/com/iluwatar/iterator/ItemType.java b/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java similarity index 79% rename from iterator/src/main/java/com/iluwatar/iterator/ItemType.java rename to iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java index 4cf36926efee..2655a7aa091f 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/ItemType.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,15 +22,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.iterator; +package com.iluwatar.iterator.list; -/** - * - * ItemType enumeration - * - */ +/** ItemType enumeration. */ public enum ItemType { - - ANY, WEAPON, RING, POTION - + ANY, + WEAPON, + RING, + POTION } diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java new file mode 100644 index 000000000000..1eb3905a7fd0 --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java @@ -0,0 +1,60 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.iterator.list; + +import com.iluwatar.iterator.Iterator; +import java.util.ArrayList; +import java.util.List; + +/** TreasureChest, the collection class. */ +public class TreasureChest { + + private final List items; + + /** Constructor. */ + public TreasureChest() { + items = + List.of( + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); + } + + public Iterator iterator(ItemType itemType) { + return new TreasureChestItemIterator(this, itemType); + } + + /** Get all items. */ + public List getItems() { + return new ArrayList<>(items); + } +} diff --git a/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java similarity index 76% rename from iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java rename to iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java index 9d841259ff26..51c33f931acb 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,24 +22,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.iterator; +package com.iluwatar.iterator.list; -import java.util.List; +import com.iluwatar.iterator.Iterator; -/** - * - * TreasureChestItemIterator - * - */ -public class TreasureChestItemIterator implements ItemIterator { +/** TreasureChestItemIterator. */ +public class TreasureChestItemIterator implements Iterator { - private TreasureChest chest; + private final TreasureChest chest; private int idx; - private ItemType type; + private final ItemType type; - /** - * Constructor - */ + /** Constructor. */ public TreasureChestItemIterator(TreasureChest chest, ItemType type) { this.chest = chest; this.type = type; @@ -59,11 +55,9 @@ public Item next() { } private int findNextIdx() { - - List items = chest.getItems(); - boolean found = false; - int tempIdx = idx; - while (!found) { + var items = chest.getItems(); + var tempIdx = idx; + while (true) { tempIdx++; if (tempIdx >= items.size()) { tempIdx = -1; diff --git a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java index f448a378e49c..13766bbc9847 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.iterator; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application Test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java b/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java deleted file mode 100644 index 665666aa7c3e..000000000000 --- a/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java +++ /dev/null @@ -1,115 +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.iterator; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.fail; - -/** - * Date: 12/14/15 - 2:58 PM - * - * @author Jeroen Meulemeester - */ -public class TreasureChestTest { - - /** - * Create a list of all expected items in the chest. - * - * @return The set of all expected items in the chest - */ - public static List dataProvider() { - final List parameters = new ArrayList<>(); - parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of courage")}); - parameters.add(new Object[]{new Item(ItemType.RING, "Ring of shadows")}); - parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of wisdom")}); - parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of blood")}); - parameters.add(new Object[]{new Item(ItemType.WEAPON, "Sword of silver +1")}); - parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of rust")}); - parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of healing")}); - parameters.add(new Object[]{new Item(ItemType.RING, "Ring of armor")}); - parameters.add(new Object[]{new Item(ItemType.WEAPON, "Steel halberd")}); - parameters.add(new Object[]{new Item(ItemType.WEAPON, "Dagger of poison")}); - return parameters; - } - - /** - * Test if the expected item can be retrieved from the chest using the {@link ItemIterator} - */ - @ParameterizedTest - @MethodSource("dataProvider") - public void testIterator(Item expectedItem) { - final TreasureChest chest = new TreasureChest(); - final ItemIterator iterator = chest.iterator(expectedItem.getType()); - assertNotNull(iterator); - - while (iterator.hasNext()) { - final Item item = iterator.next(); - assertNotNull(item); - assertEquals(expectedItem.getType(), item.getType()); - - final String name = item.toString(); - assertNotNull(name); - if (expectedItem.toString().equals(name)) { - return; - } - } - - fail("Expected to find item [" + expectedItem + "] using iterator, but we didn't."); - - } - - /** - * Test if the expected item can be retrieved from the chest using the {@link - * TreasureChest#getItems()} method - */ - @ParameterizedTest - @MethodSource("dataProvider") - public void testGetItems(Item expectedItem) throws Exception { - final TreasureChest chest = new TreasureChest(); - final List items = chest.getItems(); - assertNotNull(items); - - for (final Item item : items) { - assertNotNull(item); - assertNotNull(item.getType()); - assertNotNull(item.toString()); - - final boolean sameType = expectedItem.getType() == item.getType(); - final boolean sameName = expectedItem.toString().equals(item.toString()); - if (sameType && sameName) { - return; - } - } - - fail("Expected to find item [" + expectedItem + "] in the item list, but we didn't."); - - } - -} \ No newline at end of file diff --git a/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java b/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java new file mode 100644 index 000000000000..a075ce75f3ea --- /dev/null +++ b/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java @@ -0,0 +1,105 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.iterator.bst; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.NoSuchElementException; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; + +@TestInstance(Lifecycle.PER_CLASS) +class BstIteratorTest { + + private TreeNode nonEmptyRoot; + private TreeNode emptyRoot; + + @BeforeAll + void createTrees() { + nonEmptyRoot = new TreeNode<>(5); + nonEmptyRoot.insert(3); + nonEmptyRoot.insert(7); + nonEmptyRoot.insert(1); + nonEmptyRoot.insert(4); + nonEmptyRoot.insert(6); + + emptyRoot = null; + } + + @Test + void nextForEmptyTree() { + var iter = new BstIterator<>(emptyRoot); + assertThrows( + NoSuchElementException.class, + iter::next, + "next() should throw an IllegalStateException if hasNext() is false."); + } + + @Test + void nextOverEntirePopulatedTree() { + var iter = new BstIterator<>(nonEmptyRoot); + assertEquals(Integer.valueOf(1), iter.next().getVal(), "First Node is 1."); + assertEquals(Integer.valueOf(3), iter.next().getVal(), "Second Node is 3."); + assertEquals(Integer.valueOf(4), iter.next().getVal(), "Third Node is 4."); + assertEquals(Integer.valueOf(5), iter.next().getVal(), "Fourth Node is 5."); + assertEquals(Integer.valueOf(6), iter.next().getVal(), "Fifth Node is 6."); + assertEquals(Integer.valueOf(7), iter.next().getVal(), "Sixth Node is 7."); + } + + @Test + void hasNextForEmptyTree() { + var iter = new BstIterator<>(emptyRoot); + assertFalse(iter.hasNext(), "hasNext() should return false for empty tree."); + } + + @Test + void hasNextForPopulatedTree() { + var iter = new BstIterator<>(nonEmptyRoot); + assertTrue(iter.hasNext(), "hasNext() should return true for populated tree."); + } + + @Test + void nextAndHasNextOverEntirePopulatedTree() { + var iter = new BstIterator<>(nonEmptyRoot); + assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); + assertEquals(Integer.valueOf(1), iter.next().getVal(), "First Node is 1."); + assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); + assertEquals(Integer.valueOf(3), iter.next().getVal(), "Second Node is 3."); + assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); + assertEquals(Integer.valueOf(4), iter.next().getVal(), "Third Node is 4."); + assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); + assertEquals(Integer.valueOf(5), iter.next().getVal(), "Fourth Node is 5."); + assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); + assertEquals(Integer.valueOf(6), iter.next().getVal(), "Fifth Node is 6."); + assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); + assertEquals(Integer.valueOf(7), iter.next().getVal(), "Sixth Node is 7."); + assertFalse(iter.hasNext(), "Iterator hasNext() should be false, end of tree."); + } +} diff --git a/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java b/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java new file mode 100644 index 000000000000..3c298180d065 --- /dev/null +++ b/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java @@ -0,0 +1,108 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.iterator.list; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** TreasureChestTest */ +class TreasureChestTest { + + /** + * Create a list of all expected items in the chest. + * + * @return The set of all expected items in the chest + */ + public static List dataProvider() { + return List.of( + new Object[] {new Item(ItemType.POTION, "Potion of courage")}, + new Object[] {new Item(ItemType.RING, "Ring of shadows")}, + new Object[] {new Item(ItemType.POTION, "Potion of wisdom")}, + new Object[] {new Item(ItemType.POTION, "Potion of blood")}, + new Object[] {new Item(ItemType.WEAPON, "Sword of silver +1")}, + new Object[] {new Item(ItemType.POTION, "Potion of rust")}, + new Object[] {new Item(ItemType.POTION, "Potion of healing")}, + new Object[] {new Item(ItemType.RING, "Ring of armor")}, + new Object[] {new Item(ItemType.WEAPON, "Steel halberd")}, + new Object[] {new Item(ItemType.WEAPON, "Dagger of poison")}); + } + + /** + * Test if the expected item can be retrieved from the chest using the {@link + * TreasureChestItemIterator} + */ + @ParameterizedTest + @MethodSource("dataProvider") + void testIterator(Item expectedItem) { + final var chest = new TreasureChest(); + final var iterator = chest.iterator(expectedItem.getType()); + assertNotNull(iterator); + + while (iterator.hasNext()) { + final var item = iterator.next(); + assertNotNull(item); + assertEquals(expectedItem.getType(), item.getType()); + + final var name = item.toString(); + assertNotNull(name); + if (expectedItem.toString().equals(name)) { + return; + } + } + + fail("Expected to find item [" + expectedItem + "] using iterator, but we didn't."); + } + + /** + * Test if the expected item can be retrieved from the chest using the {@link + * TreasureChest#getItems()} method + */ + @ParameterizedTest + @MethodSource("dataProvider") + void testGetItems(Item expectedItem) { + final var chest = new TreasureChest(); + final var items = chest.getItems(); + assertNotNull(items); + + for (final var item : items) { + assertNotNull(item); + assertNotNull(item.getType()); + assertNotNull(item.toString()); + + final var sameType = expectedItem.getType() == item.getType(); + final var sameName = expectedItem.toString().equals(item.toString()); + if (sameType && sameName) { + return; + } + } + + fail("Expected to find item [" + expectedItem + "] in the item list, but we didn't."); + } +} diff --git a/layered-architecture/README.md b/layered-architecture/README.md new file mode 100644 index 000000000000..9692d6e0e2db --- /dev/null +++ b/layered-architecture/README.md @@ -0,0 +1,131 @@ +--- +title: "Layered Architecture Pattern in Java: Building Scalable and Maintainable Applications" +shortTitle: Layered Architecture +description: "Explore the Layered Architecture design pattern in Java. Learn its benefits, real-world examples, use cases, and how it enhances maintainability and scalability in enterprise applications." +category: Architectural +language: en +tag: + - Abstraction + - Decoupling + - Enterprise patterns + - Layered architecture + - Scalability +--- + +## Also known as + +* N-Tier Architecture + +## Intent of Layered Architecture Design Pattern + +The Layered Architecture design pattern helps organize applications into groups of subtasks at different levels of abstraction, facilitating independent development and maintenance of each layer. + +## Detailed Explanation of Layered Architecture Pattern with Real-World Examples + +Real-world example + +> Imagine constructing a modern high-rise building, analogous to using the Layered Architecture design pattern in software development. This pattern allows each software layer, such as the data layer, service layer, and presentation layer, to support seamless interaction while maintaining independence, enhancing maintainability and scalability. Just as a building is divided into layers such as the foundation, structural floors, residential floors, and the rooftop, each with specific functions and built using different materials and techniques, a software application can be similarly structured. +> +> In this analogy, the foundation represents the data layer, responsible for managing database operations. The structural floors are akin to the service layer, which contains business logic and rules. The residential floors parallel the presentation layer, which deals with user interfaces and interactions. Finally, the rooftop could be seen as the API layer, allowing external systems to communicate with the application. +> +> Just as each floor in a building is constructed to support the layers above and below, each software layer supports seamless interaction with its neighboring layers while maintaining a degree of independence. This structure allows for easy maintenance and updates, such as refurbishing the interiors (presentation layer) without affecting the underlying structures (business logic and data layers). + +In plain words + +> The Layered Architecture pattern organizes software into hierarchical groups of tasks, each encapsulated in distinct layers that interact with each other, facilitating ease of maintenance, scalability, and clear separation of concerns. + +Wikipedia says + +> In software engineering, multitier architecture (often referred to as n-tier architecture) or multilayered architecture is a client–server architecture in which presentation, application processing, and data management functions are physically separated. + +Architecture diagram + +![Layered Architecture Diagram](./etc/layered-architecture-diagram.png) + +## Programmatic Example of Layered Architecture in Java + +On the data layer, we keep our cake building blocks. `Cake` consist of layers and topping. + +```java +@Entity +public class Cake { + @Id + @GeneratedValue + private Long id; + @OneToOne(cascade = CascadeType.REMOVE) + private CakeTopping topping; + @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER) + private Set layers; +} +``` + +The service layer offers `CakeBakingService` for easy access to different aspects of cakes. + +```java +public interface CakeBakingService { + void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException; + List getAllCakes(); + void saveNewTopping(CakeToppingInfo toppingInfo); + List getAvailableToppings(); + void saveNewLayer(CakeLayerInfo layerInfo); + List getAvailableLayers(); +} +``` + +On the top we have our `View` responsible for rendering the cakes. + +```java +public interface View { + void render(); +} +@Slf4j +public class CakeViewImpl implements View { + private final CakeBakingService cakeBakingService; + public CakeViewImpl(CakeBakingService cakeBakingService) { + this.cakeBakingService = cakeBakingService; + } + public void render() { + cakeBakingService.getAllCakes().forEach(cake -> LOGGER.info(cake.toString())); + } +} +``` + +## When to Use the Layered Architecture Pattern in Java + +This pattern is suitable for structuring applications that can be divided into groups where each group has a specific role or responsibility. Common in enterprise applications, it simplifies dependencies, enhances maintainability, and supports scaling and technology stack segregation. + +Use the Layers architecture when + +* 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. + +## Real-World Applications of Layered Architecture Pattern in Java + +* Web applications where the presentation, business logic, and data access layers are distinctly separated. +* Enterprise systems where core functionalities are isolated from interface applications and databases. + +## Benefits and Trade-offs of Layered Architecture Pattern + +Benefits + +* Improved manageability with separation of concerns +* Easier to update or modify one layer without affecting others +* Promotes reuse of functionalities. + +Trade-offs + +* Potential performance overhead due to layer interaction +* Complexity in layer management +* Challenges in designing an effective layer distribution. + +## Related Java Design Patterns + +* [Model-View-Controller](https://java-design-patterns.com/patterns/model-view-controller/): Shares separation of concerns by dividing application into input, processing, and output. Layered Architecture often implements an MVC within its presentation layer. +* Service-Oriented Architecture (SOA): Both patterns emphasize modularization but SOA focuses more on distributed services that can be reused across different systems. + +## References and Credits + +* [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3UoKkaR) +* [Java Design Pattern Essentials](https://amzn.to/4drLhHU) +* [Pattern-Oriented Software Architecture Volume 1: A System of Patterns](https://amzn.to/3xZ1ELU) diff --git a/layered-architecture/etc/layered-architecture-diagram.png b/layered-architecture/etc/layered-architecture-diagram.png new file mode 100644 index 000000000000..8bdc13afeb52 Binary files /dev/null and b/layered-architecture/etc/layered-architecture-diagram.png differ diff --git a/layers/etc/layers.png b/layered-architecture/etc/layers.png similarity index 100% rename from layers/etc/layers.png rename to layered-architecture/etc/layers.png diff --git a/layered-architecture/etc/layers.ucls b/layered-architecture/etc/layers.ucls new file mode 100644 index 000000000000..d2c19e7741f4 --- /dev/null +++ b/layered-architecture/etc/layers.ucls @@ -0,0 +1,256 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/layered-architecture/etc/layers.urm.puml b/layered-architecture/etc/layers.urm.puml new file mode 100644 index 000000000000..51b09773fdbb --- /dev/null +++ b/layered-architecture/etc/layers.urm.puml @@ -0,0 +1,136 @@ +@startuml +package com.iluwatar.layers.dto { + class CakeInfo { + + cakeLayerInfos : List + + cakeToppingInfo : CakeToppingInfo + + id : Optional + + CakeInfo(cakeToppingInfo : CakeToppingInfo, cakeLayerInfos : List) + + CakeInfo(id : Long, cakeToppingInfo : CakeToppingInfo, cakeLayerInfos : List) + + calculateTotalCalories() : int + + toString() : String + } + class CakeLayerInfo { + + calories : int + + id : Optional + + name : String + + CakeLayerInfo(id : Long, name : String, calories : int) + + CakeLayerInfo(name : String, calories : int) + + toString() : String + } + class CakeToppingInfo { + + calories : int + + id : Optional + + name : String + + CakeToppingInfo(id : Long, name : String, calories : int) + + CakeToppingInfo(name : String, calories : int) + + toString() : String + } +} +package com.iluwatar.layers.entity { + class Cake { + - id : Long + - layers : Set + - topping : CakeTopping + + Cake() + + addLayer(layer : CakeLayer) + + getId() : Long + + getLayers() : Set + + getTopping() : CakeTopping + + setId(id : Long) + + setLayers(layers : Set) + + setTopping(topping : CakeTopping) + + toString() : String + } + class CakeLayer { + - cake : Cake + - calories : int + - id : Long + - name : String + + CakeLayer() + + CakeLayer(name : String, calories : int) + + getCake() : Cake + + getCalories() : int + + getId() : Long + + getName() : String + + setCake(cake : Cake) + + setCalories(calories : int) + + setId(id : Long) + + setName(name : String) + + toString() : String + } + class CakeTopping { + - cake : Cake + - calories : int + - id : Long + - name : String + + CakeTopping() + + CakeTopping(name : String, calories : int) + + getCake() : Cake + + getCalories() : int + + getId() : Long + + getName() : String + + setCake(cake : Cake) + + setCalories(calories : int) + + setId(id : Long) + + setName(name : String) + + toString() : String + } +} +package com.iluwatar.layers.view { + class CakeViewImpl { + - LOGGER : Logger {static} + - cakeBakingService : CakeBakingService + + CakeViewImpl(cakeBakingService : CakeBakingService) + + render() + } + interface View { + + render() {abstract} + } +} +package com.iluwatar.layers.app { + class App { + - cakeBakingService : CakeBakingService {static} + + App() + - initializeData(cakeBakingService : CakeBakingService) {static} + + main(args : String[]) {static} + } +} +package com.iluwatar.layers.dao { + interface CakeDao { + } + interface CakeLayerDao { + } + interface CakeToppingDao { + } +} +package com.iluwatar.layers.service { + interface CakeBakingService { + + bakeNewCake(CakeInfo) {abstract} + + getAllCakes() : List {abstract} + + getAvailableLayers() : List {abstract} + + getAvailableToppings() : List {abstract} + + saveNewLayer(CakeLayerInfo) {abstract} + + saveNewTopping(CakeToppingInfo) {abstract} + } + class CakeBakingServiceImpl { + - context : AbstractApplicationContext + + CakeBakingServiceImpl() + + bakeNewCake(cakeInfo : CakeInfo) + + getAllCakes() : List + - getAvailableLayerEntities() : List + + getAvailableLayers() : List + - getAvailableToppingEntities() : List + + getAvailableToppings() : List + + saveNewLayer(layerInfo : CakeLayerInfo) + + saveNewTopping(toppingInfo : CakeToppingInfo) + } +} +CakeInfo --> "-cakeLayerInfos" CakeLayerInfo +CakeInfo --> "-cakeToppingInfo" CakeToppingInfo +CakeViewImpl --> "-cakeBakingService" CakeBakingService +App --> "-cakeBakingService" CakeBakingService +Cake --> "-topping" CakeTopping +CakeLayer --> "-cake" Cake +CakeBakingServiceImpl ..|> CakeBakingService +CakeViewImpl ..|> View +@enduml \ No newline at end of file diff --git a/layered-architecture/pom.xml b/layered-architecture/pom.xml new file mode 100644 index 000000000000..c91fc733ef64 --- /dev/null +++ b/layered-architecture/pom.xml @@ -0,0 +1,82 @@ + + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + layered-architecture + layers + layers + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.layers.Runner + + + + + + + + + + diff --git a/layered-architecture/src/main/java/com/iluwatar/layers/Runner.java b/layered-architecture/src/main/java/com/iluwatar/layers/Runner.java new file mode 100644 index 000000000000..4c4fb68377ae --- /dev/null +++ b/layered-architecture/src/main/java/com/iluwatar/layers/Runner.java @@ -0,0 +1,114 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.layers; + +import dto.CakeInfo; +import dto.CakeLayerInfo; +import dto.CakeToppingInfo; +import exception.CakeBakingException; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.stereotype.Component; +import service.CakeBakingService; +import view.CakeViewImpl; + +/** + * The Runner class is the entry point of the application. It implements CommandLineRunner, which + * means it will execute the run method after the application context is loaded. + * + *

    The Runner class is responsible for initializing the cake baking service with sample data and + * creating a view to render the cakes. It uses the CakeBakingService to save new layers and + * toppings and to bake new cakes. It also handles exceptions that might occur during the cake + * baking process. + */ +@EntityScan(basePackages = "entity") +@ComponentScan(basePackages = {"com.iluwatar.layers", "service", "dto", "exception", "view", "dao"}) +@Component +@Slf4j +public class Runner implements CommandLineRunner { + private final CakeBakingService cakeBakingService; + public static final String STRAWBERRY = "strawberry"; + + @Autowired + public Runner(CakeBakingService cakeBakingService) { + this.cakeBakingService = cakeBakingService; + } + + @Override + public void run(String... args) { + // initialize sample data + initializeData(); + // create view and render it + var cakeView = new CakeViewImpl(cakeBakingService); + cakeView.render(); + } + + public static void main(String[] args) { + SpringApplication.run(Runner.class, args); + } + + /** Initializes the example data. */ + private void initializeData() { + cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200)); + cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900)); + cakeBakingService.saveNewLayer(new CakeLayerInfo(STRAWBERRY, 950)); + cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950)); + cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950)); + cakeBakingService.saveNewLayer(new CakeLayerInfo(STRAWBERRY, 950)); + + cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350)); + cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350)); + + var cake1 = + new CakeInfo( + new CakeToppingInfo("candies", 0), + List.of( + new CakeLayerInfo("chocolate", 0), + new CakeLayerInfo("banana", 0), + new CakeLayerInfo(STRAWBERRY, 0))); + try { + cakeBakingService.bakeNewCake(cake1); + } catch (CakeBakingException e) { + LOGGER.error("Cake baking exception", e); + } + var cake2 = + new CakeInfo( + new CakeToppingInfo("cherry", 0), + List.of( + new CakeLayerInfo("vanilla", 0), + new CakeLayerInfo("lemon", 0), + new CakeLayerInfo(STRAWBERRY, 0))); + try { + cakeBakingService.bakeNewCake(cake2); + } catch (CakeBakingException e) { + LOGGER.error("Cake baking exception", e); + } + } +} diff --git a/layered-architecture/src/main/java/com/iluwatar/layers/app/LayersApp.java b/layered-architecture/src/main/java/com/iluwatar/layers/app/LayersApp.java new file mode 100644 index 000000000000..2870366e00bd --- /dev/null +++ b/layered-architecture/src/main/java/com/iluwatar/layers/app/LayersApp.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.layers.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +/** + * The Layers pattern is a structural design pattern that organizes system architecture into + * distinct layers, each with a specific responsibility and abstraction level. This separation + * allows for increased modularity, facilitating independent development, maintenance, and reuse of + * each layer. Commonly, layers interact with each other through well-defined interfaces, with + * higher layers (more abstract) depending on lower layers (more concrete), but not vice versa, + * promoting a clear hierarchy and separation of concerns. + */ +@SpringBootApplication +@EnableJpaRepositories(basePackages = "dao") +@EntityScan(basePackages = "entity") +@ComponentScan(basePackages = {"com.iluwatar.layers", "service", "dto", "exception", "view", "dao"}) +public class LayersApp { + + public static void main(String[] args) { + SpringApplication.run(LayersApp.class, args); + } +} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeDao.java b/layered-architecture/src/main/java/dao/CakeDao.java similarity index 75% rename from layers/src/main/java/com/iluwatar/layers/CakeDao.java rename to layered-architecture/src/main/java/dao/CakeDao.java index d1788b1e0832..aae92a175bb0 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeDao.java +++ b/layered-architecture/src/main/java/dao/CakeDao.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,17 +22,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.layers; +package dao; -import org.springframework.data.repository.CrudRepository; +import entity.Cake; +import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -/** - * - * CRUD repository for cakes - * - */ +/** CRUD repository for cakes. */ @Repository -public interface CakeDao extends CrudRepository { - -} +public interface CakeDao extends JpaRepository {} diff --git a/layered-architecture/src/main/java/dao/CakeLayerDao.java b/layered-architecture/src/main/java/dao/CakeLayerDao.java new file mode 100644 index 000000000000..0e4415ce4c42 --- /dev/null +++ b/layered-architecture/src/main/java/dao/CakeLayerDao.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 dao; + +import entity.CakeLayer; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** CRUD repository for cake layers. */ +@Repository +public interface CakeLayerDao extends JpaRepository {} diff --git a/layered-architecture/src/main/java/dao/CakeToppingDao.java b/layered-architecture/src/main/java/dao/CakeToppingDao.java new file mode 100644 index 000000000000..bc7b4a56f723 --- /dev/null +++ b/layered-architecture/src/main/java/dao/CakeToppingDao.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 dao; + +import entity.CakeTopping; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** CRUD repository cake toppings. */ +@Repository +public interface CakeToppingDao extends JpaRepository {} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeInfo.java b/layered-architecture/src/main/java/dto/CakeInfo.java similarity index 75% rename from layers/src/main/java/com/iluwatar/layers/CakeInfo.java rename to layered-architecture/src/main/java/dto/CakeInfo.java index a1a2cb12eb9f..475c994481ab 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeInfo.java +++ b/layered-architecture/src/main/java/dto/CakeInfo.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,52 +22,43 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.layers; + +package dto; import java.util.List; -import java.util.Optional; -/** - * - * DTO for cakes - * - */ +/** DTO for cakes. */ public class CakeInfo { - public final Optional id; + public final Long id; public final CakeToppingInfo cakeToppingInfo; public final List cakeLayerInfos; - /** - * Constructor - */ + /** Constructor. */ public CakeInfo(Long id, CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) { - this.id = Optional.of(id); + this.id = id; this.cakeToppingInfo = cakeToppingInfo; this.cakeLayerInfos = cakeLayerInfos; } - /** - * Constructor - */ + /** Constructor. */ public CakeInfo(CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) { - this.id = Optional.empty(); + this.id = null; this.cakeToppingInfo = cakeToppingInfo; this.cakeLayerInfos = cakeLayerInfos; } - /** - * Calculate calories - */ + /** Calculate calories. */ public int calculateTotalCalories() { - int total = cakeToppingInfo != null ? cakeToppingInfo.calories : 0; + var total = cakeToppingInfo != null ? cakeToppingInfo.calories : 0; total += cakeLayerInfos.stream().mapToInt(c -> c.calories).sum(); return total; } @Override public String toString() { - return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id.orElse(-1L), - cakeToppingInfo, cakeLayerInfos, calculateTotalCalories()); + return String.format( + "CakeInfo id=%d topping=%s layers=%s totalCalories=%d", + id, cakeToppingInfo, cakeLayerInfos, calculateTotalCalories()); } } diff --git a/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java b/layered-architecture/src/main/java/dto/CakeLayerInfo.java similarity index 81% rename from layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java rename to layered-architecture/src/main/java/dto/CakeLayerInfo.java index f776c320e0a5..e7e464e2dc13 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java +++ b/layered-architecture/src/main/java/dto/CakeLayerInfo.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,41 +22,32 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.layers; -import java.util.Optional; +package dto; -/** - * - * DTO for cake layers - * - */ +/** DTO for cake layers. */ public class CakeLayerInfo { - public final Optional id; + public final Long id; public final String name; public final int calories; - /** - * Constructor - */ + /** Constructor. */ public CakeLayerInfo(Long id, String name, int calories) { - this.id = Optional.of(id); + this.id = id; this.name = name; this.calories = calories; } - /** - * Constructor - */ + /** Constructor. */ public CakeLayerInfo(String name, int calories) { - this.id = Optional.empty(); + this.id = null; this.name = name; this.calories = calories; } @Override public String toString() { - return String.format("CakeLayerInfo id=%d name=%s calories=%d", id.orElse(-1L), name, calories); + return String.format("CakeLayerInfo id=%d name=%s calories=%d", id, name, calories); } } diff --git a/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java b/layered-architecture/src/main/java/dto/CakeToppingInfo.java similarity index 80% rename from layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java rename to layered-architecture/src/main/java/dto/CakeToppingInfo.java index 031243f4a9f2..9c48d869ce65 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java +++ b/layered-architecture/src/main/java/dto/CakeToppingInfo.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,41 +22,32 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.layers; -import java.util.Optional; +package dto; -/** - * - * DTO for cake toppings - * - */ +/** DTO for cake toppings. */ public class CakeToppingInfo { - public final Optional id; + public final Long id; public final String name; public final int calories; - /** - * Constructor - */ + /** Constructor. */ public CakeToppingInfo(Long id, String name, int calories) { - this.id = Optional.of(id); + this.id = id; this.name = name; this.calories = calories; } - /** - * Constructor - */ + /** Constructor. */ public CakeToppingInfo(String name, int calories) { - this.id = Optional.empty(); + this.id = null; this.name = name; this.calories = calories; } @Override public String toString() { - return String.format("CakeToppingInfo id=%d name=%s calories=%d", id.orElse(-1L), name, calories); + return String.format("CakeToppingInfo id=%d name=%s calories=%d", id, name, calories); } } diff --git a/layered-architecture/src/main/java/entity/Cake.java b/layered-architecture/src/main/java/entity/Cake.java new file mode 100644 index 000000000000..58a8af659a60 --- /dev/null +++ b/layered-architecture/src/main/java/entity/Cake.java @@ -0,0 +1,66 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 entity; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OneToOne; +import java.util.HashSet; +import java.util.Set; +import lombok.Getter; +import lombok.Setter; + +/** Cake entity. */ +@Entity +@Getter +@Setter +public class Cake { + + @Id @GeneratedValue private Long id; + + @OneToOne(cascade = CascadeType.REMOVE) + private CakeTopping topping; + + @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER) + private Set layers; + + public Cake() { + setLayers(new HashSet<>()); + } + + public void addLayer(CakeLayer layer) { + this.layers.add(layer); + } + + @Override + public String toString() { + return String.format("id=%s topping=%s layers=%s", id, topping, layers.toString()); + } +} diff --git a/layered-architecture/src/main/java/entity/CakeLayer.java b/layered-architecture/src/main/java/entity/CakeLayer.java new file mode 100644 index 000000000000..798ecbd17664 --- /dev/null +++ b/layered-architecture/src/main/java/entity/CakeLayer.java @@ -0,0 +1,68 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 entity; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** CakeLayer entity. */ +@Entity +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +@EqualsAndHashCode +public class CakeLayer { + + @Id @GeneratedValue private Long id; + + private String name; + + private int calories; + + @ManyToOne(cascade = CascadeType.ALL) + private Cake cake; + + public CakeLayer(String name, int calories) { + this.setName(name); + this.setCalories(calories); + } + + @Override + public String toString() { + return String.format("id=%s name=%s calories=%d", id, name, calories); + } +} diff --git a/layered-architecture/src/main/java/entity/CakeTopping.java b/layered-architecture/src/main/java/entity/CakeTopping.java new file mode 100644 index 000000000000..8b1c5f38be30 --- /dev/null +++ b/layered-architecture/src/main/java/entity/CakeTopping.java @@ -0,0 +1,68 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 entity; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** CakeTopping entity. */ +@Entity +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +@EqualsAndHashCode +public class CakeTopping { + + @Id @GeneratedValue private Long id; + + private String name; + + private int calories; + + @OneToOne(cascade = CascadeType.ALL) + private Cake cake; + + public CakeTopping(String name, int calories) { + this.setName(name); + this.setCalories(calories); + } + + @Override + public String toString() { + return String.format("id=%s name=%s calories=%d", id, name, calories); + } +} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingException.java b/layered-architecture/src/main/java/exception/CakeBakingException.java similarity index 76% rename from layers/src/main/java/com/iluwatar/layers/CakeBakingException.java rename to layered-architecture/src/main/java/exception/CakeBakingException.java index fa338a40add3..13af2b550261 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeBakingException.java +++ b/layered-architecture/src/main/java/exception/CakeBakingException.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,16 +22,17 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.layers; -/** - * - * Custom exception used in cake baking - * - */ +package exception; + +import java.io.Serial; +import org.springframework.stereotype.Component; + +/** Custom exception used in cake baking. */ +@Component public class CakeBakingException extends Exception { - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; public CakeBakingException() {} diff --git a/layered-architecture/src/main/java/service/CakeBakingService.java b/layered-architecture/src/main/java/service/CakeBakingService.java new file mode 100644 index 000000000000..be34797d66c4 --- /dev/null +++ b/layered-architecture/src/main/java/service/CakeBakingService.java @@ -0,0 +1,62 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 service; + +import dto.CakeInfo; +import dto.CakeLayerInfo; +import dto.CakeToppingInfo; +import exception.CakeBakingException; +import java.util.List; +import org.springframework.stereotype.Service; + +/** Service for cake baking operations. */ +@Service +public interface CakeBakingService { + + /** Bakes new cake according to parameters. */ + void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException; + + /** Get all cakes. */ + List getAllCakes(); + + /** Store new cake topping. */ + void saveNewTopping(CakeToppingInfo toppingInfo); + + /** Get available cake toppings. */ + List getAvailableToppings(); + + /** Add new cake layer. */ + void saveNewLayer(CakeLayerInfo layerInfo); + + /** Get available cake layers. */ + List getAvailableLayers(); + + void deleteAllCakes(); + + void deleteAllLayers(); + + void deleteAllToppings(); +} diff --git a/layered-architecture/src/main/java/service/CakeBakingServiceImpl.java b/layered-architecture/src/main/java/service/CakeBakingServiceImpl.java new file mode 100644 index 000000000000..6af2123d9d68 --- /dev/null +++ b/layered-architecture/src/main/java/service/CakeBakingServiceImpl.java @@ -0,0 +1,199 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 service; + +import dao.CakeDao; +import dao.CakeLayerDao; +import dao.CakeToppingDao; +import dto.CakeInfo; +import dto.CakeLayerInfo; +import dto.CakeToppingInfo; +import entity.Cake; +import entity.CakeLayer; +import entity.CakeTopping; +import exception.CakeBakingException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Implementation of CakeBakingService. */ +@Service +@Transactional +public class CakeBakingServiceImpl implements CakeBakingService { + + private final CakeDao cakeDao; + private final CakeLayerDao cakeLayerDao; + private final CakeToppingDao cakeToppingDao; + + /** + * Constructs a new instance of CakeBakingServiceImpl. + * + * @param cakeDao the DAO for cake-related operations + * @param cakeLayerDao the DAO for cake layer-related operations + * @param cakeToppingDao the DAO for cake topping-related operations + */ + @Autowired + public CakeBakingServiceImpl( + CakeDao cakeDao, CakeLayerDao cakeLayerDao, CakeToppingDao cakeToppingDao) { + this.cakeDao = cakeDao; + this.cakeLayerDao = cakeLayerDao; + this.cakeToppingDao = cakeToppingDao; + } + + @Override + public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException { + var allToppings = getAvailableToppingEntities(); + var matchingToppings = + allToppings.stream() + .filter(t -> t.getName().equals(cakeInfo.cakeToppingInfo.name)) + .toList(); + if (matchingToppings.isEmpty()) { + throw new CakeBakingException( + String.format("Topping %s is not available", cakeInfo.cakeToppingInfo.name)); + } + var allLayers = getAvailableLayerEntities(); + Set foundLayers = new HashSet<>(); + for (var info : cakeInfo.cakeLayerInfos) { + var found = allLayers.stream().filter(layer -> layer.getName().equals(info.name)).findFirst(); + if (found.isEmpty()) { + throw new CakeBakingException(String.format("Layer %s is not available", info.name)); + } else { + foundLayers.add(found.get()); + } + } + + var topping = cakeToppingDao.findById(matchingToppings.iterator().next().getId()); + if (topping.isPresent()) { + var cake = new Cake(); + cake.setTopping(topping.get()); + cake.setLayers(foundLayers); + cakeDao.save(cake); + topping.get().setCake(cake); + cakeToppingDao.save(topping.get()); + Set foundLayersToUpdate = + new HashSet<>(foundLayers); // copy set to avoid a ConcurrentModificationException + + for (var layer : foundLayersToUpdate) { + layer.setCake(cake); + cakeLayerDao.save(layer); + } + + } else { + throw new CakeBakingException( + String.format("Topping %s is not available", cakeInfo.cakeToppingInfo.name)); + } + } + + @Override + public void saveNewTopping(CakeToppingInfo toppingInfo) { + cakeToppingDao.save(new CakeTopping(toppingInfo.name, toppingInfo.calories)); + } + + @Override + public void saveNewLayer(CakeLayerInfo layerInfo) { + cakeLayerDao.save(new CakeLayer(layerInfo.name, layerInfo.calories)); + } + + private List getAvailableToppingEntities() { + List result = new ArrayList<>(); + for (CakeTopping topping : cakeToppingDao.findAll()) { + if (topping.getCake() == null) { + result.add(topping); + } + } + return result; + } + + @Override + public List getAvailableToppings() { + List result = new ArrayList<>(); + for (CakeTopping next : cakeToppingDao.findAll()) { + if (next.getCake() == null) { + result.add(new CakeToppingInfo(next.getId(), next.getName(), next.getCalories())); + } + } + return result; + } + + private List getAvailableLayerEntities() { + List result = new ArrayList<>(); + for (CakeLayer next : cakeLayerDao.findAll()) { + if (next.getCake() == null) { + result.add(next); + } + } + return result; + } + + @Override + public List getAvailableLayers() { + List result = new ArrayList<>(); + for (CakeLayer next : cakeLayerDao.findAll()) { + if (next.getCake() == null) { + result.add(new CakeLayerInfo(next.getId(), next.getName(), next.getCalories())); + } + } + return result; + } + + @Override + public void deleteAllCakes() { + cakeDao.deleteAll(); + } + + @Override + public void deleteAllLayers() { + cakeLayerDao.deleteAll(); + } + + @Override + public void deleteAllToppings() { + cakeToppingDao.deleteAll(); + } + + @Override + public List getAllCakes() { + List result = new ArrayList<>(); + for (Cake cake : cakeDao.findAll()) { + var cakeToppingInfo = + new CakeToppingInfo( + cake.getTopping().getId(), + cake.getTopping().getName(), + cake.getTopping().getCalories()); + List cakeLayerInfos = new ArrayList<>(); + for (var layer : cake.getLayers()) { + cakeLayerInfos.add(new CakeLayerInfo(layer.getId(), layer.getName(), layer.getCalories())); + } + var cakeInfo = new CakeInfo(cake.getId(), cakeToppingInfo, cakeLayerInfos); + result.add(cakeInfo); + } + return result; + } +} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java b/layered-architecture/src/main/java/view/CakeViewImpl.java similarity index 77% rename from layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java rename to layered-architecture/src/main/java/view/CakeViewImpl.java index 57bb0a561b0f..a01d1c1600a0 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java +++ b/layered-architecture/src/main/java/view/CakeViewImpl.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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,27 +22,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.layers; + +package view; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import service.CakeBakingService; -/** - * - * View implementation for displaying cakes - * - */ +/** View implementation for displaying cakes. */ public class CakeViewImpl implements View { - private static final Logger LOGGER = LoggerFactory.getLogger(CakeViewImpl.class); + private final CakeBakingService cakeBakingService; - private CakeBakingService cakeBakingService; + private static final Logger LOGGER = LoggerFactory.getLogger(CakeViewImpl.class); public CakeViewImpl(CakeBakingService cakeBakingService) { this.cakeBakingService = cakeBakingService; } public void render() { - cakeBakingService.getAllCakes().stream().forEach(cake -> LOGGER.info(cake.toString())); + cakeBakingService.getAllCakes().forEach(cake -> LOGGER.info(cake.toString())); } } diff --git a/layered-architecture/src/main/java/view/View.java b/layered-architecture/src/main/java/view/View.java new file mode 100644 index 000000000000..78403c6013a5 --- /dev/null +++ b/layered-architecture/src/main/java/view/View.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 view; + +/** View interface. */ +public interface View { + + void render(); +} diff --git a/layered-architecture/src/main/resources/META-INF/logback.xml b/layered-architecture/src/main/resources/META-INF/logback.xml new file mode 100644 index 000000000000..9412507dd734 --- /dev/null +++ b/layered-architecture/src/main/resources/META-INF/logback.xml @@ -0,0 +1,53 @@ + + + + + layers.log + + layers-%d.log + 5 + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + + + + + + + + + diff --git a/layered-architecture/src/main/resources/application.properties b/layered-architecture/src/main/resources/application.properties new file mode 100644 index 000000000000..233a9db6c8a5 --- /dev/null +++ b/layered-architecture/src/main/resources/application.properties @@ -0,0 +1,12 @@ + +spring.main.web-application-type=none + +#datasource settings +spring.datasource.url=jdbc:h2:mem:databases-cake +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password=sa + +#data settings +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=create-drop diff --git a/layered-architecture/src/test/java/com/iluwatar/layers/app/LayersAppTests.java b/layered-architecture/src/test/java/com/iluwatar/layers/app/LayersAppTests.java new file mode 100644 index 000000000000..e51bca34d12f --- /dev/null +++ b/layered-architecture/src/test/java/com/iluwatar/layers/app/LayersAppTests.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.layers.app; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; + +@SpringBootTest(classes = LayersApp.class) +class LayersAppTests { + + private final ApplicationContext applicationContext; + + @Autowired + LayersAppTests(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + @Test + void contextLoads() { + assertNotNull(applicationContext); + } +} diff --git a/layered-architecture/src/test/java/com/iluwatar/layers/entity/CakeTest.java b/layered-architecture/src/test/java/com/iluwatar/layers/entity/CakeTest.java new file mode 100644 index 000000000000..eea31e9355ac --- /dev/null +++ b/layered-architecture/src/test/java/com/iluwatar/layers/entity/CakeTest.java @@ -0,0 +1,123 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.layers.entity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import entity.Cake; +import entity.CakeLayer; +import entity.CakeTopping; +import java.util.HashSet; +import java.util.Set; +import org.junit.jupiter.api.Test; + +/** + * This class contains unit tests for the Cake class. It tests the functionality of setting and + * getting the id, topping, and layers of a Cake object. It also tests the functionality of adding a + * layer to a Cake object and converting a Cake object to a string. + */ +class CakeTest { + + @Test + void testSetId() { + final var cake = new Cake(); + assertNull(cake.getId()); + + final var expectedId = 1234L; + cake.setId(expectedId); + assertEquals(expectedId, cake.getId()); + } + + @Test + void testSetTopping() { + final var cake = new Cake(); + assertNull(cake.getTopping()); + + final var expectedTopping = new CakeTopping("DummyTopping", 1000); + cake.setTopping(expectedTopping); + assertEquals(expectedTopping, cake.getTopping()); + } + + @Test + void testSetLayers() { + final var cake = new Cake(); + assertNotNull(cake.getLayers()); + assertTrue(cake.getLayers().isEmpty()); + + final var expectedLayers = + Set.of( + new CakeLayer("layer1", 1000), + new CakeLayer("layer2", 2000), + new CakeLayer("layer3", 3000)); + cake.setLayers(expectedLayers); + assertEquals(expectedLayers, cake.getLayers()); + } + + @Test + void testAddLayer() { + final var cake = new Cake(); + assertNotNull(cake.getLayers()); + assertTrue(cake.getLayers().isEmpty()); + + final Set initialLayers = new HashSet<>(); + initialLayers.add(new CakeLayer("layer1", 1000)); + initialLayers.add(new CakeLayer("layer2", 2000)); + + cake.setLayers(initialLayers); + assertEquals(initialLayers, cake.getLayers()); + + final var newLayer = new CakeLayer("layer3", 3000); + cake.addLayer(newLayer); + + final Set expectedLayers = new HashSet<>(); + expectedLayers.addAll(initialLayers); + expectedLayers.addAll(initialLayers); + expectedLayers.add(newLayer); + assertEquals(expectedLayers, cake.getLayers()); + } + + @Test + void testToString() { + final var topping = new CakeTopping("topping", 20); + topping.setId(2345L); + + final var layer = new CakeLayer("layer", 100); + layer.setId(3456L); + + final var cake = new Cake(); + cake.setId(1234L); + cake.setTopping(topping); + cake.addLayer(layer); + + final var expected = + "id=1234 topping=id=2345 name=topping calories=20 " + + "layers=[id=3456 name=layer calories=100]"; + assertEquals(expected, cake.toString()); + } +} diff --git a/layered-architecture/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java b/layered-architecture/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java new file mode 100644 index 000000000000..9acb49d2a289 --- /dev/null +++ b/layered-architecture/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java @@ -0,0 +1,69 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.layers.exception; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import exception.CakeBakingException; +import org.junit.jupiter.api.Test; + +/** + * Tests for the {@link CakeBakingException} class. This class contains unit tests to verify the + * correct functionality of the {@code CakeBakingException} class constructors, including the + * default constructor and the constructor that accepts a message parameter. + */ +class CakeBakingExceptionTest { + + /** + * Tests the default constructor of {@link CakeBakingException}. Ensures that an exception created + * with the default constructor has {@code null} as its message and cause. + */ + @Test + void testConstructor() { + final var exception = new CakeBakingException(); + assertNull(exception.getMessage(), "The message should be null for the default constructor."); + assertNull(exception.getCause(), "The cause should be null for the default constructor."); + } + + /** + * Tests the constructor of {@link CakeBakingException} that accepts a message. Ensures that an + * exception created with this constructor correctly stores the provided message and has {@code + * null} as its cause. + */ + @Test + void testConstructorWithMessage() { + final var expectedMessage = "message"; + final var exception = new CakeBakingException(expectedMessage); + assertEquals( + expectedMessage, + exception.getMessage(), + "The stored message should match the expected message."); + assertNull( + exception.getCause(), + "The cause should be null when an exception is created with only a message."); + } +} diff --git a/layered-architecture/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java b/layered-architecture/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java new file mode 100644 index 000000000000..a14c0076073a --- /dev/null +++ b/layered-architecture/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java @@ -0,0 +1,194 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.layers.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.layers.app.LayersApp; +import dto.CakeInfo; +import dto.CakeLayerInfo; +import dto.CakeToppingInfo; +import exception.CakeBakingException; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import service.CakeBakingServiceImpl; + +/** Constructs a new instance of CakeBakingServiceImplTest. */ +@SpringBootTest(classes = LayersApp.class) +class CakeBakingServiceImplTest { + + private final CakeBakingServiceImpl cakeBakingService; + + @Autowired + CakeBakingServiceImplTest(CakeBakingServiceImpl cakeBakingService) { + this.cakeBakingService = cakeBakingService; + } + + @BeforeEach + void setUp() { + cakeBakingService.deleteAllCakes(); + cakeBakingService.deleteAllLayers(); + cakeBakingService.deleteAllToppings(); + } + + @Test + void testLayers() { + final var initialLayers = cakeBakingService.getAvailableLayers(); + assertNotNull(initialLayers); + assertTrue(initialLayers.isEmpty()); + + cakeBakingService.saveNewLayer(new CakeLayerInfo("Layer1", 1000)); + cakeBakingService.saveNewLayer(new CakeLayerInfo("Layer2", 2000)); + + final var availableLayers = cakeBakingService.getAvailableLayers(); + assertNotNull(availableLayers); + assertEquals(2, availableLayers.size()); + for (final var layer : availableLayers) { + assertNotNull(layer.id); + assertNotNull(layer.name); + assertNotNull(layer.toString()); + assertTrue(layer.calories > 0); + } + } + + @Test + void testToppings() { + final var initialToppings = cakeBakingService.getAvailableToppings(); + assertNotNull(initialToppings); + assertTrue(initialToppings.isEmpty()); + + cakeBakingService.saveNewTopping(new CakeToppingInfo("Topping1", 1000)); + cakeBakingService.saveNewTopping(new CakeToppingInfo("Topping2", 2000)); + + final var availableToppings = cakeBakingService.getAvailableToppings(); + assertNotNull(availableToppings); + assertEquals(2, availableToppings.size()); + for (final var topping : availableToppings) { + assertNotNull(topping.id); + assertNotNull(topping.name); + assertNotNull(topping.toString()); + assertTrue(topping.calories > 0); + } + } + + @Test + void testBakeCakes() throws CakeBakingException { + + final var initialCakes = cakeBakingService.getAllCakes(); + assertNotNull(initialCakes); + assertTrue(initialCakes.isEmpty()); + + final var topping1 = new CakeToppingInfo("Topping1", 1000); + final var topping2 = new CakeToppingInfo("Topping2", 2000); + cakeBakingService.saveNewTopping(topping1); + cakeBakingService.saveNewTopping(topping2); + + final var layer1 = new CakeLayerInfo("Layer1", 1000); + final var layer2 = new CakeLayerInfo("Layer2", 2000); + final var layer3 = new CakeLayerInfo("Layer3", 2000); + cakeBakingService.saveNewLayer(layer1); + cakeBakingService.saveNewLayer(layer2); + cakeBakingService.saveNewLayer(layer3); + + cakeBakingService.bakeNewCake(new CakeInfo(topping1, List.of(layer1, layer2))); + cakeBakingService.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer3))); + + final var allCakes = cakeBakingService.getAllCakes(); + assertNotNull(allCakes); + assertEquals(2, allCakes.size()); + for (final var cakeInfo : allCakes) { + assertNotNull(cakeInfo.id); + assertNotNull(cakeInfo.cakeToppingInfo); + assertNotNull(cakeInfo.cakeLayerInfos); + assertNotNull(cakeInfo.toString()); + assertFalse(cakeInfo.cakeLayerInfos.isEmpty()); + assertTrue(cakeInfo.calculateTotalCalories() > 0); + } + } + + @Test + void testBakeCakeMissingTopping() { + final var layer1 = new CakeLayerInfo("Layer1", 1000); + final var layer2 = new CakeLayerInfo("Layer2", 2000); + cakeBakingService.saveNewLayer(layer1); + cakeBakingService.saveNewLayer(layer2); + + final var missingTopping = new CakeToppingInfo("Topping1", 1000); + assertThrows( + CakeBakingException.class, + () -> cakeBakingService.bakeNewCake(new CakeInfo(missingTopping, List.of(layer1, layer2)))); + } + + @Test + void testBakeCakeMissingLayer() { + final var initialCakes = cakeBakingService.getAllCakes(); + assertNotNull(initialCakes); + assertTrue(initialCakes.isEmpty()); + + final var topping1 = new CakeToppingInfo("Topping1", 1000); + cakeBakingService.saveNewTopping(topping1); + + final var layer1 = new CakeLayerInfo("Layer1", 1000); + cakeBakingService.saveNewLayer(layer1); + + final var missingLayer = new CakeLayerInfo("Layer2", 2000); + assertThrows( + CakeBakingException.class, + () -> cakeBakingService.bakeNewCake(new CakeInfo(topping1, List.of(layer1, missingLayer)))); + } + + @Test + void testBakeCakesUsedLayer() throws CakeBakingException { + final var initialCakes = cakeBakingService.getAllCakes(); + assertNotNull(initialCakes); + assertTrue(initialCakes.isEmpty()); + + final var topping1 = new CakeToppingInfo("Topping1", 1000); + final var topping2 = new CakeToppingInfo("Topping2", 2000); + cakeBakingService.saveNewTopping(topping1); + cakeBakingService.saveNewTopping(topping2); + + final var layer1 = new CakeLayerInfo("Layer1", 1000); + final var layer2 = new CakeLayerInfo("Layer2", 2000); + cakeBakingService.saveNewLayer(layer1); + cakeBakingService.saveNewLayer(layer2); + + cakeBakingService.bakeNewCake(new CakeInfo(topping1, List.of(layer1, layer2))); + assertThrows( + CakeBakingException.class, + () -> + cakeBakingService.bakeNewCake( + new CakeInfo(topping2, Collections.singletonList(layer2)))); + } +} diff --git a/layered-architecture/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java b/layered-architecture/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java new file mode 100644 index 000000000000..2e3b1ae598b8 --- /dev/null +++ b/layered-architecture/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java @@ -0,0 +1,112 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.layers.view; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import dto.CakeInfo; +import dto.CakeLayerInfo; +import dto.CakeToppingInfo; +import java.util.LinkedList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import service.CakeBakingService; +import view.CakeViewImpl; + +/** + * This class contains unit tests for the CakeViewImpl class. It tests the functionality of + * rendering cakes using the CakeViewImpl class. It also tests the logging functionality of the + * CakeViewImpl class. + */ +class CakeViewImplTest { + + private InMemoryAppender appender; + + @BeforeEach + void setUp() { + appender = new InMemoryAppender(CakeViewImpl.class); + } + + @AfterEach + void tearDown() { + appender.stop(); + } + + /** Verify if the cake view renders the expected result. */ + @Test + void testRender() { + + final var layers = + List.of( + new CakeLayerInfo("layer1", 1000), + new CakeLayerInfo("layer2", 2000), + new CakeLayerInfo("layer3", 3000)); + + final var cake = new CakeInfo(new CakeToppingInfo("topping", 1000), layers); + final var cakes = List.of(cake); + + final var bakingService = mock(CakeBakingService.class); + when(bakingService.getAllCakes()).thenReturn(cakes); + + final var cakeView = new CakeViewImpl(bakingService); + + assertEquals(0, appender.getLogSize()); + + cakeView.render(); + assertEquals(cake.toString(), appender.getLastMessage()); + } + + private static class InMemoryAppender extends AppenderBase { + + private final List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } + } +} diff --git a/layers/README.md b/layers/README.md deleted file mode 100644 index 49b74c175b96..000000000000 --- a/layers/README.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -layout: pattern -title: Layers -folder: layers -permalink: /patterns/layers/ -pumlformat: svg -categories: Architectural -tags: - - Java - - Difficulty-Intermediate - - Spring ---- - -## Intent -Layers is an architectural style where software responsibilities are - divided among the different layers of the application. - -![alt text](./etc/layers.png "Layers") - -## Applicability -Use the Layers architecture when - -* 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 - -## Credits - -* [Pattern Oriented Software Architecture Vol I-V](http://www.amazon.com/Pattern-Oriented-Software-Architecture-Volume-Patterns/dp/0471958697) diff --git a/layers/etc/layers.ucls b/layers/etc/layers.ucls deleted file mode 100644 index 060b391c0acf..000000000000 --- a/layers/etc/layers.ucls +++ /dev/null @@ -1,256 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/layers/pom.xml b/layers/pom.xml deleted file mode 100644 index 9ca1c58e7e0a..000000000000 --- a/layers/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - 4.0.0 - - com.iluwatar - java-design-patterns - 1.20.0-SNAPSHOT - - com.iluwatar.layers - layers - - - org.springframework.data - spring-data-jpa - - - org.hibernate - hibernate-entitymanager - - - commons-dbcp - commons-dbcp - - - com.h2database - h2 - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.mockito - mockito-core - test - - - diff --git a/layers/src/main/java/com/iluwatar/layers/App.java b/layers/src/main/java/com/iluwatar/layers/App.java deleted file mode 100644 index 2dfeee90595b..000000000000 --- a/layers/src/main/java/com/iluwatar/layers/App.java +++ /dev/null @@ -1,118 +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.layers; - -import java.util.Arrays; - -/** - * - * Layers is an architectural style where software responsibilities are divided among the different layers of the - * application. - *

    - * This example demonstrates a traditional 3-layer architecture consisting of data access layer, business layer and - * presentation layer. - *

    - * The data access layer is formed of Spring Data repositories CakeDao, CakeToppingDao and - * CakeLayerDao. The repositories can be used for CRUD operations on cakes, cake toppings and cake layers - * respectively. - *

    - * The business layer is built on top of the data access layer. CakeBakingService offers methods to - * retrieve available cake toppings and cake layers and baked cakes. Also the service is used to create new cakes out of - * cake toppings and cake layers. - *

    - * The presentation layer is built on the business layer and in this example it simply lists the cakes that have been - * baked. - *

    - * We have applied so called strict layering which means that the layers can only access the classes directly beneath - * them. This leads the solution to create an additional set of DTOs ( CakeInfo, - * CakeToppingInfo, CakeLayerInfo) to translate data between layers. In other words, - * CakeBakingService cannot return entities ( Cake, CakeTopping, - * CakeLayer) directly since these reside on data access layer but instead translates these into business - * layer DTOs (CakeInfo, CakeToppingInfo, CakeLayerInfo) and returns them - * instead. This way the presentation layer does not have any knowledge of other layers than the business layer and thus - * is not affected by changes to them. - * - * @see Cake - * @see CakeTopping - * @see CakeLayer - * @see CakeDao - * @see CakeToppingDao - * @see CakeLayerDao - * @see CakeBakingService - * @see CakeInfo - * @see CakeToppingInfo - * @see CakeLayerInfo - * - */ -public class App { - - private static CakeBakingService cakeBakingService = new CakeBakingServiceImpl(); - - /** - * Application entry point - * - * @param args Command line parameters - */ - public static void main(String[] args) { - - // initialize example data - initializeData(cakeBakingService); - - // create view and render it - CakeViewImpl cakeView = new CakeViewImpl(cakeBakingService); - cakeView.render(); - } - - /** - * Initializes the example data - */ - private static void initializeData(CakeBakingService cakeBakingService) { - cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200)); - cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900)); - cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950)); - cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950)); - cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950)); - cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950)); - - cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350)); - cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350)); - - CakeInfo cake1 = - new CakeInfo(new CakeToppingInfo("candies", 0), Arrays.asList(new CakeLayerInfo( - "chocolate", 0), new CakeLayerInfo("banana", 0), new CakeLayerInfo("strawberry", 0))); - try { - cakeBakingService.bakeNewCake(cake1); - } catch (CakeBakingException e) { - e.printStackTrace(); - } - CakeInfo cake2 = - new CakeInfo(new CakeToppingInfo("cherry", 0), Arrays.asList( - new CakeLayerInfo("vanilla", 0), new CakeLayerInfo("lemon", 0), new CakeLayerInfo( - "strawberry", 0))); - try { - cakeBakingService.bakeNewCake(cake2); - } catch (CakeBakingException e) { - e.printStackTrace(); - } - } -} diff --git a/layers/src/main/java/com/iluwatar/layers/Cake.java b/layers/src/main/java/com/iluwatar/layers/Cake.java deleted file mode 100644 index 10490709e259..000000000000 --- a/layers/src/main/java/com/iluwatar/layers/Cake.java +++ /dev/null @@ -1,90 +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.layers; - -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; - -/** - * - * Cake entity - * - */ -@Entity -public class Cake { - - @Id - @GeneratedValue - private Long id; - - @OneToOne(cascade = CascadeType.REMOVE) - private CakeTopping topping; - - @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER) - private Set layers; - - public Cake() { - setLayers(new HashSet<>()); - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public CakeTopping getTopping() { - return topping; - } - - public void setTopping(CakeTopping topping) { - this.topping = topping; - } - - public Set getLayers() { - return layers; - } - - public final void setLayers(Set layers) { - this.layers = layers; - } - - public void addLayer(CakeLayer layer) { - this.layers.add(layer); - } - - @Override - public String toString() { - return String.format("id=%s topping=%s layers=%s", id, topping, layers.toString()); - } -} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java b/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java deleted file mode 100644 index 080d4f6a42d4..000000000000 --- a/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java +++ /dev/null @@ -1,63 +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.layers; - -import java.util.List; - -/** - * - * Service for cake baking operations - * - */ -public interface CakeBakingService { - - /** - * Bakes new cake according to parameters - */ - void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException; - - /** - * Get all cakes - */ - List getAllCakes(); - - /** - * Store new cake topping - */ - void saveNewTopping(CakeToppingInfo toppingInfo); - - /** - * Get available cake toppings - */ - List getAvailableToppings(); - - /** - * Add new cake layer - */ - void saveNewLayer(CakeLayerInfo layerInfo); - - /** - * Get available cake layers - */ - List getAvailableLayers(); -} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java b/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java deleted file mode 100644 index e8deee73a767..000000000000 --- a/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java +++ /dev/null @@ -1,175 +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.layers; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - * - * Implementation of CakeBakingService - * - */ -@Service -@Transactional -public class CakeBakingServiceImpl implements CakeBakingService { - - private AbstractApplicationContext context; - - public CakeBakingServiceImpl() { - this.context = new ClassPathXmlApplicationContext("applicationContext.xml"); - } - - @Override - public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException { - List allToppings = getAvailableToppingEntities(); - List matchingToppings = - allToppings.stream().filter(t -> t.getName().equals(cakeInfo.cakeToppingInfo.name)) - .collect(Collectors.toList()); - if (matchingToppings.isEmpty()) { - throw new CakeBakingException(String.format("Topping %s is not available", - cakeInfo.cakeToppingInfo.name)); - } - List allLayers = getAvailableLayerEntities(); - Set foundLayers = new HashSet<>(); - for (CakeLayerInfo info : cakeInfo.cakeLayerInfos) { - Optional found = - allLayers.stream().filter(layer -> layer.getName().equals(info.name)).findFirst(); - if (!found.isPresent()) { - throw new CakeBakingException(String.format("Layer %s is not available", info.name)); - } else { - foundLayers.add(found.get()); - } - } - CakeToppingDao toppingBean = context.getBean(CakeToppingDao.class); - CakeTopping topping = toppingBean.findOne(matchingToppings.iterator().next().getId()); - CakeDao cakeBean = context.getBean(CakeDao.class); - Cake cake = new Cake(); - cake.setTopping(topping); - cake.setLayers(foundLayers); - cakeBean.save(cake); - topping.setCake(cake); - toppingBean.save(topping); - CakeLayerDao layerBean = context.getBean(CakeLayerDao.class); - for (CakeLayer layer : foundLayers) { - layer.setCake(cake); - layerBean.save(layer); - } - } - - @Override - public void saveNewTopping(CakeToppingInfo toppingInfo) { - CakeToppingDao bean = context.getBean(CakeToppingDao.class); - bean.save(new CakeTopping(toppingInfo.name, toppingInfo.calories)); - } - - @Override - public void saveNewLayer(CakeLayerInfo layerInfo) { - CakeLayerDao bean = context.getBean(CakeLayerDao.class); - bean.save(new CakeLayer(layerInfo.name, layerInfo.calories)); - } - - private List getAvailableToppingEntities() { - CakeToppingDao bean = context.getBean(CakeToppingDao.class); - List result = new ArrayList<>(); - Iterator iterator = bean.findAll().iterator(); - while (iterator.hasNext()) { - CakeTopping topping = iterator.next(); - if (topping.getCake() == null) { - result.add(topping); - } - } - return result; - } - - @Override - public List getAvailableToppings() { - CakeToppingDao bean = context.getBean(CakeToppingDao.class); - List result = new ArrayList<>(); - Iterator iterator = bean.findAll().iterator(); - while (iterator.hasNext()) { - CakeTopping next = iterator.next(); - if (next.getCake() == null) { - result.add(new CakeToppingInfo(next.getId(), next.getName(), next.getCalories())); - } - } - return result; - } - - private List getAvailableLayerEntities() { - CakeLayerDao bean = context.getBean(CakeLayerDao.class); - List result = new ArrayList<>(); - Iterator iterator = bean.findAll().iterator(); - while (iterator.hasNext()) { - CakeLayer next = iterator.next(); - if (next.getCake() == null) { - result.add(next); - } - } - return result; - } - - @Override - public List getAvailableLayers() { - CakeLayerDao bean = context.getBean(CakeLayerDao.class); - List result = new ArrayList<>(); - Iterator iterator = bean.findAll().iterator(); - while (iterator.hasNext()) { - CakeLayer next = iterator.next(); - if (next.getCake() == null) { - result.add(new CakeLayerInfo(next.getId(), next.getName(), next.getCalories())); - } - } - return result; - } - - @Override - public List getAllCakes() { - CakeDao cakeBean = context.getBean(CakeDao.class); - List result = new ArrayList<>(); - Iterator iterator = cakeBean.findAll().iterator(); - while (iterator.hasNext()) { - Cake cake = iterator.next(); - CakeToppingInfo cakeToppingInfo = - new CakeToppingInfo(cake.getTopping().getId(), cake.getTopping().getName(), cake - .getTopping().getCalories()); - List cakeLayerInfos = new ArrayList<>(); - for (CakeLayer layer : cake.getLayers()) { - cakeLayerInfos.add(new CakeLayerInfo(layer.getId(), layer.getName(), layer.getCalories())); - } - CakeInfo cakeInfo = new CakeInfo(cake.getId(), cakeToppingInfo, cakeLayerInfos); - result.add(cakeInfo); - } - return result; - } -} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeLayer.java b/layers/src/main/java/com/iluwatar/layers/CakeLayer.java deleted file mode 100644 index a6dc920f93e3..000000000000 --- a/layers/src/main/java/com/iluwatar/layers/CakeLayer.java +++ /dev/null @@ -1,93 +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.layers; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -/** - * - * CakeLayer entity - * - */ -@Entity -public class CakeLayer { - - @Id - @GeneratedValue - private Long id; - - private String name; - - private int calories; - - @ManyToOne(cascade = CascadeType.ALL) - private Cake cake; - - public CakeLayer() {} - - public CakeLayer(String name, int calories) { - this.setName(name); - this.setCalories(calories); - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public final void setName(String name) { - this.name = name; - } - - public int getCalories() { - return calories; - } - - public final void setCalories(int calories) { - this.calories = calories; - } - - @Override - public String toString() { - return String.format("id=%s name=%s calories=%d", id, name, calories); - } - - public Cake getCake() { - return cake; - } - - public void setCake(Cake cake) { - this.cake = cake; - } -} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeLayerDao.java b/layers/src/main/java/com/iluwatar/layers/CakeLayerDao.java deleted file mode 100644 index d1edebe7aa88..000000000000 --- a/layers/src/main/java/com/iluwatar/layers/CakeLayerDao.java +++ /dev/null @@ -1,36 +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.layers; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -/** - * - * CRUD repository for cake layers - * - */ -@Repository -public interface CakeLayerDao extends CrudRepository { - -} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeTopping.java b/layers/src/main/java/com/iluwatar/layers/CakeTopping.java deleted file mode 100644 index 47b2a44bae2d..000000000000 --- a/layers/src/main/java/com/iluwatar/layers/CakeTopping.java +++ /dev/null @@ -1,93 +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.layers; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToOne; - -/** - * - * CakeTopping entity - * - */ -@Entity -public class CakeTopping { - - @Id - @GeneratedValue - private Long id; - - private String name; - - private int calories; - - @OneToOne(cascade = CascadeType.ALL) - private Cake cake; - - public CakeTopping() {} - - public CakeTopping(String name, int calories) { - this.setName(name); - this.setCalories(calories); - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public final void setName(String name) { - this.name = name; - } - - public final int getCalories() { - return calories; - } - - public void setCalories(int calories) { - this.calories = calories; - } - - @Override - public String toString() { - return String.format("id=%s name=%s calories=%d", id, name, calories); - } - - public Cake getCake() { - return cake; - } - - public void setCake(Cake cake) { - this.cake = cake; - } -} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeToppingDao.java b/layers/src/main/java/com/iluwatar/layers/CakeToppingDao.java deleted file mode 100644 index fdbc0f3b4905..000000000000 --- a/layers/src/main/java/com/iluwatar/layers/CakeToppingDao.java +++ /dev/null @@ -1,36 +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.layers; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -/** - * - * CRUD repository cake toppings - * - */ -@Repository -public interface CakeToppingDao extends CrudRepository { - -} diff --git a/layers/src/main/java/com/iluwatar/layers/View.java b/layers/src/main/java/com/iluwatar/layers/View.java deleted file mode 100644 index 7cf56530807d..000000000000 --- a/layers/src/main/java/com/iluwatar/layers/View.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.layers; - -/** - * - * View interface - * - */ -public interface View { - - void render(); - -} diff --git a/layers/src/main/resources/META-INF/persistence.xml b/layers/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index da9820d8a7db..000000000000 --- a/layers/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/layers/src/main/resources/applicationContext.xml b/layers/src/main/resources/applicationContext.xml deleted file mode 100644 index eca3670b0fbf..000000000000 --- a/layers/src/main/resources/applicationContext.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/layers/src/main/resources/logback.xml b/layers/src/main/resources/logback.xml deleted file mode 100644 index 1da6e5828175..000000000000 --- a/layers/src/main/resources/logback.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - layers.log - - layers-%d.log - 5 - - - %-5p [%d{ISO8601,UTC}] %c: %m%n - - - - - - %-5p [%d{ISO8601,UTC}] %c: %m%n - - - - - - - - - - - - - - - - - - diff --git a/layers/src/test/java/com/iluwatar/layers/AppTest.java b/layers/src/test/java/com/iluwatar/layers/AppTest.java deleted file mode 100644 index aa14e039d050..000000000000 --- a/layers/src/test/java/com/iluwatar/layers/AppTest.java +++ /dev/null @@ -1,39 +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.layers; - -import org.junit.jupiter.api.Test; - -/** - * - * Application test - * - */ -public class AppTest { - - @Test - public void test() { - String[] args = {}; - App.main(args); - } -} diff --git a/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java b/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java deleted file mode 100644 index e13e148a3723..000000000000 --- a/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java +++ /dev/null @@ -1,52 +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.layers; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -/** - * Date: 12/15/15 - 7:57 PM - * - * @author Jeroen Meulemeester - */ -public class CakeBakingExceptionTest { - - @Test - public void testConstructor() throws Exception { - final CakeBakingException exception = new CakeBakingException(); - assertNull(exception.getMessage()); - assertNull(exception.getCause()); - } - - @Test - public void testConstructorWithMessage() throws Exception { - final String expectedMessage = "message"; - final CakeBakingException exception = new CakeBakingException(expectedMessage); - assertEquals(expectedMessage, exception.getMessage()); - assertNull(exception.getCause()); - } - -} diff --git a/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java b/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java deleted file mode 100644 index f740fb5f4691..000000000000 --- a/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java +++ /dev/null @@ -1,186 +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.layers; - -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Date: 12/15/15 - 9:55 PM - * - * @author Jeroen Meulemeester - */ -public class CakeBakingServiceImplTest { - - @Test - public void testLayers() throws CakeBakingException { - final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); - - final List initialLayers = service.getAvailableLayers(); - assertNotNull(initialLayers); - assertTrue(initialLayers.isEmpty()); - - service.saveNewLayer(new CakeLayerInfo("Layer1", 1000)); - service.saveNewLayer(new CakeLayerInfo("Layer2", 2000)); - - final List availableLayers = service.getAvailableLayers(); - assertNotNull(availableLayers); - assertEquals(2, availableLayers.size()); - for (final CakeLayerInfo layer : availableLayers) { - assertNotNull(layer.id); - assertNotNull(layer.name); - assertNotNull(layer.toString()); - assertTrue(layer.calories > 0); - } - - } - - @Test - public void testToppings() throws CakeBakingException { - final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); - - final List initialToppings = service.getAvailableToppings(); - assertNotNull(initialToppings); - assertTrue(initialToppings.isEmpty()); - - service.saveNewTopping(new CakeToppingInfo("Topping1", 1000)); - service.saveNewTopping(new CakeToppingInfo("Topping2", 2000)); - - final List availableToppings = service.getAvailableToppings(); - assertNotNull(availableToppings); - assertEquals(2, availableToppings.size()); - for (final CakeToppingInfo topping : availableToppings) { - assertNotNull(topping.id); - assertNotNull(topping.name); - assertNotNull(topping.toString()); - assertTrue(topping.calories > 0); - } - - } - - @Test - public void testBakeCakes() throws CakeBakingException { - final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); - - final List initialCakes = service.getAllCakes(); - assertNotNull(initialCakes); - assertTrue(initialCakes.isEmpty()); - - final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000); - final CakeToppingInfo topping2 = new CakeToppingInfo("Topping2", 2000); - service.saveNewTopping(topping1); - service.saveNewTopping(topping2); - - final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); - final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000); - final CakeLayerInfo layer3 = new CakeLayerInfo("Layer3", 2000); - service.saveNewLayer(layer1); - service.saveNewLayer(layer2); - service.saveNewLayer(layer3); - - service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2))); - service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer3))); - - final List allCakes = service.getAllCakes(); - assertNotNull(allCakes); - assertEquals(2, allCakes.size()); - for (final CakeInfo cakeInfo : allCakes) { - assertNotNull(cakeInfo.id); - assertNotNull(cakeInfo.cakeToppingInfo); - assertNotNull(cakeInfo.cakeLayerInfos); - assertNotNull(cakeInfo.toString()); - assertFalse(cakeInfo.cakeLayerInfos.isEmpty()); - assertTrue(cakeInfo.calculateTotalCalories() > 0); - } - - } - - @Test - public void testBakeCakeMissingTopping() throws CakeBakingException { - final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); - - final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); - final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000); - service.saveNewLayer(layer1); - service.saveNewLayer(layer2); - - final CakeToppingInfo missingTopping = new CakeToppingInfo("Topping1", 1000); - assertThrows(CakeBakingException.class, () -> { - service.bakeNewCake(new CakeInfo(missingTopping, Arrays.asList(layer1, layer2))); - }); - } - - @Test - public void testBakeCakeMissingLayer() throws CakeBakingException { - final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); - - final List initialCakes = service.getAllCakes(); - assertNotNull(initialCakes); - assertTrue(initialCakes.isEmpty()); - - final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000); - service.saveNewTopping(topping1); - - final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); - service.saveNewLayer(layer1); - - final CakeLayerInfo missingLayer = new CakeLayerInfo("Layer2", 2000); - assertThrows(CakeBakingException.class, () -> { - service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, missingLayer))); - }); - } - - @Test - public void testBakeCakesUsedLayer() throws CakeBakingException { - final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); - - final List initialCakes = service.getAllCakes(); - assertNotNull(initialCakes); - assertTrue(initialCakes.isEmpty()); - - final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000); - final CakeToppingInfo topping2 = new CakeToppingInfo("Topping2", 2000); - service.saveNewTopping(topping1); - service.saveNewTopping(topping2); - - final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); - final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000); - service.saveNewLayer(layer1); - service.saveNewLayer(layer2); - - service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2))); - assertThrows(CakeBakingException.class, () -> { - service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer2))); - }); - } - -} diff --git a/layers/src/test/java/com/iluwatar/layers/CakeTest.java b/layers/src/test/java/com/iluwatar/layers/CakeTest.java deleted file mode 100644 index f71a0b35d4ce..000000000000 --- a/layers/src/test/java/com/iluwatar/layers/CakeTest.java +++ /dev/null @@ -1,119 +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.layers; - -import org.junit.jupiter.api.Test; - -import java.util.HashSet; -import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Date: 12/15/15 - 8:02 PM - * - * @author Jeroen Meulemeester - */ -public class CakeTest { - - @Test - public void testSetId() { - final Cake cake = new Cake(); - assertNull(cake.getId()); - - final Long expectedId = Long.valueOf(1234L); - cake.setId(expectedId); - assertEquals(expectedId, cake.getId()); - } - - @Test - public void testSetTopping() { - final Cake cake = new Cake(); - assertNull(cake.getTopping()); - - final CakeTopping expectedTopping = new CakeTopping("DummyTopping", 1000); - cake.setTopping(expectedTopping); - assertEquals(expectedTopping, cake.getTopping()); - } - - @Test - public void testSetLayers() { - final Cake cake = new Cake(); - assertNotNull(cake.getLayers()); - assertTrue(cake.getLayers().isEmpty()); - - final Set expectedLayers = new HashSet<>(); - expectedLayers.add(new CakeLayer("layer1", 1000)); - expectedLayers.add(new CakeLayer("layer2", 2000)); - expectedLayers.add(new CakeLayer("layer3", 3000)); - - cake.setLayers(expectedLayers); - assertEquals(expectedLayers, cake.getLayers()); - } - - @Test - public void testAddLayer() { - final Cake cake = new Cake(); - assertNotNull(cake.getLayers()); - assertTrue(cake.getLayers().isEmpty()); - - final Set initialLayers = new HashSet<>(); - initialLayers.add(new CakeLayer("layer1", 1000)); - initialLayers.add(new CakeLayer("layer2", 2000)); - - cake.setLayers(initialLayers); - assertEquals(initialLayers, cake.getLayers()); - - final CakeLayer newLayer = new CakeLayer("layer3", 3000); - cake.addLayer(newLayer); - - final Set expectedLayers = new HashSet<>(); - expectedLayers.addAll(initialLayers); - expectedLayers.addAll(initialLayers); - expectedLayers.add(newLayer); - assertEquals(expectedLayers, cake.getLayers()); - } - - @Test - public void testToString() { - final CakeTopping topping = new CakeTopping("topping", 20); - topping.setId(2345L); - - final CakeLayer layer = new CakeLayer("layer", 100); - layer.setId(3456L); - - final Cake cake = new Cake(); - cake.setId(1234L); - cake.setTopping(topping); - cake.addLayer(layer); - - final String expected = "id=1234 topping=id=2345 name=topping calories=20 " - + "layers=[id=3456 name=layer calories=100]"; - assertEquals(expected, cake.toString()); - - } - -} diff --git a/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java b/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java deleted file mode 100644 index 4aed18869e9e..000000000000 --- a/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java +++ /dev/null @@ -1,110 +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.layers; - -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.AppenderBase; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Date: 12/15/15 - 10:04 PM - * - * @author Jeroen Meulemeester - */ -public class CakeViewImplTest { - - private InMemoryAppender appender; - - @BeforeEach - public void setUp() { - appender = new InMemoryAppender(CakeViewImpl.class); - } - - @AfterEach - public void tearDown() { - appender.stop(); - } - - /** - * Verify if the cake view renders the expected result - */ - @Test - public void testRender() { - - final List layers = new ArrayList<>(); - layers.add(new CakeLayerInfo("layer1", 1000)); - layers.add(new CakeLayerInfo("layer2", 2000)); - layers.add(new CakeLayerInfo("layer3", 3000)); - - final List cakes = new ArrayList<>(); - final CakeInfo cake = new CakeInfo(new CakeToppingInfo("topping", 1000), layers); - cakes.add(cake); - - final CakeBakingService bakingService = mock(CakeBakingService.class); - when(bakingService.getAllCakes()).thenReturn(cakes); - - final CakeViewImpl cakeView = new CakeViewImpl(bakingService); - - assertEquals(0, appender.getLogSize()); - - cakeView.render(); - assertEquals(cake.toString(), appender.getLastMessage()); - - } - - private class InMemoryAppender extends AppenderBase { - - private List log = new LinkedList<>(); - - public InMemoryAppender(Class clazz) { - ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); - start(); - } - - @Override - protected void append(ILoggingEvent eventObject) { - log.add(eventObject); - } - - public String getLastMessage() { - return log.get(log.size() - 1).getFormattedMessage(); - } - - public int getLogSize() { - return log.size(); - } - } - -} diff --git a/lazy-loading/README.md b/lazy-loading/README.md index d40061293531..2d448da2f034 100644 --- a/lazy-loading/README.md +++ b/lazy-loading/README.md @@ -1,33 +1,178 @@ --- -layout: pattern -title: Lazy Loading -folder: lazy-loading -permalink: /patterns/lazy-loading/ -categories: Other -tags: - - Java - - Difficulty-Beginner - - Idiom - - Performance +title: "Lazy Loading Pattern in Java: Enhancing Performance with On-Demand Object Initialization" +shortTitle: Lazy Loading +description: "Learn how to implement the Lazy Loading design pattern in Java to optimize memory usage and improve application startup times. Discover practical examples, benefits, and best practices for efficient resource management." +category: Performance optimization +language: en +tag: + - Instantiation + - Memory management + - Optimization + - Performance + - Persistence + - Resource management --- -## Intent -Lazy loading is a design pattern commonly used to defer -initialization of an object until the point at which it is needed. It can -contribute to efficiency in the program's operation if properly and -appropriately used. +## Also known as -![alt text](./etc/lazy-loading.png "Lazy Loading") +* Lazy Initialization -## Applicability -Use the Lazy Loading idiom when +## Intent of Lazy Loading Design Pattern -* eager loading is expensive or the object to be loaded might not be needed at all +The Lazy Loading design pattern in Java defers object initialization until the object is actually needed, minimizing memory usage and reducing startup times. This technique is crucial for optimizing Java application performance. -## Real world examples +## Detailed Explanation of Lazy Loading Pattern with Real-World Examples +Real-world example + +> A real-world analogy for the Lazy Loading pattern in Java is using lights in a smart home. Instead of switching all lights on at once when someone enters the house, motion sensors detect and turn on lights only in rooms being used. This mirrors how Java developers can optimize performance by delaying object creation. + +In plain words + +> The Lazy Loading pattern defers the creation of an object or resource until it's actually needed, optimizing memory usage and improving performance. + +Wikipedia says + +> Lazy loading (also known as asynchronous loading) is a technique used in computer programming, especially web design and web development, to defer initialization of an object until it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used. This makes it ideal in use cases where network content is accessed and initialization times are to be kept at a minimum, such as in the case of web pages. For example, deferring loading of images on a web page until they are needed for viewing can make the initial display of the web page faster. The opposite of lazy loading is eager loading. + +Sequence diagram + +![Lazy Loading Sequence Diagram](./etc/lazy-loading-sequence-diagram.png) + +## Programmatic Example of Lazy Loading Pattern in Java + +The Lazy Loading design pattern is a performance optimization technique that delays the initialization of an object or a costly computation until it's absolutely necessary. This pattern can significantly improve the performance of your application by avoiding unnecessary computation and reducing memory usage. + +In the provided code, we can see an example of the Lazy Loading pattern in the `App`, `HolderNaive`, `HolderThreadSafe`, and `Java8Holder` classes. + +The `App` class is the entry point of the application. It creates instances of `HolderNaive`, `HolderThreadSafe`, and `Java8Holder`, and retrieves the `Heavy` object from them. + +```java +@Slf4j +public class App { + + public static void main(String[] args) { + + var holderNaive = new HolderNaive(); + var heavy = holderNaive.getHeavy(); + LOGGER.info("heavy={}", heavy); + + var holderThreadSafe = new HolderThreadSafe(); + var another = holderThreadSafe.getHeavy(); + LOGGER.info("another={}", another); + + var java8Holder = new Java8Holder(); + var next = java8Holder.getHeavy(); + LOGGER.info("next={}", next); + } +} +``` + +The `HolderNaive`, `HolderThreadSafe`, and `Java8Holder` classes are implementations of the Lazy Loading pattern with increasing sophistication. + +The `HolderNaive` class is a simple, non-thread-safe implementation of the pattern. + +```java +public class HolderNaive { + private Heavy heavy; + + public HolderNaive() { + LOGGER.info("HolderNaive created"); + } + + public Heavy getHeavy() { + if (heavy == null) { + heavy = new Heavy(); + } + return heavy; + } +} +``` + +The `HolderThreadSafe` class is a thread-safe implementation of the pattern, but with heavy synchronization on each access. + +```java +public class HolderThreadSafe { + private Heavy heavy; + + public synchronized Heavy getHeavy() { + if (heavy == null) { + heavy = new Heavy(); + } + return heavy; + } +} +``` + +The `Java8Holder` class is the most efficient implementation of the pattern, utilizing Java 8 features. + +```java +public class Java8Holder { + + private Supplier heavy = this::createAndCacheHeavy; + + public Java8Holder() { + LOGGER.info("Java8Holder created"); + } + + public Heavy getHeavy() { + return heavy.get(); + } + + private synchronized Heavy createAndCacheHeavy() { + class HeavyFactory implements Supplier { + private final Heavy heavyInstance = new Heavy(); + + public Heavy get() { + return heavyInstance; + } + } + + if (!(heavy instanceof HeavyFactory)) { + heavy = new HeavyFactory(); + } + + return heavy.get(); + } +} +``` + +In this example, the `App` class retrieves a `Heavy` object from `HolderNaive`, `HolderThreadSafe`, and `Java8Holder`. These classes delay the creation of the `Heavy` object until it's actually needed, demonstrating the Lazy Loading pattern. + +## When to Use the Lazy Loading Pattern in Java + +Use Lazy Loading when: + +* An object is resource-intensive to create and might not always be used. +* You need to delay object creation to optimize memory usage or improve startup times. +* Loading data or resources should happen just-in-time rather than at application startup. + +## Real-World Applications of Lazy Loading Pattern in Java + +* Hibernate (Java ORM Framework): Delays loading of related objects until they are accessed, leveraging the Lazy Loading pattern to optimize Java application performance. * JPA annotations @OneToOne, @OneToMany, @ManyToOne, @ManyToMany and fetch = FetchType.LAZY +* Spring Framework (Dependency Injection): Loads beans only when required, reducing application startup time. + +## Benefits and Trade-offs of Lazy Loading Pattern + +Benefits: + +* Reduces memory usage by initializing objects only when required. +* Improves application startup performance by postponing expensive object creation. + +Trade-offs: + +* Complexity in implementation if objects are interdependent. +* Risk of latency spikes if initialization occurs at an unexpected point. + +## Related Java Design Patterns + +* [Proxy](https://java-design-patterns.com/patterns/proxy/): Can act as a placeholder for lazy-loaded objects, deferring their actual loading until necessary. +* Virtual Proxy: Specific type of Proxy that handles object creation on demand. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Often combined with Lazy Loading to ensure only one instance of an object is created and loaded lazily. -## Credits +## References and Credits -* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Java Performance: The Definitive Guide: Getting the Most Out of Your Code](https://amzn.to/3Wu5neF) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/lazy-loading/etc/lazy-loading-sequence-diagram.png b/lazy-loading/etc/lazy-loading-sequence-diagram.png new file mode 100644 index 000000000000..30dde481c691 Binary files /dev/null and b/lazy-loading/etc/lazy-loading-sequence-diagram.png differ diff --git a/lazy-loading/etc/lazy-loading.urm.puml b/lazy-loading/etc/lazy-loading.urm.puml new file mode 100644 index 000000000000..aaf49f1df941 --- /dev/null +++ b/lazy-loading/etc/lazy-loading.urm.puml @@ -0,0 +1,40 @@ +@startuml +package com.iluwatar.lazy.loading { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Heavy { + - LOGGER : Logger {static} + + Heavy() + } + class HolderNaive { + - LOGGER : Logger {static} + - heavy : Heavy + + HolderNaive() + + getHeavy() : Heavy + } + class HolderThreadSafe { + - LOGGER : Logger {static} + - heavy : Heavy + + HolderThreadSafe() + + getHeavy() : Heavy + } + class Java8Holder { + - LOGGER : Logger {static} + - heavy : Supplier + + Java8Holder() + - createAndCacheHeavy() : Heavy + + getHeavy() : Heavy + } + ~class HeavyFactory { + - heavyInstance : Heavy + ~ HeavyFactory() + + get() : Heavy + } +} +HolderThreadSafe --> "-heavy" Heavy +HolderNaive --> "-heavy" Heavy +HeavyFactory --> "-heavyInstance" Heavy +@enduml \ No newline at end of file diff --git a/lazy-loading/pom.xml b/lazy-loading/pom.xml index 6664ddcc7e23..9b2061c2cc6a 100644 --- a/lazy-loading/pom.xml +++ b/lazy-loading/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT lazy-loading - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.lazy.loading.App + + + + + + + + diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java index 0a5eac75953f..44889905e688 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,43 +24,39 @@ */ package com.iluwatar.lazy.loading; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * * Lazy loading idiom defers object creation until needed. - *

    - * This example shows different implementations of the pattern with increasing sophistication. - *

    - * Additional information and lazy loading flavours are described in - * http://martinfowler.com/eaaCatalog/lazyLoad.html * + *

    This example shows different implementations of the pattern with increasing sophistication. + * + *

    Additional information and lazy loading flavours are described in + * http://martinfowler.com/eaaCatalog/lazyLoad.html */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { // Simple lazy loader - not thread safe - HolderNaive holderNaive = new HolderNaive(); - Heavy heavy = holderNaive.getHeavy(); + var holderNaive = new HolderNaive(); + var heavy = holderNaive.getHeavy(); LOGGER.info("heavy={}", heavy); // Thread safe lazy loader, but with heavy synchronization on each access - HolderThreadSafe holderThreadSafe = new HolderThreadSafe(); - Heavy another = holderThreadSafe.getHeavy(); + var holderThreadSafe = new HolderThreadSafe(); + var another = holderThreadSafe.getHeavy(); LOGGER.info("another={}", another); // The most efficient lazy loader utilizing Java 8 features - Java8Holder java8Holder = new Java8Holder(); - Heavy next = java8Holder.getHeavy(); + var java8Holder = new Java8Holder(); + var next = java8Holder.getHeavy(); LOGGER.info("next={}", next); } } diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java index 1c23611c3136..0c96768b67a1 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,13 @@ */ package com.iluwatar.lazy.loading; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * Heavy objects are expensive to create. - * - */ +/** Heavy objects are expensive to create. */ +@Slf4j public class Heavy { - private static final Logger LOGGER = LoggerFactory.getLogger(Heavy.class); - - /** - * Constructor - */ + /** Constructor. */ public Heavy() { LOGGER.info("Creating Heavy ..."); try { diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java index 5e4552ecfee4..55281a7e666a 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,30 +24,20 @@ */ package com.iluwatar.lazy.loading; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * Simple implementation of the lazy loading idiom. However, this is not thread safe. - * - */ +/** Simple implementation of the lazy loading idiom. However, this is not thread safe. */ +@Slf4j public class HolderNaive { - private static final Logger LOGGER = LoggerFactory.getLogger(HolderNaive.class); - private Heavy heavy; - /** - * Constructor - */ + /** Constructor. */ public HolderNaive() { LOGGER.info("HolderNaive created"); } - /** - * Get heavy object - */ + /** Get heavy object. */ public Heavy getHeavy() { if (heavy == null) { heavy = new Heavy(); diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java index b36ec24ba107..f698a05791da 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,31 +24,23 @@ */ package com.iluwatar.lazy.loading; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** - * * Same as HolderNaive but with added synchronization. This implementation is thread safe, but each * {@link #getHeavy()} call costs additional synchronization overhead. - * */ +@Slf4j public class HolderThreadSafe { - private static final Logger LOGGER = LoggerFactory.getLogger(HolderThreadSafe.class); - private Heavy heavy; - /** - * Constructor - */ + /** Constructor. */ public HolderThreadSafe() { LOGGER.info("HolderThreadSafe created"); } - /** - * Get heavy object - */ + /** Get heavy object. */ public synchronized Heavy getHeavy() { if (heavy == null) { heavy = new Heavy(); diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java index faa553c5eb36..375c594bab6c 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,22 +24,17 @@ */ package com.iluwatar.lazy.loading; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.function.Supplier; +import lombok.extern.slf4j.Slf4j; /** - * * This lazy loader is thread safe and more efficient than {@link HolderThreadSafe}. It utilizes * Java 8 functional interface {@link Supplier} as {@link Heavy} factory. - * */ +@Slf4j public class Java8Holder { - private static final Logger LOGGER = LoggerFactory.getLogger(Java8Holder.class); - - private Supplier heavy = () -> createAndCacheHeavy(); + private Supplier heavy = this::createAndCacheHeavy; public Java8Holder() { LOGGER.info("Java8Holder created"); @@ -56,9 +53,11 @@ public Heavy get() { return heavyInstance; } } - if (!HeavyFactory.class.isInstance(heavy)) { + + if (!(heavy instanceof HeavyFactory)) { heavy = new HeavyFactory(); } + return heavy.get(); } } diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java index 56b5a2c3d8f4..72cdd9e478d5 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,19 +24,15 @@ */ package com.iluwatar.lazy.loading; -import org.junit.jupiter.api.Test; - import static java.time.Duration.ofMillis; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTimeout; -/** - * Date: 12/19/15 - 11:58 AM - * - * @author Jeroen Meulemeester - */ +import org.junit.jupiter.api.Test; + +/** AbstractHolderTest */ public abstract class AbstractHolderTest { /** @@ -49,19 +47,20 @@ public abstract class AbstractHolderTest { * * @return The lazy loaded {@link Heavy} object */ - abstract Heavy getHeavy() throws Exception; + abstract Heavy getHeavy(); /** * This test shows that the heavy field is not instantiated until the method getHeavy is called */ @Test - public void testGetHeavy() throws Exception { - assertTimeout(ofMillis(3000), () -> { - assertNull(getInternalHeavyValue()); - assertNotNull(getHeavy()); - assertNotNull(getInternalHeavyValue()); - assertSame(getHeavy(), getInternalHeavyValue()); - }); + void testGetHeavy() { + assertTimeout( + ofMillis(3000), + () -> { + assertNull(getInternalHeavyValue()); + assertNotNull(getHeavy()); + assertNotNull(getInternalHeavyValue()); + assertSame(getHeavy(), getInternalHeavyValue()); + }); } - } diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java index bd43b0d35910..3f3e5b28a063 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.lazy.loading; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderNaiveTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderNaiveTest.java index 39e8a55d70ab..e165c4a9b6a6 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderNaiveTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderNaiveTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,14 @@ */ package com.iluwatar.lazy.loading; -import java.lang.reflect.Field; - -/** - * Date: 12/19/15 - 12:05 PM - * - * @author Jeroen Meulemeester - */ -public class HolderNaiveTest extends AbstractHolderTest { +/** HolderNaiveTest */ +class HolderNaiveTest extends AbstractHolderTest { private final HolderNaive holder = new HolderNaive(); @Override Heavy getInternalHeavyValue() throws Exception { - final Field holderField = HolderNaive.class.getDeclaredField("heavy"); + final var holderField = HolderNaive.class.getDeclaredField("heavy"); holderField.setAccessible(true); return (Heavy) holderField.get(this.holder); } @@ -44,5 +40,4 @@ Heavy getInternalHeavyValue() throws Exception { Heavy getHeavy() { return holder.getHeavy(); } - -} \ No newline at end of file +} diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java index d4017363d392..e6c8efb4b370 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,27 +24,20 @@ */ package com.iluwatar.lazy.loading; -import java.lang.reflect.Field; - -/** - * Date: 12/19/15 - 12:19 PM - * - * @author Jeroen Meulemeester - */ -public class HolderThreadSafeTest extends AbstractHolderTest { +/** HolderThreadSafeTest */ +class HolderThreadSafeTest extends AbstractHolderTest { private final HolderThreadSafe holder = new HolderThreadSafe(); @Override Heavy getInternalHeavyValue() throws Exception { - final Field holderField = HolderThreadSafe.class.getDeclaredField("heavy"); + final var holderField = HolderThreadSafe.class.getDeclaredField("heavy"); holderField.setAccessible(true); return (Heavy) holderField.get(this.holder); } @Override - Heavy getHeavy() throws Exception { + Heavy getHeavy() { return this.holder.getHeavy(); } - -} \ No newline at end of file +} diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/Java8HolderTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/Java8HolderTest.java index 3e5078397653..41c1d4886fe2 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/Java8HolderTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/Java8HolderTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,31 +24,25 @@ */ package com.iluwatar.lazy.loading; -import java.lang.reflect.Field; import java.util.function.Supplier; -/** - * Date: 12/19/15 - 12:27 PM - * - * @author Jeroen Meulemeester - */ -public class Java8HolderTest extends AbstractHolderTest { +/** Java8HolderTest */ +class Java8HolderTest extends AbstractHolderTest { private final Java8Holder holder = new Java8Holder(); - @Override Heavy getInternalHeavyValue() throws Exception { - final Field holderField = Java8Holder.class.getDeclaredField("heavy"); + final var holderField = Java8Holder.class.getDeclaredField("heavy"); holderField.setAccessible(true); - final Supplier supplier = (Supplier) holderField.get(this.holder); - final Class supplierClass = supplier.getClass(); + final var supplier = (Supplier) holderField.get(this.holder); + final var supplierClass = supplier.getClass(); // This is a little fishy, but I don't know another way to test this: // The lazy holder is at first a lambda, but gets replaced with a new supplier after loading ... if (supplierClass.isLocalClass()) { - final Field instanceField = supplierClass.getDeclaredField("heavyInstance"); + final var instanceField = supplierClass.getDeclaredField("heavyInstance"); instanceField.setAccessible(true); return (Heavy) instanceField.get(supplier); } else { @@ -55,8 +51,7 @@ Heavy getInternalHeavyValue() throws Exception { } @Override - Heavy getHeavy() throws Exception { + Heavy getHeavy() { return holder.getHeavy(); } - -} \ No newline at end of file +} diff --git a/leader-election/README.md b/leader-election/README.md new file mode 100644 index 000000000000..12c898e3cbc2 --- /dev/null +++ b/leader-election/README.md @@ -0,0 +1,183 @@ +--- +title: "Leader Election Pattern in Java: Mastering Node Coordination and Consensus" +shortTitle: Leader Election +description: "Learn how the Leader Election design pattern helps Java applications maintain consistency, fault tolerance, and scalability in distributed systems. Discover examples, use cases, and implementation details." +category: Concurrency +language: en +tag: + - API design + - Cloud distributed + - Fault tolerance + - Scalability + - Synchronization +--- + +## Also known as + +* Coordinator Election +* Master Election + +## Intent of Leader Election Design Pattern + +The Leader Election design pattern is crucial for enabling a system to elect a leader from a group of nodes, ensuring the leader is consistently recognized and able to coordinate tasks while other nodes remain followers. This pattern is fundamental in distributed systems, particularly for achieving fault tolerance and high availability. + +## Detailed Explanation of Leader Election Pattern with Real-World Examples + +Real-world example + +> A real-world analogy to the Leader Election pattern is the election of a team captain in sports. All team members (nodes) participate in the election process, following a set of agreed-upon rules (protocol). Once a captain (leader) is chosen, they assume responsibility for coordinating strategies, giving directions, and representing the team in discussions. If the captain is injured or unavailable, the team holds a new election or appoints a vice-captain (failover mechanism) to ensure that leadership and direction are maintained consistently. + +In plain words + +> The leader election pattern is a design approach that enables a distributed system to select one node as the coordinator or leader to manage tasks and maintain order, while other nodes operate as followers. + +Wikipedia says + +> In distributed computing, leader election is the process of designating a single process as the organizer of some task distributed among several computers (nodes). Before the task has begun, all network nodes are either unaware which node will serve as the "leader" (or coordinator) of the task, or unable to communicate with the current coordinator. After a leader election algorithm has been run, however, each node throughout the network recognizes a particular, unique node as the task leader. + +Sequence diagram + +![Leader Election Sequence Diagram](./etc/leader-election-sequence-diagram.png) + +## Programmatic Example of Leader Election Pattern in Java + +The Leader Election pattern is a design approach that enables a distributed system to select one node as the coordinator or leader to manage tasks and maintain order, while other nodes operate as followers. This pattern is particularly useful in distributed systems where one node needs to act as a central coordinator for a specific function or decision-making process. + +In the provided code, we have an `AbstractMessageManager` class and `AbstractInstance` class. The `AbstractMessageManager` class is responsible for managing messages between instances and finding the next instance (potential leader) based on certain conditions. The `AbstractInstance` class represents a node in the distributed system. + +Let's break down the code and explain how it works: + +```java +public abstract class AbstractMessageManager implements MessageManager { + + protected Map instanceMap; + + public AbstractMessageManager(Map instanceMap) { + this.instanceMap = instanceMap; + } + + protected Instance findNextInstance(int currentId) { + // Implementation details... + } + +} +``` + +The `AbstractMessageManager` class manages the instances in the system. It contains a map of instances, where the key is the instance ID and the value is the instance itself. The `findNextInstance` method is used to find the next instance with the smallest ID that is alive. This method can be used in the leader election process to determine the next leader if the current leader fails. + +```java +public abstract class AbstractInstance implements Instance { + + protected int id; + protected boolean alive; + protected MessageManager messageManager; + + public AbstractInstance(MessageManager messageManager, int id) { + this.messageManager = messageManager; + this.id = id; + this.alive = true; + } + + public boolean isAlive() { + return alive; + } + + public void setAlive(boolean alive) { + this.alive = alive; + } + + public void onMessage(Message message) { + // Implementation details... + } + +} +``` + +The `AbstractInstance` class represents a node in the distributed system. Each instance can check if it's alive, set its health status, and consume messages from other instances. + +Now, let's look at the `BullyApp` and `RingApp` classes, which implement two different leader election algorithms: + +```java +public class BullyApp { + + public static void main(String[] args) { + + Map instanceMap = new HashMap<>(); + var messageManager = new BullyMessageManager(instanceMap); + + var instance1 = new BullyInstance(messageManager, 1, 1); + // ... more instances ... + + instanceMap.put(1, instance1); + // ... more instances ... + + instance1.setAlive(false); + } +} +``` + +The `BullyApp` class implements the Bully algorithm for leader election. In this algorithm, when a node notices the leader is down, it starts an election by sending an election message to all nodes with higher IDs. If it doesn't receive a response, it declares itself the leader and sends a victory message to all nodes with lower IDs. + +```java +public class RingApp { + + public static void main(String[] args) { + + Map instanceMap = new HashMap<>(); + var messageManager = new RingMessageManager(instanceMap); + + var instance1 = new RingInstance(messageManager, 1, 1); + // ... more instances ... + + instanceMap.put(1, instance1); + // ... more instances ... + + instance1.setAlive(false); + } +} +``` + +The `RingApp` class implements the Ring algorithm for leader election. In this algorithm, each node sends an election message to its neighbor in a logical ring topology. When a node receives an election message, it passes it on if the ID in the message is higher than its own. The process continues until the message has made a full circle, at which point the node with the highest ID becomes the leader. + +These examples demonstrate how the Leader Election pattern can be implemented in different ways to suit the specific requirements of a distributed system. + +## When to Use the Leader Election Pattern in Java + +Use the Leader Election pattern in Java applications where: + +* A distributed system needs one node to act as the central coordinator for a specific function or decision-making process. +* High availability is essential, and the leader should be replaceable in case of failure. +* Coordination is required across different nodes in a cluster, particularly in cloud environments. + +## Real-World Applications of Leader Election Pattern in Java + +* Apache ZooKeeper: Provides leader election for distributed services. +* Kubernetes: Elects a leader pod to manage stateful workloads. +* Hazelcast: Distributed data grid uses leader election for cluster management. + +## Benefits and Trade-offs of Leader Election Pattern + +Benefits: + +* Consistency: Ensures a single, consistent leader handles coordination tasks. +* Fault Tolerance: Allows for leader replacement if the current leader fails. +* Scalability: Works effectively in large, distributed systems where multiple nodes are present. + +Trade-offs: + +* Complexity: Requires careful implementation to handle network partitions and latency. +* Overhead: Election processes may introduce performance overhead. +* Single Point of Failure: Even with redundancy, the leader can become a bottleneck if not carefully designed. + +## Related Java Design Patterns + +* [Observer](https://java-design-patterns.com/patterns/observer/): Followers can observe changes from the leader to stay updated. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): The leader functions as a single instance, acting as a unique decision-maker. +* [State](https://java-design-patterns.com/patterns/state/): Helps in managing state transitions, particularly in switching leadership roles. + +## References and Credits + +* [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z) +* [Distributed Systems: Principles and Paradigms](https://amzn.to/3UN2vbH) +* [Site Reliability Engineering: How Google Runs Production Systems](https://amzn.to/4brjBRI) +* [Leader Election pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/leader-election) diff --git a/leader-election/etc/leader-election-sequence-diagram.png b/leader-election/etc/leader-election-sequence-diagram.png new file mode 100644 index 000000000000..ab5243ee206a Binary files /dev/null and b/leader-election/etc/leader-election-sequence-diagram.png differ diff --git a/leader-election/etc/leader-election.urm.png b/leader-election/etc/leader-election.urm.png new file mode 100644 index 000000000000..85a90b75b636 Binary files /dev/null and b/leader-election/etc/leader-election.urm.png differ diff --git a/leader-election/etc/leader-election.urm.puml b/leader-election/etc/leader-election.urm.puml new file mode 100644 index 000000000000..c28066f31566 --- /dev/null +++ b/leader-election/etc/leader-election.urm.puml @@ -0,0 +1,120 @@ +@startuml +package com.iluwatar.leaderelection.ring { + class RingApp { + + RingApp() + + main(args : String[]) {static} + } + class RingInstance { + - LOGGER : Logger {static} + + RingInstance(messageManager : MessageManager, localId : int, leaderId : int) + # handleElectionInvokeMessage() + # handleElectionMessage(message : Message) + # handleHeartbeatInvokeMessage() + # handleHeartbeatMessage(message : Message) + # handleLeaderInvokeMessage() + # handleLeaderMessage(message : Message) + } + class RingMessageManager { + + RingMessageManager(instanceMap : Map) + + sendElectionMessage(currentId : int, content : String) : boolean + + sendHeartbeatInvokeMessage(currentId : int) + + sendHeartbeatMessage(leaderId : int) : boolean + + sendLeaderMessage(currentId : int, leaderId : int) : boolean + } +} +package com.iluwatar.leaderelection { + abstract class AbstractInstance { + # HEARTBEAT_INTERVAL : int {static} + - LOGGER : Logger {static} + # alive : boolean + # leaderId : int + # localId : int + # messageManager : MessageManager + # messageQueue : Queue + + AbstractInstance(messageManager : MessageManager, localId : int, leaderId : int) + # handleElectionInvokeMessage() {abstract} + # handleElectionMessage(Message) {abstract} + # handleHeartbeatInvokeMessage() {abstract} + # handleHeartbeatMessage(Message) {abstract} + # handleLeaderInvokeMessage() {abstract} + # handleLeaderMessage(Message) {abstract} + + isAlive() : boolean + + onMessage(message : Message) + - processMessage(message : Message) + + run() + + setAlive(alive : boolean) + } + abstract class AbstractMessageManager { + # instanceMap : Map + + AbstractMessageManager(instanceMap : Map) + # findNextInstance(currentId : int) : Instance + } + interface Instance { + + isAlive() : boolean {abstract} + + onMessage(Message) {abstract} + + setAlive(boolean) {abstract} + } + class Message { + - content : String + - type : MessageType + + Message() + + Message(type : MessageType, content : String) + + equals(o : Object) : boolean + + getContent() : String + + getType() : MessageType + + hashCode() : int + + setContent(content : String) + + setType(type : MessageType) + } + interface MessageManager { + + sendElectionMessage(int, String) : boolean {abstract} + + sendHeartbeatInvokeMessage(int) {abstract} + + sendHeartbeatMessage(int) : boolean {abstract} + + sendLeaderMessage(int, int) : boolean {abstract} + } + enum MessageType { + + ELECTION {static} + + ELECTION_INVOKE {static} + + HEARTBEAT {static} + + HEARTBEAT_INVOKE {static} + + LEADER {static} + + LEADER_INVOKE {static} + + valueOf(name : String) : MessageType {static} + + values() : MessageType[] {static} + } +} +package com.iluwatar.leaderelection.bully { + class BullyApp { + + BullyApp() + + main(args : String[]) {static} + } + class BullyInstance { + - LOGGER : Logger {static} + + BullyInstance(messageManager : MessageManager, localId : int, leaderId : int) + # handleElectionInvokeMessage() + # handleElectionMessage(message : Message) + # handleHeartbeatInvokeMessage() + # handleHeartbeatMessage(message : Message) + # handleLeaderInvokeMessage() + # handleLeaderMessage(message : Message) + - isLeader() : boolean + } + class BullyMessageManager { + + BullyMessageManager(instanceMap : Map) + - findElectionCandidateInstanceList(currentId : int) : List + + sendElectionMessage(currentId : int, content : String) : boolean + + sendHeartbeatInvokeMessage(currentId : int) + + sendHeartbeatMessage(leaderId : int) : boolean + + sendLeaderMessage(currentId : int, leaderId : int) : boolean + } +} +AbstractInstance --> "-messageQueue" Message +Message --> "-type" MessageType +AbstractInstance --> "-messageManager" MessageManager +AbstractInstance ..|> Instance +AbstractMessageManager ..|> MessageManager +BullyInstance --|> AbstractInstance +BullyMessageManager --|> AbstractMessageManager +RingInstance --|> AbstractInstance +RingMessageManager --|> AbstractMessageManager +@enduml \ No newline at end of file diff --git a/leader-election/pom.xml b/leader-election/pom.xml new file mode 100644 index 000000000000..fbe1edbea0c6 --- /dev/null +++ b/leader-election/pom.xml @@ -0,0 +1,83 @@ + + + + 4.0.0 + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + leader-election + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + bully + + + + com.iluwatar.leaderelection.bully.BullyApp + + + ${project.artifactId}-Bully + + + + ring + + + + com.iluwatar.leaderelection.ring.RingApp + + + ${project.artifactId}-Ring + + + + + + + diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java new file mode 100644 index 000000000000..398d0baf306c --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java @@ -0,0 +1,145 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection; + +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import lombok.extern.slf4j.Slf4j; + +/** Abstract class of all the instance implementation classes. */ +@Slf4j +public abstract class AbstractInstance implements Instance, Runnable { + + protected static final int HEARTBEAT_INTERVAL = 5000; + private static final String INSTANCE = "Instance "; + + protected MessageManager messageManager; + protected Queue messageQueue; + protected final int localId; + protected int leaderId; + protected boolean alive; + + /** Constructor of BullyInstance. */ + public AbstractInstance(MessageManager messageManager, int localId, int leaderId) { + this.messageManager = messageManager; + this.messageQueue = new ConcurrentLinkedQueue<>(); + this.localId = localId; + this.leaderId = leaderId; + this.alive = true; + } + + /** The instance will execute the message in its message queue periodically once it is alive. */ + @Override + @SuppressWarnings("squid:S2189") + public void run() { + while (true) { + if (!this.messageQueue.isEmpty()) { + this.processMessage(this.messageQueue.remove()); + } + } + } + + /** + * Once messages are sent to the certain instance, it will firstly be added to the queue and wait + * to be executed. + * + * @param message Message sent by other instances + */ + @Override + public void onMessage(Message message) { + messageQueue.offer(message); + } + + /** + * Check if the instance is alive or not. + * + * @return {@code true} if the instance is alive. + */ + @Override + public boolean isAlive() { + return alive; + } + + /** + * Set the health status of the certain instance. + * + * @param alive {@code true} for alive. + */ + @Override + public void setAlive(boolean alive) { + this.alive = alive; + } + + /** + * Process the message according to its type. + * + * @param message Message polled from queue. + */ + private void processMessage(Message message) { + switch (message.getType()) { + case ELECTION -> { + LOGGER.info(INSTANCE + localId + " - Election Message handling..."); + handleElectionMessage(message); + } + case LEADER -> { + LOGGER.info(INSTANCE + localId + " - Leader Message handling..."); + handleLeaderMessage(message); + } + case HEARTBEAT -> { + LOGGER.info(INSTANCE + localId + " - Heartbeat Message handling..."); + handleHeartbeatMessage(message); + } + case ELECTION_INVOKE -> { + LOGGER.info(INSTANCE + localId + " - Election Invoke Message handling..."); + handleElectionInvokeMessage(); + } + case LEADER_INVOKE -> { + LOGGER.info(INSTANCE + localId + " - Leader Invoke Message handling..."); + handleLeaderInvokeMessage(); + } + case HEARTBEAT_INVOKE -> { + LOGGER.info(INSTANCE + localId + " - Heartbeat Invoke Message handling..."); + handleHeartbeatInvokeMessage(); + } + default -> {} + } + } + + /** + * Abstract methods to handle different types of message. These methods need to be implemented in + * concrete instance class to implement corresponding leader-selection pattern. + */ + protected abstract void handleElectionMessage(Message message); + + protected abstract void handleElectionInvokeMessage(); + + protected abstract void handleLeaderMessage(Message message); + + protected abstract void handleLeaderInvokeMessage(); + + protected abstract void handleHeartbeatMessage(Message message); + + protected abstract void handleHeartbeatInvokeMessage(); +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java new file mode 100644 index 000000000000..d613182e5aa9 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java @@ -0,0 +1,66 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection; + +import java.util.Map; + +/** Abstract class of all the message manager classes. */ +public abstract class AbstractMessageManager implements MessageManager { + + /** Contain all the instances in the system. Key is its ID, and value is the instance itself. */ + protected Map instanceMap; + + /** Constructor of AbstractMessageManager. */ + public AbstractMessageManager(Map instanceMap) { + this.instanceMap = instanceMap; + } + + /** + * Find the next instance with the smallest ID. + * + * @return The next instance. + */ + protected Instance findNextInstance(int currentId) { + Instance result = null; + var candidateList = + instanceMap.keySet().stream() + .filter((i) -> i > currentId && instanceMap.get(i).isAlive()) + .sorted() + .toList(); + if (candidateList.isEmpty()) { + var index = + instanceMap.keySet().stream() + .filter((i) -> instanceMap.get(i).isAlive()) + .sorted() + .toList() + .get(0); + result = instanceMap.get(index); + } else { + var index = candidateList.get(0); + result = instanceMap.get(index); + } + return result; + } +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java new file mode 100644 index 000000000000..a2a16f0f62f9 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java @@ -0,0 +1,50 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection; + +/** Instance interface. */ +public interface Instance { + + /** + * Check if the instance is alive or not. + * + * @return {@code true} if the instance is alive. + */ + boolean isAlive(); + + /** + * Set the health status of the certain instance. + * + * @param alive {@code true} for alive. + */ + void setAlive(boolean alive); + + /** + * Consume messages from other instances. + * + * @param message Message sent by other instances + */ + void onMessage(Message message); +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java b/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java new file mode 100644 index 000000000000..af3788e954fe --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** Message used to transport data between instances. */ +@Setter +@Getter +@EqualsAndHashCode +@AllArgsConstructor +@NoArgsConstructor +public class Message { + + private MessageType type; + private String content; +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java new file mode 100644 index 000000000000..96a030421c65 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java @@ -0,0 +1,62 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection; + +/** MessageManager interface. */ +public interface MessageManager { + + /** + * Send heartbeat message to leader instance to check whether the leader instance is alive. + * + * @param leaderId Instance ID of leader instance. + * @return {@code true} if leader instance is alive, or {@code false} if not. + */ + boolean sendHeartbeatMessage(int leaderId); + + /** + * Send election message to other instances. + * + * @param currentId Instance ID of which sends this message. + * @param content Election message content. + * @return {@code true} if the message is accepted by the target instances. + */ + boolean sendElectionMessage(int currentId, String content); + + /** + * Send new leader notification message to other instances. + * + * @param currentId Instance ID of which sends this message. + * @param leaderId Leader message content. + * @return {@code true} if the message is accepted by the target instances. + */ + boolean sendLeaderMessage(int currentId, int leaderId); + + /** + * Send heartbeat invoke message. This will invoke heartbeat task in the target instance. + * + * @param currentId Instance ID of which sends this message. + */ + void sendHeartbeatInvokeMessage(int currentId); +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java new file mode 100644 index 000000000000..d2d06cc21e4f --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java @@ -0,0 +1,47 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection; + +/** Message Type enum. */ +public enum MessageType { + + /** Start the election. The content of the message stores ID(s) of the candidate instance(s). */ + ELECTION, + + /** Nodify the new leader. The content of the message should be the leader ID. */ + LEADER, + + /** Check health of current leader instance. */ + HEARTBEAT, + + /** Inform target instance to start election. */ + ELECTION_INVOKE, + + /** Inform target instance to notify all the other instance that it is the new leader. */ + LEADER_INVOKE, + + /** Inform target instance to start heartbeat. */ + HEARTBEAT_INVOKE +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java new file mode 100644 index 000000000000..700d8ac6e13c --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java @@ -0,0 +1,74 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.bully; + +import com.iluwatar.leaderelection.Instance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; +import java.util.HashMap; +import java.util.Map; + +/** + * Example of how to use bully leader election. Initially 5 instances is created in the clould + * system, and the instance with ID 1 is set as leader. After the system is started stop the leader + * instance, and the new leader will be elected. + */ +public class BullyApp { + + /** Program entry point. */ + public static void main(String[] args) { + + Map instanceMap = new HashMap<>(); + var messageManager = new BullyMessageManager(instanceMap); + + var instance1 = new BullyInstance(messageManager, 1, 1); + var instance2 = new BullyInstance(messageManager, 2, 1); + var instance3 = new BullyInstance(messageManager, 3, 1); + var instance4 = new BullyInstance(messageManager, 4, 1); + var instance5 = new BullyInstance(messageManager, 5, 1); + + instanceMap.put(1, instance1); + instanceMap.put(2, instance2); + instanceMap.put(3, instance3); + instanceMap.put(4, instance4); + instanceMap.put(5, instance5); + + instance4.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); + + final var thread1 = new Thread(instance1); + final var thread2 = new Thread(instance2); + final var thread3 = new Thread(instance3); + final var thread4 = new Thread(instance4); + final var thread5 = new Thread(instance5); + + thread1.start(); + thread2.start(); + thread3.start(); + thread4.start(); + thread5.start(); + + instance1.setAlive(false); + } +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java new file mode 100644 index 000000000000..3ee9629d469d --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java @@ -0,0 +1,121 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.bully; + +import com.iluwatar.leaderelection.AbstractInstance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageManager; +import lombok.extern.slf4j.Slf4j; + +/** + * Impelemetation with bully algorithm. Each instance should have a sequential id and is able to + * communicate with other instances in the system. Initially the instance with smallest (or largest) + * ID is selected to be the leader. All the other instances send heartbeat message to leader + * periodically to check its health. If one certain instance finds the server done, it will send an + * election message to all the instances of which the ID is larger. If the target instance is alive, + * it will return an alive message (in this sample return true) and then send election message with + * its ID. If not, the original instance will send leader message to all the other instances. + */ +@Slf4j +public class BullyInstance extends AbstractInstance { + private static final String INSTANCE = "Instance "; + + /** Constructor of BullyInstance. */ + public BullyInstance(MessageManager messageManager, int localId, int leaderId) { + super(messageManager, localId, leaderId); + } + + /** + * Process the heartbeat invoke message. After receiving the message, the instance will send a + * heartbeat to leader to check its health. If alive, it will inform the next instance to do the + * heartbeat. If not, it will start the election process. + */ + @Override + protected void handleHeartbeatInvokeMessage() { + try { + boolean isLeaderAlive = messageManager.sendHeartbeatMessage(leaderId); + if (isLeaderAlive) { + LOGGER.info(INSTANCE + localId + "- Leader is alive."); + Thread.sleep(HEARTBEAT_INTERVAL); + messageManager.sendHeartbeatInvokeMessage(localId); + } else { + LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election."); + boolean electionResult = + messageManager.sendElectionMessage(localId, String.valueOf(localId)); + if (electionResult) { + LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification."); + messageManager.sendLeaderMessage(localId, localId); + } + } + } catch (InterruptedException e) { + LOGGER.info(INSTANCE + localId + "- Interrupted."); + } + } + + /** + * Process election invoke message. Send election message to all the instances with smaller ID. If + * any one of them is alive, do nothing. If no instance alive, send leader message to all the + * alive instance and restart heartbeat. + */ + @Override + protected void handleElectionInvokeMessage() { + if (!isLeader()) { + LOGGER.info(INSTANCE + localId + "- Start election."); + boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId)); + if (electionResult) { + LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification."); + leaderId = localId; + messageManager.sendLeaderMessage(localId, localId); + messageManager.sendHeartbeatInvokeMessage(localId); + } + } + } + + /** Process leader message. Update local leader information. */ + @Override + protected void handleLeaderMessage(Message message) { + leaderId = Integer.parseInt(message.getContent()); + LOGGER.info(INSTANCE + localId + " - Leader update done."); + } + + private boolean isLeader() { + return localId == leaderId; + } + + @Override + protected void handleLeaderInvokeMessage() { + // Not used in Bully Instance + } + + @Override + protected void handleHeartbeatMessage(Message message) { + // Not used in Bully Instance + } + + @Override + protected void handleElectionMessage(Message message) { + // Not used in Bully Instance + } +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java new file mode 100644 index 000000000000..e3bd158ed7db --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java @@ -0,0 +1,112 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.bully; + +import com.iluwatar.leaderelection.AbstractMessageManager; +import com.iluwatar.leaderelection.Instance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; +import java.util.List; +import java.util.Map; + +/** Implementation of BullyMessageManager. */ +public class BullyMessageManager extends AbstractMessageManager { + + /** Constructor of BullyMessageManager. */ + public BullyMessageManager(Map instanceMap) { + super(instanceMap); + } + + /** + * Send heartbeat message to current leader instance to check the health. + * + * @param leaderId leaderID + * @return {@code true} if the leader is alive. + */ + @Override + public boolean sendHeartbeatMessage(int leaderId) { + var leaderInstance = instanceMap.get(leaderId); + return leaderInstance.isAlive(); + } + + /** + * Send election message to all the instances with smaller ID. + * + * @param currentId Instance ID of which sends this message. + * @param content Election message content. + * @return {@code true} if no alive instance has smaller ID, so that the election is accepted. + */ + @Override + public boolean sendElectionMessage(int currentId, String content) { + var candidateList = findElectionCandidateInstanceList(currentId); + if (candidateList.isEmpty()) { + return true; + } else { + var electionMessage = new Message(MessageType.ELECTION_INVOKE, ""); + candidateList.forEach((i) -> instanceMap.get(i).onMessage(electionMessage)); + return false; + } + } + + /** + * Send leader message to all the instances to notify the new leader. + * + * @param currentId Instance ID of which sends this message. + * @param leaderId Leader message content. + * @return {@code true} if the message is accepted. + */ + @Override + public boolean sendLeaderMessage(int currentId, int leaderId) { + var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); + instanceMap.keySet().stream() + .filter((i) -> i != currentId) + .forEach((i) -> instanceMap.get(i).onMessage(leaderMessage)); + return false; + } + + /** + * Send heartbeat invoke message to the next instance. + * + * @param currentId Instance ID of which sends this message. + */ + @Override + public void sendHeartbeatInvokeMessage(int currentId) { + var nextInstance = this.findNextInstance(currentId); + var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); + nextInstance.onMessage(heartbeatInvokeMessage); + } + + /** + * Find all the alive instances with smaller ID than current instance. + * + * @param currentId ID of current instance. + * @return ID list of all the candidate instance. + */ + private List findElectionCandidateInstanceList(int currentId) { + return instanceMap.keySet().stream() + .filter((i) -> i < currentId && instanceMap.get(i).isAlive()) + .toList(); + } +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java new file mode 100644 index 000000000000..f72e37b01154 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java @@ -0,0 +1,74 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.ring; + +import com.iluwatar.leaderelection.Instance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; +import java.util.HashMap; +import java.util.Map; + +/** + * Example of how to use ring leader election. Initially 5 instances is created in the clould + * system, and the instance with ID 1 is set as leader. After the system is started stop the leader + * instance, and the new leader will be elected. + */ +public class RingApp { + + /** Program entry point. */ + public static void main(String[] args) { + + Map instanceMap = new HashMap<>(); + var messageManager = new RingMessageManager(instanceMap); + + var instance1 = new RingInstance(messageManager, 1, 1); + var instance2 = new RingInstance(messageManager, 2, 1); + var instance3 = new RingInstance(messageManager, 3, 1); + var instance4 = new RingInstance(messageManager, 4, 1); + var instance5 = new RingInstance(messageManager, 5, 1); + + instanceMap.put(1, instance1); + instanceMap.put(2, instance2); + instanceMap.put(3, instance3); + instanceMap.put(4, instance4); + instanceMap.put(5, instance5); + + instance2.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); + + final var thread1 = new Thread(instance1); + final var thread2 = new Thread(instance2); + final var thread3 = new Thread(instance3); + final var thread4 = new Thread(instance4); + final var thread5 = new Thread(instance5); + + thread1.start(); + thread2.start(); + thread3.start(); + thread4.start(); + thread5.start(); + + instance1.setAlive(false); + } +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java new file mode 100644 index 000000000000..d4a8f0d38721 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java @@ -0,0 +1,129 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.ring; + +import com.iluwatar.leaderelection.AbstractInstance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageManager; +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; + +/** + * Implementation with token ring algorithm. The instances in the system are organized as a ring. + * Each instance should have a sequential id and the instance with smallest (or largest) id should + * be the initial leader. All the other instances send heartbeat message to leader periodically to + * check its health. If one certain instance finds the server done, it will send an election message + * to the next alive instance in the ring, which contains its own ID. Then the next instance add its + * ID into the message and pass it to the next. After all the alive instances' ID are add to the + * message, the message is send back to the first instance, and it will choose the instance with the + * smallest ID to be the new leader, and then send a leader message to other instances to inform the + * result. + */ +@Slf4j +public class RingInstance extends AbstractInstance { + private static final String INSTANCE = "Instance "; + + /** Constructor of RingInstance. */ + public RingInstance(MessageManager messageManager, int localId, int leaderId) { + super(messageManager, localId, leaderId); + } + + /** + * Process the heartbeat invoke message. After receiving the message, the instance will send a + * heartbeat to leader to check its health. If alive, it will inform the next instance to do the + * heartbeat. If not, it will start the election process. + */ + @Override + protected void handleHeartbeatInvokeMessage() { + try { + var isLeaderAlive = messageManager.sendHeartbeatMessage(this.leaderId); + if (isLeaderAlive) { + LOGGER.info(INSTANCE + localId + "- Leader is alive. Start next heartbeat in 5 second."); + Thread.sleep(HEARTBEAT_INTERVAL); + messageManager.sendHeartbeatInvokeMessage(this.localId); + } else { + LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election."); + messageManager.sendElectionMessage(this.localId, String.valueOf(this.localId)); + } + } catch (InterruptedException e) { + LOGGER.info(INSTANCE + localId + "- Interrupted."); + } + } + + /** + * Process election message. If the local ID is contained in the ID list, the instance will select + * the alive instance with the smallest ID to be the new leader, and send the leader inform + * message. If not, it will add its local ID to the list and send the message to the next instance + * in the ring. + */ + @Override + protected void handleElectionMessage(Message message) { + var content = message.getContent(); + LOGGER.info(INSTANCE + localId + " - Election Message: " + content); + var candidateList = + Arrays.stream(content.trim().split(",")).map(Integer::valueOf).sorted().toList(); + if (candidateList.contains(localId)) { + var newLeaderId = candidateList.get(0); + LOGGER.info(INSTANCE + localId + " - New leader should be " + newLeaderId + "."); + messageManager.sendLeaderMessage(localId, newLeaderId); + } else { + content += "," + localId; + messageManager.sendElectionMessage(localId, content); + } + } + + /** + * Process leader Message. The instance will set the leader ID to be the new one and send the + * message to the next instance until all the alive instance in the ring is informed. + */ + @Override + protected void handleLeaderMessage(Message message) { + var newLeaderId = Integer.valueOf(message.getContent()); + if (this.leaderId != newLeaderId) { + LOGGER.info(INSTANCE + localId + " - Update leaderID"); + this.leaderId = newLeaderId; + messageManager.sendLeaderMessage(localId, newLeaderId); + } else { + LOGGER.info(INSTANCE + localId + " - Leader update done. Start heartbeat."); + messageManager.sendHeartbeatInvokeMessage(localId); + } + } + + /** Not used in Ring instance. */ + @Override + protected void handleLeaderInvokeMessage() { + // Not used in Ring instance. + } + + @Override + protected void handleHeartbeatMessage(Message message) { + // Not used in Ring instance. + } + + @Override + protected void handleElectionInvokeMessage() { + // Not used in Ring instance. + } +} diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java new file mode 100644 index 000000000000..7a055cf10331 --- /dev/null +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java @@ -0,0 +1,95 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.ring; + +import com.iluwatar.leaderelection.AbstractMessageManager; +import com.iluwatar.leaderelection.Instance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; +import java.util.Map; + +/** Implementation of RingMessageManager. */ +public class RingMessageManager extends AbstractMessageManager { + + /** Constructor of RingMessageManager. */ + public RingMessageManager(Map instanceMap) { + super(instanceMap); + } + + /** + * Send heartbeat message to current leader instance to check the health. + * + * @param leaderId leaderID + * @return {@code true} if the leader is alive. + */ + @Override + public boolean sendHeartbeatMessage(int leaderId) { + var leaderInstance = instanceMap.get(leaderId); + return leaderInstance.isAlive(); + } + + /** + * Send election message to the next instance. + * + * @param currentId currentID + * @param content list contains all the IDs of instances which have received this election + * message. + * @return {@code true} if the election message is accepted by the target instance. + */ + @Override + public boolean sendElectionMessage(int currentId, String content) { + var nextInstance = this.findNextInstance(currentId); + var electionMessage = new Message(MessageType.ELECTION, content); + nextInstance.onMessage(electionMessage); + return true; + } + + /** + * Send leader message to the next instance. + * + * @param currentId Instance ID of which sends this message. + * @param leaderId Leader message content. + * @return {@code true} if the leader message is accepted by the target instance. + */ + @Override + public boolean sendLeaderMessage(int currentId, int leaderId) { + var nextInstance = this.findNextInstance(currentId); + var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); + nextInstance.onMessage(leaderMessage); + return true; + } + + /** + * Send heartbeat invoke message to the next instance. + * + * @param currentId Instance ID of which sends this message. + */ + @Override + public void sendHeartbeatInvokeMessage(int currentId) { + var nextInstance = this.findNextInstance(currentId); + var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); + nextInstance.onMessage(heartbeatInvokeMessage); + } +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java new file mode 100644 index 000000000000..f8a4d1869fbf --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +/** Message test case. */ +class MessageTest { + + @Test + void testGetType() { + var message = new Message(MessageType.HEARTBEAT, ""); + assertEquals(MessageType.HEARTBEAT, message.getType()); + } + + @Test + void testGetContent() { + var content = "test"; + var message = new Message(MessageType.HEARTBEAT, content); + assertEquals(content, message.getContent()); + } +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java new file mode 100644 index 000000000000..32ba40c38f17 --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.bully; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** BullyApp unit test. */ +class BullyAppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> BullyApp.main(new String[] {})); + } +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java new file mode 100644 index 000000000000..f1453202a39f --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java @@ -0,0 +1,136 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.bully; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import com.iluwatar.leaderelection.AbstractInstance; +import com.iluwatar.leaderelection.Instance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; +import java.util.Map; +import java.util.Queue; +import org.junit.jupiter.api.Test; + +/** BullyMessageManager unit test. */ +class BullyMessageManagerTest { + + @Test + void testSendHeartbeatMessage() { + var instance1 = new BullyInstance(null, 1, 1); + Map instanceMap = Map.of(1, instance1); + var messageManager = new BullyMessageManager(instanceMap); + assertTrue(messageManager.sendHeartbeatMessage(1)); + } + + @Test + void testSendElectionMessageNotAccepted() { + try { + var instance1 = new BullyInstance(null, 1, 1); + var instance2 = new BullyInstance(null, 1, 2); + var instance3 = new BullyInstance(null, 1, 3); + var instance4 = new BullyInstance(null, 1, 4); + Map instanceMap = + Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); + instance1.setAlive(false); + var messageManager = new BullyMessageManager(instanceMap); + var result = messageManager.sendElectionMessage(3, "3"); + var instanceClass = AbstractInstance.class; + var messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + var message2 = ((Queue) messageQueueField.get(instance2)).poll(); + var instance4QueueSize = ((Queue) messageQueueField.get(instance4)).size(); + var expectedMessage = new Message(MessageType.ELECTION_INVOKE, ""); + assertEquals(message2, expectedMessage); + assertEquals(instance4QueueSize, 0); + assertFalse(result); + } catch (IllegalAccessException | NoSuchFieldException e) { + fail("Error to access private field."); + } + } + + @Test + void testElectionMessageAccepted() { + var instance1 = new BullyInstance(null, 1, 1); + var instance2 = new BullyInstance(null, 1, 2); + var instance3 = new BullyInstance(null, 1, 3); + var instance4 = new BullyInstance(null, 1, 4); + Map instanceMap = + Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); + instance1.setAlive(false); + var messageManager = new BullyMessageManager(instanceMap); + var result = messageManager.sendElectionMessage(2, "2"); + assertTrue(result); + } + + @Test + void testSendLeaderMessage() { + try { + var instance1 = new BullyInstance(null, 1, 1); + var instance2 = new BullyInstance(null, 1, 2); + var instance3 = new BullyInstance(null, 1, 3); + var instance4 = new BullyInstance(null, 1, 4); + Map instanceMap = + Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); + instance1.setAlive(false); + var messageManager = new BullyMessageManager(instanceMap); + messageManager.sendLeaderMessage(2, 2); + var instanceClass = AbstractInstance.class; + var messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + var message3 = ((Queue) messageQueueField.get(instance3)).poll(); + var message4 = ((Queue) messageQueueField.get(instance4)).poll(); + var expectedMessage = new Message(MessageType.LEADER, "2"); + assertEquals(message3, expectedMessage); + assertEquals(message4, expectedMessage); + } catch (IllegalAccessException | NoSuchFieldException e) { + fail("Error to access private field."); + } + } + + @Test + void testSendHeartbeatInvokeMessage() { + try { + var instance1 = new BullyInstance(null, 1, 1); + var instance2 = new BullyInstance(null, 1, 2); + var instance3 = new BullyInstance(null, 1, 3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); + var messageManager = new BullyMessageManager(instanceMap); + messageManager.sendHeartbeatInvokeMessage(2); + var message = new Message(MessageType.HEARTBEAT_INVOKE, ""); + var instanceClass = AbstractInstance.class; + var messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + var messageSent = ((Queue) messageQueueField.get(instance3)).poll(); + assertEquals(messageSent.getType(), message.getType()); + assertEquals(messageSent.getContent(), message.getContent()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Error to access private field."); + } + } +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java new file mode 100644 index 000000000000..31dbad14b8ab --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.bully; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; + +import com.iluwatar.leaderelection.AbstractInstance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; +import java.util.Queue; +import org.junit.jupiter.api.Test; + +/** BullyInstance unit test. */ +class BullyinstanceTest { + + @Test + void testOnMessage() { + try { + final var bullyInstance = new BullyInstance(null, 1, 1); + var bullyMessage = new Message(MessageType.HEARTBEAT, ""); + bullyInstance.onMessage(bullyMessage); + var instanceClass = AbstractInstance.class; + var messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + assertEquals(bullyMessage, ((Queue) messageQueueField.get(bullyInstance)).poll()); + } catch (IllegalAccessException | NoSuchFieldException e) { + fail("fail to access messasge queue."); + } + } + + @Test + void testIsAlive() { + try { + final var bullyInstance = new BullyInstance(null, 1, 1); + var instanceClass = AbstractInstance.class; + var aliveField = instanceClass.getDeclaredField("alive"); + aliveField.setAccessible(true); + aliveField.set(bullyInstance, false); + assertFalse(bullyInstance.isAlive()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Fail to access field alive."); + } + } + + @Test + void testSetAlive() { + final var bullyInstance = new BullyInstance(null, 1, 1); + bullyInstance.setAlive(false); + assertFalse(bullyInstance.isAlive()); + } +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java new file mode 100644 index 000000000000..839e481f4c81 --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.ring; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** RingApp unit test. */ +class RingAppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> RingApp.main(new String[] {})); + } +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java new file mode 100644 index 000000000000..140432e54e1a --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.ring; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; + +import com.iluwatar.leaderelection.AbstractInstance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; +import java.util.Queue; +import org.junit.jupiter.api.Test; + +/** RingInstance unit test. */ +class RingInstanceTest { + + @Test + void testOnMessage() { + try { + final var ringInstance = new RingInstance(null, 1, 1); + var ringMessage = new Message(MessageType.HEARTBEAT, ""); + ringInstance.onMessage(ringMessage); + var ringInstanceClass = AbstractInstance.class; + var messageQueueField = ringInstanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + assertEquals(ringMessage, ((Queue) messageQueueField.get(ringInstance)).poll()); + } catch (IllegalAccessException | NoSuchFieldException e) { + fail("fail to access messasge queue."); + } + } + + @Test + void testIsAlive() { + try { + final var ringInstance = new RingInstance(null, 1, 1); + var ringInstanceClass = AbstractInstance.class; + var aliveField = ringInstanceClass.getDeclaredField("alive"); + aliveField.setAccessible(true); + aliveField.set(ringInstance, false); + assertFalse(ringInstance.isAlive()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Fail to access field alive."); + } + } + + @Test + void testSetAlive() { + final var ringInstance = new RingInstance(null, 1, 1); + ringInstance.setAlive(false); + assertFalse(ringInstance.isAlive()); + } +} diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java new file mode 100644 index 000000000000..ed13e4fb45f4 --- /dev/null +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java @@ -0,0 +1,113 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderelection.ring; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import com.iluwatar.leaderelection.AbstractInstance; +import com.iluwatar.leaderelection.Instance; +import com.iluwatar.leaderelection.Message; +import com.iluwatar.leaderelection.MessageType; +import java.util.Map; +import java.util.Queue; +import org.junit.jupiter.api.Test; + +/** RingMessageManager unit test. */ +class RingMessageManagerTest { + + @Test + void testSendHeartbeatMessage() { + var instance1 = new RingInstance(null, 1, 1); + Map instanceMap = Map.of(1, instance1); + var messageManager = new RingMessageManager(instanceMap); + assertTrue(messageManager.sendHeartbeatMessage(1)); + } + + @Test + void testSendElectionMessage() { + try { + var instance1 = new RingInstance(null, 1, 1); + var instance2 = new RingInstance(null, 1, 2); + var instance3 = new RingInstance(null, 1, 3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); + var messageManager = new RingMessageManager(instanceMap); + var messageContent = "2"; + messageManager.sendElectionMessage(2, messageContent); + var ringMessage = new Message(MessageType.ELECTION, messageContent); + var instanceClass = AbstractInstance.class; + var messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + var ringMessageSent = ((Queue) messageQueueField.get(instance3)).poll(); + assertEquals(ringMessageSent.getType(), ringMessage.getType()); + assertEquals(ringMessageSent.getContent(), ringMessage.getContent()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Error to access private field."); + } + } + + @Test + void testSendLeaderMessage() { + try { + var instance1 = new RingInstance(null, 1, 1); + var instance2 = new RingInstance(null, 1, 2); + var instance3 = new RingInstance(null, 1, 3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); + var messageManager = new RingMessageManager(instanceMap); + var messageContent = "3"; + messageManager.sendLeaderMessage(2, 3); + var ringMessage = new Message(MessageType.LEADER, messageContent); + var instanceClass = AbstractInstance.class; + var messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + var ringMessageSent = ((Queue) messageQueueField.get(instance3)).poll(); + assertEquals(ringMessageSent, ringMessage); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Error to access private field."); + } + } + + @Test + void testSendHeartbeatInvokeMessage() { + try { + var instance1 = new RingInstance(null, 1, 1); + var instance2 = new RingInstance(null, 1, 2); + var instance3 = new RingInstance(null, 1, 3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); + var messageManager = new RingMessageManager(instanceMap); + messageManager.sendHeartbeatInvokeMessage(2); + var ringMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); + var instanceClass = AbstractInstance.class; + var messageQueueField = instanceClass.getDeclaredField("messageQueue"); + messageQueueField.setAccessible(true); + var ringMessageSent = ((Queue) messageQueueField.get(instance3)).poll(); + assertEquals(ringMessageSent.getType(), ringMessage.getType()); + assertEquals(ringMessageSent.getContent(), ringMessage.getContent()); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Error to access private field."); + } + } +} diff --git a/leader-followers/README.md b/leader-followers/README.md new file mode 100644 index 000000000000..c8c3d0d2a8ae --- /dev/null +++ b/leader-followers/README.md @@ -0,0 +1,175 @@ +--- +title: "Leader-Followers Pattern in Java: Enhancing Efficiency with Dynamic Worker Allocation" +shortTitle: Leader-Followers +description: "Discover the Leader-Followers design pattern for efficient thread management and synchronization. Learn how to optimize resource usage and improve system performance with detailed examples and applications." +category: Concurrency +language: en +tag: + - Decoupling + - Performance + - Synchronization + - Thread management +--- + +## Intent of Leader/Followers Design Pattern + +To efficiently manage a set of worker threads, the Leader-Followers pattern enables multiple threads to take turns sharing a set of event sources, optimizing resource utilization and improving performance compared to a one-thread-per-source approach. + +## Detailed Explanation of Leader/Followers Pattern with Real-World Examples + +Real-world Example + +> Imagine managing a busy restaurant with multiple servers and a single host. The host acts as the "leader" and is responsible for greeting guests, managing the waitlist, and seating guests. Once the guests are seated, the host returns to the entrance to manage new arrivals. The servers, or "followers," wait for the host to assign them tables. This assignment is done on a rotational basis where the next available server takes the next group of guests. This system ensures that the host efficiently handles the incoming flow of guests while servers focus on providing service, similar to how the Leader and Followers pattern manages threads and tasks in a software system. This approach optimizes resource utilization (in this case, staff) and ensures smooth operations during peak times, much like it optimizes thread usage in computing environments. + +In plain words + +> The Leader-Followers design pattern utilizes a single leader thread to distribute work among multiple follower threads, effectively managing task delegation, thread synchronization, and improving resource efficiency in concurrent programming. + +[martinfowler.com](https://martinfowler.com/articles/patterns-of-distributed-systems/leader-follower.html) says + +> Select one server in the cluster as a leader. The leader is responsible for taking decisions on behalf of the entire cluster and propagating the decisions to all the other servers. + +Sequence diagram + +![Leader-Followers Sequence Diagram](./etc/leader-followers-sequence-diagram.png) + +## Programmatic Example of Leader-Followers Pattern in Java + +The Leader-Followers pattern is a concurrency design pattern where one thread (the leader) waits for work to arrive, de-multiplexes, dispatches, and processes the work, thereby enhancing CPU cache affinity and reducing event dispatching latency. Once the leader finishes processing the work, it promotes one of the follower threads to be the new leader. This pattern is useful for enhancing CPU cache affinity, minimizing locking overhead, and reducing event dispatching latency. + +In the provided code, we have a `WorkCenter` class that manages a group of `Worker` threads. One of these workers is designated as the leader and is responsible for receiving and processing tasks. Once a task is processed, the leader promotes a new leader from the remaining workers. + +```java +// WorkCenter class +public class WorkCenter { + + @Getter + private Worker leader; + private final List workers = new CopyOnWriteArrayList<>(); + + // Method to create workers and set the initial leader + public void createWorkers(int numberOfWorkers, TaskSet taskSet, TaskHandler taskHandler) { + for (var id = 1; id <= numberOfWorkers; id++) { + var worker = new Worker(id, this, taskSet, taskHandler); + workers.add(worker); + } + promoteLeader(); + } + + // Method to promote a new leader + public void promoteLeader() { + Worker leader = null; + if (!workers.isEmpty()) { + leader = workers.get(0); + } + this.leader = leader; + } +} +``` + +In the `Worker` class, each worker is a thread that waits for tasks to process. If the worker is the leader, it processes the task and then promotes a new leader. + +```java +// Worker class +public class Worker implements Runnable { + + private final long id; + private final WorkCenter workCenter; + private final TaskSet taskSet; + private final TaskHandler taskHandler; + + @Override + public void run() { + while (!Thread.interrupted()) { + try { + if (workCenter.getLeader() != null && !workCenter.getLeader().equals(this)) { + synchronized (workCenter) { + if (workCenter.getLeader() != null && !workCenter.getLeader().equals(this)) { + workCenter.wait(); + continue; + } + } + } + final Task task = taskSet.getTask(); + synchronized (workCenter) { + workCenter.removeWorker(this); + workCenter.promoteLeader(); + workCenter.notifyAll(); + } + taskHandler.handleTask(task); + workCenter.addWorker(this); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } +} +``` + +In the `App` class, we create a `WorkCenter`, add tasks to a `TaskSet`, and then start the workers. The leader worker will start processing the tasks, and once it finishes a task, it will promote a new leader. + +```java +// App class +public class App { + + public static void main(String[] args) throws InterruptedException { + var taskSet = new TaskSet(); + var taskHandler = new TaskHandler(); + var workCenter = new WorkCenter(); + workCenter.createWorkers(4, taskSet, taskHandler); + addTasks(taskSet); + startWorkers(workCenter); + } + + private static void addTasks(TaskSet taskSet) throws InterruptedException { + var rand = new SecureRandom(); + for (var i = 0; i < 5; i++) { + var time = Math.abs(rand.nextInt(1000)); + taskSet.addTask(new Task(time)); + } + } + + private static void startWorkers(WorkCenter workCenter) throws InterruptedException { + var workers = workCenter.getWorkers(); + var exec = Executors.newFixedThreadPool(workers.size()); + workers.forEach(exec::submit); + exec.awaitTermination(2, TimeUnit.SECONDS); + exec.shutdownNow(); + } +} +``` + +This is a basic example of the Leader/Followers pattern. The leader worker processes tasks and promotes a new leader once it finishes a task. The new leader then starts processing the next task, and the cycle continues. + +## When to Use the Leader/Followers Pattern in Java + +* The Leader-Followers pattern is useful in scenarios requiring efficient handling of multiple services on a single thread, avoiding resource thrashing, and improving scalability in concurrent programming environments. +* Applicable in server environments where multiple client requests must be handled concurrently with minimal resource consumption. + +## Real-World Applications of Leader-Followers Pattern in Java + +* Network servers handling multiple incoming connections. +* Event-driven applications that manage a large number of input/output sources. + +## Benefits and Trade-offs of Leader/Followers Pattern + +Benefits: + +* Reduces the number of threads and context switching, leading to better performance and lower resource utilization. +* Improves system scalability and responsiveness. + +Trade-offs: + +* Increased complexity in managing the synchronization between leader and followers. +* Potential for underutilization of resources if not correctly implemented. + +## Related Java Design Patterns + +* [Half-Sync/Half-Async](https://java-design-patterns.com/patterns/half-sync-half-async/): Leader and Followers can be seen as a variation where the synchronization aspect is divided between the leader (synchronous handling) and followers (waiting asynchronously). +* [Thread Pool](https://java-design-patterns.com/patterns/thread-pool/): Both patterns manage a pool of worker threads, but Thread Pool assigns tasks to any available thread rather than using a leader to distribute work. + +## References and Credits + +* [Java Concurrency in Practice](https://amzn.to/4aRMruW) +* [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) diff --git a/leader-followers/etc/leader-followers-sequence-diagram.png b/leader-followers/etc/leader-followers-sequence-diagram.png new file mode 100644 index 000000000000..1c32d5c1f24f Binary files /dev/null and b/leader-followers/etc/leader-followers-sequence-diagram.png differ diff --git a/leader-followers/etc/leader-followers.png b/leader-followers/etc/leader-followers.png new file mode 100644 index 000000000000..de8efd9f0b6b Binary files /dev/null and b/leader-followers/etc/leader-followers.png differ diff --git a/leader-followers/etc/leader-followers.urm.puml b/leader-followers/etc/leader-followers.urm.puml new file mode 100644 index 000000000000..fc674a518aa8 --- /dev/null +++ b/leader-followers/etc/leader-followers.urm.puml @@ -0,0 +1,54 @@ +@startuml +package com.iluwatar.leaderfollowers { + class App { + + App() + - addTasks(taskSet : TaskSet) {static} + - execute(workCenter : WorkCenter, taskSet : TaskSet) {static} + + main(args : String[]) {static} + } + class Task { + - finished : boolean + - time : int + + Task(time : int) + + getTime() : int + + isFinished() : boolean + + setFinished() + } + class TaskHandler { + + TaskHandler() + + handleTask(task : Task) + } + class TaskSet { + - queue : BlockingQueue + + TaskSet() + + addTask(task : Task) + + getSize() : int + + getTask() : Task + } + class WorkCenter { + - leader : Worker + - workers : List + + WorkCenter() + + addWorker(worker : Worker) + + createWorkers(numberOfWorkers : int, taskSet : TaskSet, taskHandler : TaskHandler) + + getLeader() : Worker + + getWorkers() : List + + promoteLeader() + + removeWorker(worker : Worker) + } + class Worker { + - id : long + - taskHandler : TaskHandler + - taskSet : TaskSet + - workCenter : WorkCenter + + Worker(id : long, workCenter : WorkCenter, taskSet : TaskSet, taskHandler : TaskHandler) + + equals(o : Object) : boolean + + hashCode() : int + + run() + } +} +Worker --> "-taskSet" TaskSet +Worker --> "-taskHandler" TaskHandler +TaskSet --> "-queue" Task +Worker --> "-workCenter" WorkCenter +@enduml \ No newline at end of file diff --git a/leader-followers/pom.xml b/leader-followers/pom.xml new file mode 100644 index 000000000000..12152cd3fc26 --- /dev/null +++ b/leader-followers/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + leader-followers + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.leaderfollowers.App + + + + + + + + + diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java new file mode 100644 index 000000000000..88ff5c55fa56 --- /dev/null +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java @@ -0,0 +1,67 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderfollowers; + +import java.security.SecureRandom; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class App { + + public static void main(String[] args) throws InterruptedException { + var taskSet = new TaskSet(); + var taskHandler = new TaskHandler(); + var workCenter = new WorkCenter(); + workCenter.createWorkers(4, taskSet, taskHandler); + execute(workCenter, taskSet); + } + + private static void execute(WorkCenter workCenter, TaskSet taskSet) throws InterruptedException { + var workers = workCenter.getWorkers(); + var exec = Executors.newFixedThreadPool(workers.size()); + + try { + workers.forEach(exec::submit); + Thread.sleep(1000); + addTasks(taskSet); + boolean terminated = exec.awaitTermination(2, TimeUnit.SECONDS); + if (!terminated) { + LOGGER.warn("Executor did not terminate in the given time."); + } + } finally { + exec.shutdownNow(); + } + } + + private static void addTasks(TaskSet taskSet) throws InterruptedException { + var rand = new SecureRandom(); + for (var i = 0; i < 5; i++) { + var time = Math.abs(rand.nextInt(1000)); + taskSet.addTask(new Task(time)); + } + } +} diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Task.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Task.java new file mode 100644 index 000000000000..29374b931cc5 --- /dev/null +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Task.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderfollowers; + +import lombok.Getter; +import lombok.Setter; + +/** A unit of work to be processed by the Workers. */ +public class Task { + + @Getter private final int time; + + @Getter @Setter private boolean finished; + + public Task(int time) { + this.time = time; + } +} diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskHandler.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskHandler.java new file mode 100644 index 000000000000..8689ce4421dd --- /dev/null +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskHandler.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderfollowers; + +import lombok.extern.slf4j.Slf4j; + +/** The TaskHandler is used by the {@link Worker} to process the newly arrived task. */ +@Slf4j +public class TaskHandler { + + /** This interface handles one task at a time. */ + public void handleTask(Task task) throws InterruptedException { + var time = task.getTime(); + Thread.sleep(time); + LOGGER.info("It takes " + time + " milliseconds to finish the task"); + task.setFinished(true); + } +} diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java new file mode 100644 index 000000000000..c54037024490 --- /dev/null +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderfollowers; + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; + +/** A TaskSet is a collection of the tasks, the leader receives task from here. */ +public class TaskSet { + + private final BlockingQueue queue = new ArrayBlockingQueue<>(100); + + public void addTask(Task task) throws InterruptedException { + queue.put(task); + } + + public Task getTask() throws InterruptedException { + return queue.take(); + } + + public int getSize() { + return queue.size(); + } +} diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java new file mode 100644 index 000000000000..c2fd32f3afef --- /dev/null +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java @@ -0,0 +1,70 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderfollowers; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import lombok.Getter; + +/** + * A WorkCenter contains a leader and a list of idle workers. The leader is responsible for + * receiving work when it arrives. This class also provides a mechanism to promote a new leader. A + * worker once he completes his task will add himself back to the center. + */ +public class WorkCenter { + + @Getter private Worker leader; + private final List workers = new CopyOnWriteArrayList<>(); + + /** Create workers and set leader. */ + public void createWorkers(int numberOfWorkers, TaskSet taskSet, TaskHandler taskHandler) { + for (var id = 1; id <= numberOfWorkers; id++) { + var worker = new Worker(id, this, taskSet, taskHandler); + workers.add(worker); + } + promoteLeader(); + } + + public void addWorker(Worker worker) { + workers.add(worker); + } + + public void removeWorker(Worker worker) { + workers.remove(worker); + } + + /** Promote a leader. */ + public void promoteLeader() { + Worker leader = null; + if (!workers.isEmpty()) { + leader = workers.get(0); + } + this.leader = leader; + } + + public List getWorkers() { + return workers; + } +} diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java new file mode 100644 index 000000000000..b079bc616da7 --- /dev/null +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java @@ -0,0 +1,81 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderfollowers; + +import lombok.EqualsAndHashCode; +import lombok.extern.slf4j.Slf4j; + +/** Worker class that takes work from work center. */ +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@Slf4j +public class Worker implements Runnable { + + @EqualsAndHashCode.Include private final long id; + private final WorkCenter workCenter; + private final TaskSet taskSet; + private final TaskHandler taskHandler; + + /** Constructor to create a worker which will take work from the work center. */ + public Worker(long id, WorkCenter workCenter, TaskSet taskSet, TaskHandler taskHandler) { + super(); + this.id = id; + this.workCenter = workCenter; + this.taskSet = taskSet; + this.taskHandler = taskHandler; + } + + /** + * The leader thread listens for task. When task arrives, it promotes one of the followers to be + * the new leader. Then it handles the task and add himself back to work center. + */ + @Override + public void run() { + while (!Thread.interrupted()) { + try { + if (workCenter.getLeader() != null && !workCenter.getLeader().equals(this)) { + synchronized (workCenter) { + if (workCenter.getLeader() != null && !workCenter.getLeader().equals(this)) { + workCenter.wait(); + continue; + } + } + } + final Task task = taskSet.getTask(); + synchronized (workCenter) { + workCenter.removeWorker(this); + workCenter.promoteLeader(); + workCenter.notifyAll(); + } + taskHandler.handleTask(task); + LOGGER.info("The Worker with the ID " + id + " completed the task"); + workCenter.addWorker(this); + } catch (InterruptedException e) { + LOGGER.warn("Worker interrupted"); + Thread.currentThread().interrupt(); + return; + } + } + } +} diff --git a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/AppTest.java b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/AppTest.java new file mode 100644 index 000000000000..dd8779141c01 --- /dev/null +++ b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderfollowers; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application test */ +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskHandlerTest.java b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskHandlerTest.java new file mode 100644 index 000000000000..a52aa9f79bbe --- /dev/null +++ b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskHandlerTest.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderfollowers; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** Tests for TaskHandler */ +class TaskHandlerTest { + + @Test + void testHandleTask() throws InterruptedException { + var taskHandler = new TaskHandler(); + var handle = new Task(100); + taskHandler.handleTask(handle); + assertTrue(handle.isFinished()); + } +} diff --git a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskSetTest.java b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskSetTest.java new file mode 100644 index 000000000000..8b55ba41855d --- /dev/null +++ b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskSetTest.java @@ -0,0 +1,49 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderfollowers; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +/** Tests for TaskSet */ +class TaskSetTest { + + @Test + void testAddTask() throws InterruptedException { + var taskSet = new TaskSet(); + taskSet.addTask(new Task(10)); + assertEquals(1, taskSet.getSize()); + } + + @Test + void testGetTask() throws InterruptedException { + var taskSet = new TaskSet(); + taskSet.addTask(new Task(100)); + Task task = taskSet.getTask(); + assertEquals(100, task.getTime()); + assertEquals(0, taskSet.getSize()); + } +} diff --git a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/WorkCenterTest.java b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/WorkCenterTest.java new file mode 100644 index 000000000000..425edc57632c --- /dev/null +++ b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/WorkCenterTest.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.leaderfollowers; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; + +/** Tests for WorkCenter */ +class WorkCenterTest { + + @Test + void testCreateWorkers() { + var taskSet = new TaskSet(); + var taskHandler = new TaskHandler(); + var workCenter = new WorkCenter(); + workCenter.createWorkers(5, taskSet, taskHandler); + assertEquals(5, workCenter.getWorkers().size()); + assertEquals(workCenter.getWorkers().get(0), workCenter.getLeader()); + } + + @Test + void testNullLeader() { + var workCenter = new WorkCenter(); + workCenter.promoteLeader(); + assertNull(workCenter.getLeader()); + } + + @Test + void testPromoteLeader() { + var taskSet = new TaskSet(); + var taskHandler = new TaskHandler(); + var workCenter = new WorkCenter(); + workCenter.createWorkers(5, taskSet, taskHandler); + workCenter.removeWorker(workCenter.getLeader()); + workCenter.promoteLeader(); + assertEquals(4, workCenter.getWorkers().size()); + assertEquals(workCenter.getWorkers().get(0), workCenter.getLeader()); + } +} diff --git a/lgpl-3.0.txt b/lgpl-3.0.txt new file mode 100644 index 000000000000..95107e3c5982 --- /dev/null +++ b/lgpl-3.0.txt @@ -0,0 +1,190 @@ +==== + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 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. +==== + + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/localization/ar/README.md b/localization/ar/README.md new file mode 100644 index 000000000000..c2f4c60169b5 --- /dev/null +++ b/localization/ar/README.md @@ -0,0 +1,43 @@ +# أنماط التصميم بلغة برمجة الجافا + +![Java CI with Maven](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI%20with%20Maven/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-148-orange.svg?style=flat-square)](#contributors-) + + + +# مقدمة + +أنماط التصميم هي أفضل التدريبات التي يمكن للمبرمج استخدامها لحل المشكلات الشائعة عند تصميم تطبيق أو نظام. +يمكن لأنماط التصميم تسريع عملية التطوير من خلال توفير نماذج تطوير مجربة ومثبتة ومفيدة. +تساعد إعادة استخدام أنماط التصميم في منع المشكلات الدقيقة التي تسبب مشكلات كبيرة ، كما تعمل على تحسين قابلية قراءة الكود للمهندسين البرمجيات الذين هم على دراية بالأنماط. + +# البدء في التعلم + +يعرض هذا الموقع أنماط تصميم جافا. تم تطوير الحلول من قبل المبرمجين والمهندسين ذوي الخبرة من مجتمع المصادر المفتوحة. يمكن تصفح الأنماط من خلال أوصافها عالية المستوى أو بالنظر إلى كود المصدر الخاص بها. تم كتابة الشرح على أمثلة الكود المصدري جيدًا ويمكن اعتبارها برامج تعليمية حول كيفية تنفيذ نمط معين. نحن نستخدم تقنيات Java مفتوحة المصدر الأكثر شيوعًا والتي أثبتت جدارتها في مشاريع الجافا. +قبل الغوص في المادة ، يجب أن تكون على دراية [بمبادئ تصميم البرامج المختلفة](https://java-design-patterns.com/principles/). + +يجب أن تكون جميع التصميمات بسيطة قدر الإمكان. يجب أن تبدأ بـ KISS و YAGNI وافعل أبسط شيء يمكن أن يعمل بهذه المبادىء. يجب إستخدام الأنماط فقط عند الحاجة إليها من أجل تمديد البرنامج بشكل عملي. + +بمجرد أن تصبح معتادًا على هذه المفاهيم ، يمكنك البدء في التعمق في [أنماط التصميم المتاحة](https://java-design-patterns.com/patterns/) من خلال أي من الأساليب التالية + +ابحث عن نمط محدد بالاسم. لا يمكنك العثور على واحد؟ الرجاء الإبلاغ عن نمط جديد [هنا](https://github.com/iluwatar/java-design-patterns/issues). +استخدام علامات مثل Performance أو Gang of Four أو الوصول إلى البيانات. +استخدام فئات الأنماط و Creational, Behavioral وغيرها. + +نأمل أن تجد الحلول الموجهة للكائنات المعروضة على هذا الموقع مفيدة في مشاريعك البرمجية وأن تستمتع بتعلمها بقدر ما قمنا بتطويرها. + + +# كيف تساهم؟ + +إذا كنت على استعداد للمساهمة في المشروع ، فستجد المعلومات ذات الصلة في [ويكي المطور الخاص بنا](https://github.com/iluwatar/java-design-patterns/wiki). سنساعدك ونجيب على أسئلتك في [غرفة الدردشة Gitter](https://gitter.im/iluwatar/java-design-patterns). + + +# الترخيص + +هذا المشروع مرخص بموجب شروط ترخيص MIT. + diff --git a/localization/ar/abstract-document/README.md b/localization/ar/abstract-document/README.md new file mode 100644 index 000000000000..bf1599124f26 --- /dev/null +++ b/localization/ar/abstract-document/README.md @@ -0,0 +1,188 @@ +--- +title: Abstract Document +shortTitle: Abstract Document +category: Structural +language: ar +tag: + - Extensibility +--- + + +## الهدف + +استخدام الخصائص الديناميكية والحصول على مرونة اللغات غير المتغيرة مع الحفاظ على أمان الأنواع. + +## التوضيح + +يتيح استخدام نمط الوثيقة المجردة إدارة الخصائص غير الثابتة الإضافية. يستخدم هذا النمط مفهوم +السمات لتمكين أمان الأنواع وخصائص مفصولة من فئات مختلفة في مجموعة من الواجهات. + +مثال من العالم الحقيقي + +> خذ على سبيل المثال سيارة مكونة من العديد من الأجزاء. ومع ذلك، لا نعرف إذا كانت السيارة تحتوي على جميع الأجزاء أو جزء منها فقط. سياراتنا ديناميكية ومرنة للغاية. + +بصيغة أخرى + +> يسمح نمط الوثيقة المجردة بإضافة خصائص إلى الكائنات دون أن تكون هذه الكائنات على دراية بذلك. + +حسب ويكيبيديا + +> نمط تصميم هيكلي موجه للكائنات لتنظيم الكائنات في حاويات من نوع مفتاح-قيمة بشكل فضفاض مع نوعية غير محددة، وكشف البيانات باستخدام طرق عرض مهيكلة. الهدف من هذا النمط هو تحقيق درجة عالية من المرونة بين المكونات في لغة قوية النوع حيث يمكن إضافة خصائص جديدة إلى شجرة الكائنات أثناء العمل دون فقدان دعم أمان الأنواع. يستخدم النمط السمات لفصل خصائص مختلفة للفئة إلى واجهات متعددة. + +**مثال برمجي** + +أولاً، دعونا نعرف الفئات الأساسية `Document` و `AbstractDocument`. في الأساس، تجعل الكائن يحتوي على خريطة من الخصائص وأي عدد من الكائنات الفرعية. + + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + ... +} +``` + +بعد ذلك، نعرف `enum` لـ `Property` ومجموعة من الواجهات للنمط، السعر، النموذج، والأجزاء. هذا يتيح لنا إنشاء واجهات تظهر بشكل ثابت لفئة `Car`. + + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} +``` + +Ahora estamos listos para introducir el Coche `Car`. + +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` + +وأخيرًا، هكذا نبني ونستخدم السيارة `Car` في مثال كامل. + + +```java + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); + + // Constructing parts and car + // Here is our car: + // model: 300SL + // price: 10000 + // parts: + // wheel/15C/100 + // door/Lambo/300 +``` + +## Diagrama de clases + +![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain") + +## التطبيق + +استخدم نمط الوثيقة المجردة عندما: + +* يوجد حاجة لإضافة خصائص أثناء العمل. +* ترغب في طريقة مرنة لتنظيم النطاق في هيكل مشابه لشجرة. +* ترغب في نظام أقل ترابطًا. + +## الحقوق + + +* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492) \ No newline at end of file diff --git a/localization/ar/abstract-document/etc/abstract-document.png b/localization/ar/abstract-document/etc/abstract-document.png new file mode 100644 index 000000000000..6bc0b29a4e77 Binary files /dev/null and b/localization/ar/abstract-document/etc/abstract-document.png differ diff --git a/localization/ar/abstract-factory/README.md b/localization/ar/abstract-factory/README.md new file mode 100644 index 000000000000..230c9ae12b44 --- /dev/null +++ b/localization/ar/abstract-factory/README.md @@ -0,0 +1,234 @@ +--- +title: Abstract Factory +shortTitle: Abstract Factory +category: Creational +language: ar +tag: + - Gang of Four +--- +## يُعرف أيضًا باسم + +Kit + +## الهدف + +توفير واجهة لإنشاء عائلات من الكائنات المرتبطة المعتمدة دون تحديد فئتها المحددة. + +## التوضيح + +مثال من العالم الحقيقي + +> لإنشاء مملكة نحتاج إلى كائنات بموضوع مشترك. المملكة الإلفية تحتاج إلى ملك إلفي، وقلعة إلفية، وجيش إلفي، بينما المملكة الأوركية تحتاج إلى ملك أوركي، وقلعة أوركية، وجيش أوركي. هناك اعتماد بين كائنات المملكة. + +بصيغة أخرى + +> مصنع للمصانع؛ مصنع يجمع بين مصانع فردية ولكنها مرتبطة/معتمدة دون تحديد فئتها المحددة. + +حسب ويكيبيديا + +> يوفر نمط المصنع المجرد طريقة لتغليف مجموعة من المصانع الفردية التي لها موضوع مشترك دون تحديد فئاتها المحددة. + +**مثال برمجي** + +ترجمة المثال السابق حول الممالك. أولاً لدينا بعض الواجهات والتنفيذات لكائنات `Castle`. + + +```java +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 بطريقة مشابهة +-> ... + +``` + +ثم لدينا التجريد والتنفيذ لمصنع المملكة `KingdomFactory`. + + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +الآن لدينا المصنع المجرد الذي يسمح لنا بإنشاء عائلات من الكائنات المرتبطة. على سبيل المثال، مصنع المملكة الإلفية `ElfKingdomFactory` يقوم بإنشاء القلعة `castle`، الملك `king`، والجيش `army`، إلخ. + + + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +ناتج البرنامج: + + +```java +This is the elven castle! +This is the elven king! +This is the elven Army! +``` + +الآن يمكننا تصميم مصنع لمصانع الممالك الخاصة بنا. في هذا المثال، قمنا بإنشاء `FactoryMaker`، المسؤول عن إعادة نسخة من `ElfKingdomFactory` أو `OrcKingdomFactory`. +يمكن للعميل استخدام `FactoryMaker` لإنشاء مصنع محدد، والذي بدوره سينتج كائنات محددة مختلفة (مشتقة من `Army` و `King` و `Castle`). +في هذا المثال نستخدم أيضًا `enum` لتمرير نوع مصنع المملكة الذي سيطلبه العميل. + + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + default -> throw new IllegalArgumentException("KingdomType not supported."); + }; + } +} + + public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + --similar use of the orc factory + } +``` + +## مخطط الفئات + +![alt text](./etc/abstract-factory.urm.png "Diagrama de Clases de Abstract Factory") + + +## التطبيق + +استخدم نمط المصنع المجرد عندما: + +* يجب أن يكون النظام غير متحيز حول كيفية إنشاء وتركيب وتمثيل كائناته. +* يجب تكوين النظام مع إحدى عائلات المنتجات المتعددة. +* تم تصميم عائلة الكائنات المرتبطة لتستخدم معًا وتحتاج إلى فرض هذا الافتراض. +* ترغب في توفير مكتبة من المنتجات ولا تريد الكشف عن تنفيذاتها، بل واجهاتها فقط. +* العمر الافتراضي للاعتماد هو مفهومًا أقصر من عمر العميل. +* تحتاج إلى قيمة في وقت التشغيل لبناء الاعتماد. +* تريد تحديد أي منتج من العائلة يتم استدعاؤه في وقت التشغيل. +* تحتاج إلى توفير واحد أو أكثر من المعلمات المعروفة فقط في وقت التشغيل قبل أن تتمكن من حل الاعتماد. +* تحتاج إلى الاتساق بين المنتجات. +* لا تريد تغيير الكود الموجود عند إضافة منتجات أو عائلات جديدة من المنتجات إلى البرنامج. + +أمثلة على حالات الاستخدام + +* اختيار استدعاء التنفيذ الصحيح لـ FileSystemAcmeService أو DatabaseAcmeService أو NetworkAcmeService في وقت التشغيل. +* كتابة الاختبارات الوحدوية تصبح أسهل بكثير. +* أدوات واجهة المستخدم (UI) لأنظمة تشغيل مختلفة (SO). + +## العواقب + +* إخفاء حقن الاعتمادات في جافا داخل كائنات الخدمة قد يؤدي إلى أخطاء في وقت التشغيل كان يمكن تجنبها في وقت الترجمة. +* بينما يكون النمط جيدًا في إنشاء كائنات محددة مسبقًا، قد يكون من الصعب إضافة الجديدة. +* الكود يصبح أكثر تعقيدًا مما ينبغي لأنه يتم إضافة العديد من الواجهات والفئات الجديدة جنبًا إلى جنب مع النمط. + +## الدروس التعليمية + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## الاستخدامات المعروفة + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## الأنماط المتعلقة + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## الحقوق + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/ar/abstract-factory/etc/abstract-factory.urm.png b/localization/ar/abstract-factory/etc/abstract-factory.urm.png new file mode 100644 index 000000000000..836858a2c652 Binary files /dev/null and b/localization/ar/abstract-factory/etc/abstract-factory.urm.png differ diff --git a/localization/ar/active-object/README.md b/localization/ar/active-object/README.md new file mode 100644 index 000000000000..842570a2604a --- /dev/null +++ b/localization/ar/active-object/README.md @@ -0,0 +1,126 @@ +--- +title: Active Object +shortTitle: Active Object +category: Concurrency +language: ar +tag: + - Performance +--- + + +## الهدف +يفصل نمط التصميم الكائن النشط بين تنفيذ الطريقة واستدعائها للكائنات التي تعمل في خيط تحكم خاص بها. الهدف هو إدخال التزامن باستخدام استدعاءات الطرق غير المتزامنة وجدولة لإدارة الطلبات. + +## التوضيح + +ستحتوي الفئة التي تنفذ نمط التصميم الكائن النشط على آلية مزامنة ذاتية دون استخدام الطرق المتزامنة (synchronized). + +مثال من العالم الحقيقي + +> الأورك معروفون بوحشيتهم وفلسفتهم في عدم العمل الجماعي. بناءً على هذا السلوك، يمكن القول إن لديهم خيط تحكم خاص بهم. + +يمكننا استخدام نمط الكائن النشط لتنفيذ مخلوق لديه خيط تحكم خاص به ويعرض واجهة برمجة التطبيقات (API) الخاصة به، ولكن ليس التنفيذ نفسه. + +**مثال برمجي** + + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` +يمكننا أن نرى أن أي فئة تمتد من ActiveCreature سيكون لديها خيط تحكم خاص بها لاستدعاء وتنفيذ الطرق. + +على سبيل المثال، الفئة Orc: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` +الآن يمكننا إنشاء مخلوقات متعددة مثل الأورك، نطلب منهم الأكل والتجول، وسيفعلون ذلك في خيط التحكم الخاص بهم: + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## مخطط الفئات + +![alt text](./etc/active-object.urm.png "Active Object class diagram") + +## الدروس التعليمية + +* [Android and Java Concurrency: The Active Object Pattern](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) \ No newline at end of file diff --git a/localization/ar/active-object/etc/active-object.urm.png b/localization/ar/active-object/etc/active-object.urm.png new file mode 100644 index 000000000000..c14f66144ee2 Binary files /dev/null and b/localization/ar/active-object/etc/active-object.urm.png differ diff --git a/localization/ar/acyclic-visitor/README.md b/localization/ar/acyclic-visitor/README.md new file mode 100644 index 000000000000..8bb8e01a154f --- /dev/null +++ b/localization/ar/acyclic-visitor/README.md @@ -0,0 +1,167 @@ +--- +title: Acyclic Visitor +shortTitle: Acyclic Visitor +category: Behavioral +language: ar +tag: + - Extensibility +--- +## الهدف + +السماح بإضافة وظائف جديدة إلى تسلسلات الفئات الموجودة دون التأثير عليها، ودون إنشاء الدوائر المعتمدة المزعجة التي هي جزء من نمط GoF (Gang of Four) للزائر (Visitor). + +## التوضيح + +مثال من العالم الحقيقي + +> لدينا تسلسل فئات مودم. يجب أن تتم زيارة المودمات في هذه التسلسلات بواسطة خوارزمية خارجية بناءً على بعض الفلاتر (هل المودم متوافق مع Unix أو DOS؟). + +بصيغة أخرى + +> يتيح نمط Acyclic Visitor إضافة وظائف إلى تسلسلات الفئات الموجودة دون تعديلها. + +[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) يقول + +> يسمح نمط Acyclic Visitor بإضافة وظائف جديدة إلى تسلسلات الفئات الموجودة دون التأثير عليها، ودون إنشاء الدوائر المعتمدة التي هي جزء من نمط الزائر (Visitor Pattern) في GangOfFour. + +**مثال برمجي** + +هنا لدينا تسلسل `Modem`. + + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + +بعد ذلك، لدينا تسلسل `ModemVisitor`. + + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + ... + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + ... + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +وأخيرًا، هنا "الزوار" في العمل. + + +```java + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + var zoom = new Zoom(); + var hayes = new Hayes(); + hayes.accept(conDos); + zoom.accept(conDos); + hayes.accept(conUnix); + zoom.accept(conUnix); +``` + +ناتج البرنامج: + + +``` + // Hayes modem used with Dos configurator. + // Zoom modem used with Dos configurator. + // Only HayesVisitor is allowed to visit Hayes modem + // Zoom modem used with Unix configurator. +``` + + +## مخطط الفئات + +![alt text](./etc/acyclic-visitor.png "Acyclic Visitor") + +## التطبيق + +يمكن استخدام هذا النمط في الحالات التالية: + +* عندما تحتاج إلى إضافة وظيفة جديدة إلى تسلسل فئات دون التأثير عليها أو تعديلها. +* عندما توجد وظائف تعمل على التسلسل ولكنها لا تنتمي إلى التسلسل بحد ذاته. على سبيل المثال، الفئات `ConfigureForDOS` و `ConfigureForUnix` و `ConfigureForX`. +* عندما تحتاج إلى تنفيذ عمليات مختلفة تمامًا على كائن اعتمادًا على نوعه. +* عندما يكون من المتوقع توسيع التسلسل الزائر بشكل متكرر باستخدام مشتقات من فئة العنصر. +* عندما يكون عملية إعادة التجميع، الربط، الاختبار أو توزيع المشتقات من فئة العنصر مرهقة جدًا. + +## الدروس التعليمية + +* [Acyclic Visitor Pattern Example](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) + +## العواقب + +الجوانب الجيدة: + +* لا توجد دوائر اعتماد بين التسلسلات. +* لا حاجة لإعادة تجميع جميع الزوار إذا تم إضافة زائر جديد. +* لا يسبب أخطاء في الترجمة في الزوار الموجودين إذا كانت التسلسل تحتوي على عضو جديد. + +الجوانب السيئة: + + +* ينتهك [مبدأ الاستبدال في ليسكوف](https://java-design-patterns.com/principles/#liskov-substitution-principle) من خلال إظهار أنه يمكن قبول جميع الزوار مع الاهتمام بزائر واحد فقط. +* يجب إنشاء تسلسل زوار موازٍ لجميع الأعضاء في التسلسل الذي يمكن زيارته. + +## الأنماط المتعلقة + +* [Visitor Pattern](https://java-design-patterns.com/patterns/visitor/) + + +## الحقوق + + +* [Acyclic Visitor by Robert C. Martin](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor in WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) diff --git a/localization/ar/acyclic-visitor/etc/acyclic-visitor.png b/localization/ar/acyclic-visitor/etc/acyclic-visitor.png new file mode 100644 index 000000000000..7b4df13d80f8 Binary files /dev/null and b/localization/ar/acyclic-visitor/etc/acyclic-visitor.png differ diff --git a/localization/ar/adapter/README.md b/localization/ar/adapter/README.md new file mode 100644 index 000000000000..06cb0a14ae6e --- /dev/null +++ b/localization/ar/adapter/README.md @@ -0,0 +1,141 @@ +--- +title: Adapter +shortTitle: Adapter +category: Structural +language: ar +tag: + - Gang of Four +--- + +## أيضًا معروف بـ +الغطاء (Wrapper) + +## الهدف +تحويل واجهة فئة إلى واجهة أخرى يتوقعها العميل. يتيح نمط المحول (Adapter) للفئات العمل مع فئات أخرى التي لا يمكنها العمل معها في الظروف العادية بسبب مشاكل التوافق. + +## التوضيح + +مثال من العالم الحقيقي + +> تخيل أنك تمتلك بعض الصور في بطاقة ذاكرة وتريد نقلها إلى جهاز الكمبيوتر الخاص بك. لنقل الصور، تحتاج إلى نوع من المحول الذي يتوافق مع منافذ جهاز الكمبيوتر الخاص بك ويسمح لك بإدخال البطاقة. في هذه الحالة، قارئ البطاقات هو محول (Adapter). +> مثال آخر هو محول التيار الكهربائي؛ إذا كان هناك قابس بثلاثة دبابيس ولا يمكن توصيله بمنفذ كهربائي به ثقبين، فإنه يحتاج إلى محول لجعله متوافقًا مع المنفذ. +> مثال آخر هو مترجم يترجم كلمات من شخص لآخر. + +بصيغة أخرى + +> يتيح نمط المحول (Adapter) تغليف كائن داخل محول لجعله متوافقًا مع فئة سيكون غير متوافق معها بطريقة أخرى. + +حسب ويكيبيديا + +> في هندسة البرمجيات، نمط المحول هو نمط تصميم برمجي يسمح باستخدام واجهة فئة موجودة كواجهة مختلفة. وغالبًا ما يُستخدم لجعل الفئات الموجودة تعمل مع فئات أخرى دون الحاجة إلى تعديل كود المصدر الخاص بها. + +**مثال برمجي** + +خذ على سبيل المثال قبطان يمكنه فقط استخدام القوارب التي تعمل بالمجاديف ولا يمكنه الإبحار على الإطلاق. + +أولاً، لدينا الواجهات `RowingBoat` (قارب المجاديف) و `FishingBoat` (قارب الصيد). + +```java +public interface RowingBoat { + void row(); +} + +@Slf4j +public class FishingBoat { + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } +} +``` + +ويتوقع القبطان تنفيذ واجهة `RowingBoat` (قارب المجاديف) ليتمكن من التحرك. + + +```java +public class Captain { + + private final RowingBoat rowingBoat; + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +الآن لنفترض أن مجموعة من القراصنة قد جاءت ويجب على قائدنا الهروب، ولكن هناك فقط قارب صيد. نحتاج إلى إنشاء محول يسمح للقائد باستخدام قارب الصيد مع مهاراته لاستخدام القوارب التي تعمل بالمجاديف. + + +```java +@Slf4j +public class FishingBoatAdapter implements RowingBoat { + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} +``` + +والآن يمكن لـ `Captain` (القائد) استخدام `FishingBoat` (قارب الصيد) للهروب من القراصنة. + + +```java +var captain = new Captain(new FishingBoatAdapter()); +captain.row(); +``` + +## مخطط الفئات +![alt text](./etc/adapter.urm.png "Adapter class diagram") + +## التطبيق +استخدم نمط المحول (Adapter) عندما: + +* تريد استخدام فئة موجودة وواجهتها لا تتناسب مع ما تحتاجه. +* تريد إنشاء فئة قابلة لإعادة الاستخدام تتعاون مع فئات غير مرتبطة أو لم يكن من المخطط تعاونها معًا، أي فئات ليس لديها بالضرورة واجهات متوافقة. +* تحتاج إلى استخدام عدة فئات فرعية موجودة، ولكن من غير العملي تعديل واجهتها عن طريق إنشاء فئات فرعية لكل واحدة. يمكن للمحول تعديل واجهة الفئة الأصلية. +* العديد من التطبيقات التي تستخدم مكتبات طرف ثالث تستخدم المحولات كطبقات وسيطة بين التطبيق والمكتبة لفصل التطبيق عن المكتبة. إذا كان من الضروري استخدام مكتبة أخرى، يكفي إنشاء محول للمكتبة الجديدة دون الحاجة إلى تعديل كود التطبيق. + +## الدروس + + +* [Dzone](https://dzone.com/articles/adapter-design-pattern-in-java) +* [Refactoring Guru](https://refactoring.guru/design-patterns/adapter/java/example) +* [Baeldung](https://www.baeldung.com/java-adapter-pattern) + +## العواقب +المحولات بين الفئات والكائنات لها خصائص مختلفة. محول الفئات + +* يقوم بإجراء التكيف ويرتبط بفئة محددة. كنتيجة لذلك، لن يعمل محول الفئات عندما نريد تكيف فئة وفئاتها الفرعية. +* يسمح للمحول بتعديل سلوك الفئة المتكيفة لأن المحول هو فئة فرعية من الفئة المتكيفة. +* يستخدم كائنًا واحدًا ولا يحتاج إلى استخدام مؤشرات إضافية للإشارة إلى الفئة المتكيفة. + +محوّل الكائنات + +* يسمح للمحول الواحد بالعمل مع العديد من الفئات، أي مع الفئة المتكيفة وكل الفئات الفرعية لها (إذا كانت موجودة). يمكن للمحول أيضًا إضافة وظائف إلى جميع الفئات المتكيفة في نفس الوقت. +* يجعل من الصعب تعديل سلوك الفئة المتكيفة. سيكون من الضروري إنشاء فئة فرعية للفئة المتكيفة وجعل المحول يشير إلى الفئة الفرعية بدلاً من الفئة الأصلية. + +## أمثلة من العالم الواقعي + + +* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +* [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +* [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + + +## الشكر + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/ar/adapter/etc/adapter.urm.png b/localization/ar/adapter/etc/adapter.urm.png new file mode 100644 index 000000000000..341ad67699d9 Binary files /dev/null and b/localization/ar/adapter/etc/adapter.urm.png differ diff --git a/localization/ar/aggregator-microservices/README.md b/localization/ar/aggregator-microservices/README.md new file mode 100644 index 000000000000..40d3ff26f7a8 --- /dev/null +++ b/localization/ar/aggregator-microservices/README.md @@ -0,0 +1,111 @@ +--- +title: Aggregator Microservices +shortTitle: Aggregator Microservices +category: Architectural +language: ar +tag: +- Cloud distributed +- Decoupling +- Microservices +--- + +## الهدف + +يقوم المستخدم بإجراء مكالمة واحدة إلى خدمة المجمع، ومن ثم يقوم المجمع بالاتصال بكل خدمة ميكروسيرفيس ذات صلة. + +## الشرح + +مثال من العالم الواقعي + +> يحتاج سوقنا الإلكتروني إلى معلومات حول المنتجات والمخزون الحالي. يقوم بإجراء مكالمة إلى خدمة المجمع التي بدورها تتصل بخدمة ميكروسيرفيس المعلومات الخاصة بالمنتج وخدمة ميكروسيرفيس المخزون للمنتج التي تعيد المعلومات مجمعة. + +ببساطة + +> يقوم ميكروسيرفيس المجمع بجمع البيانات من عدة ميكروسيرفيسات ويعيد النتيجة مجمعة لمعالجتها. + +يقول StackOverflow + +> يقوم ميكروسيرفيس المجمع بالاتصال بعدة خدمات لتحقيق الوظيفة المطلوبة من التطبيق. + +**مثال برمجي** + +لنبدأ بنموذج البيانات. هنا هو `Product`. + + +```java +public class Product { + private String title; + private int productInventories; + // getters and setters -> + ... +} +``` + +بعد ذلك، يمكننا تقديم ميكروسيرفيسنا `Aggregator` (مجمع الميكروسيرفيسات). يحتوي على `ProductInformationClient` (عميل معلومات المنتج) و +`ProductInventoryClient` (عميل مخزون المنتج) للاتصال بالميكروسيرفيسات المعنية. + + +```java +@RestController +public class Aggregator { + + @Resource + private ProductInformationClient informationClient; + + @Resource + private ProductInventoryClient inventoryClient; + + @RequestMapping(path = "/product", method = RequestMethod.GET) + public Product getProduct() { + + var product = new Product(); + var productTitle = informationClient.getProductTitle(); + var productInventory = inventoryClient.getProductInventories(); + + //Fallback to error message + product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed")); + + //Fallback to default error inventory + product.setProductInventories(requireNonNullElse(productInventory, -1)); + + return product; + } +} +``` + +هذه هي جوهر تنفيذ الميكروسيرفيسات للمعلومات. ميكروسيرفيس المخزون مشابه، ببساطة يعيد +عدد المخزون. + + +```java +@RestController +public class InformationController { + @RequestMapping(value = "/information", method = RequestMethod.GET) + public String getProductTitle() { + return "The Product Title."; + } +} +``` + +الآن عند استدعاء واجهة برمجة التطبيقات REST الخاصة بنا `Aggregator` تُرجع معلومات المنتج. + + +```bash +curl http://localhost:50004/product +{"title":"The Product Title.","productInventories":5} +``` + +## مخطط الفئة + +![alt text](./aggregator-service/etc/aggregator-service.png "Aggregator Microservice") + +## قابلية التطبيق + +استخدم نمط تجميع الميكروسيرفيسات (Aggregator Microservices) عندما تحتاج إلى واجهة برمجة تطبيقات موحدة لعدة ميكروسيرفيسات، بغض النظر عن جهاز العميل. + + +## الشكر + +* [أنماط تصميم الميكروسيرفيس](http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/) +* [أنماط الميكروسيرفيس: مع أمثلة في Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=8b4e570267bc5fb8b8189917b461dc60) +* [أنماط العمارة: اكتشاف الأنماط الأساسية في أكثر المجالات ضرورة في العمارة المؤسسية](https://www.amazon.com/gp/product/B077T7V8RC/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B077T7V8RC&linkId=c34d204bfe1b277914b420189f09c1a4) diff --git a/localization/ar/aggregator-microservices/aggregator-service/etc/aggregator-service.png b/localization/ar/aggregator-microservices/aggregator-service/etc/aggregator-service.png new file mode 100644 index 000000000000..75ee82328bbe Binary files /dev/null and b/localization/ar/aggregator-microservices/aggregator-service/etc/aggregator-service.png differ diff --git a/localization/ar/ambassador/README.md b/localization/ar/ambassador/README.md new file mode 100644 index 000000000000..b70fe071eb31 --- /dev/null +++ b/localization/ar/ambassador/README.md @@ -0,0 +1,210 @@ +--- +title: Ambassador +shortTitle: Ambassador +category: Structural +language: ar +tag: + - Decoupling + - Cloud distributed +--- + +## الهدف + +توفير مثيل من الخدمة المساعدة للعميل وتفويض الوظائف المشتركة لها من مصدر مشترك. + +## الشرح + +مثال واقعي + +> خدمة بعيدة تحتوي على العديد من العملاء الذين يصلون إلى وظيفة تقدمها هذه الخدمة. الخدمة هي تطبيق قديم ومن +> المستحيل تحديثها. عدد كبير من الطلبات من قبل المستخدمين تسبب مشاكل في الاتصال. يجب تنفيذ قواعد جديدة +> بشأن تكرار الطلبات جنبًا إلى جنب مع فحوصات التأخير والسجلات من جانب العميل. + +بكلمات أخرى + +> باستخدام نمط Ambassador، يمكننا تنفيذ تقليل تكرار الطلبات من العملاء جنبًا إلى جنب مع فحوصات التأخير +> والسجلات. + +وفقًا لوثائق مايكروسوفت + +> يمكن اعتبار خدمة Ambassador وكأنها وكيل خارج العملية يتواجد جنبًا إلى جنب مع العميل. +> +> يمكن أن يكون هذا النمط مفيدًا لتفريغ المهام المشتركة في الاتصال من العميل مثل المراقبة، السجلات، التوجيه، +> الأمان (مثل TLS) وأنماط المقاومة (*) بطريقة مستقلة عن اللغة. غالبًا ما يُستخدم مع التطبيقات القديمة، +> أو التطبيقات الأخرى التي يصعب تعديلها، بهدف توسيع قدراتها في الشبكات. يمكنه أيضًا +> تمكين فريق متخصص لتنفيذ هذه الميزات. + +**مثال على الكود** + +مع المقدمة السابقة في الاعتبار، سنقوم بمحاكاة وظيفتها في المثال التالي. لدينا واجهة يتم تنفيذها +من قبل الخدمة البعيدة وكذلك خدمة Ambassador: + +```java +interface RemoteServiceInterface { + long doRemoteFunction(int value) throws Exception; +} +``` + +## خدمة بعيدة ممثلة كـ Singleton (مثيل واحد). + +```java +@Slf4j +public class RemoteService implements RemoteServiceInterface { + private static RemoteService service = null; + + static synchronized RemoteService getRemoteService() { + if (service == null) { + service = new RemoteService(); + } + return service; + } + + private RemoteService() {} + + @Override + public long doRemoteFunction(int value) { + long waitTime = (long) Math.floor(Math.random() * 1000); + + try { + sleep(waitTime); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep interrupted", e); + } + + return waitTime >= 200 ? value * 10 : -1; + } +} +``` + +## خدمة السفير مع إضافة وظائف إضافية مثل السجلات والتحقق من الكمون + +```java +@Slf4j +public class ServiceAmbassador implements RemoteServiceInterface { + private static final int RETRIES = 3; + private static final int DELAY_MS = 3000; + + ServiceAmbassador() { + } + + @Override + public long doRemoteFunction(int value) { + return safeCall(value); + } + + private long checkLatency(int value) { + var startTime = System.currentTimeMillis(); + var result = RemoteService.getRemoteService().doRemoteFunction(value); + var timeTaken = System.currentTimeMillis() - startTime; + + LOGGER.info("Time taken (ms): " + timeTaken); + return result; + } + + private long safeCall(int value) { + var retries = 0; + var result = (long) FAILURE; + + for (int i = 0; i < RETRIES; i++) { + if (retries >= RETRIES) { + return FAILURE; + } + + if ((result = checkLatency(value)) == FAILURE) { + LOGGER.info("Failed to reach remote: (" + (i + 1) + ")"); + retries++; + try { + sleep(DELAY_MS); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep state interrupted", e); + } + } else { + break; + } + } + return result; + } +} +``` + +العميل لديه خدمة سفير محلية تستخدم للتفاعل مع الخدمة البعيدة: + + +```java +@Slf4j +public class Client { + private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador(); + + long useService(int value) { + var result = serviceAmbassador.doRemoteFunction(value); + LOGGER.info("Service result: " + result); + return result; + } +} +``` + +بعد ذلك، لدينا عميلان يستخدمان الخدمة: + + +```java +public class App { + public static void main(String[] args) { + var host1 = new Client(); + var host2 = new Client(); + host1.useService(12); + host2.useService(73); + } +} +``` + +هذه هي النتيجة التي سنحصل عليها بعد تنفيذ المثال: + + +```java +Time taken (ms): 111 +Service result: 120 +Time taken (ms): 931 +Failed to reach remote: (1) +Time taken (ms): 665 +Failed to reach remote: (2) +Time taken (ms): 538 +Failed to reach remote: (3) +Service result: -1 +``` + +## مخطط الفئات + +![alt text](./etc/ambassador.urm.png "مخطط فئات Ambassador") + +## التطبيقات + +يتم تطبيق نمط Ambassador عندما نعمل مع خدمة بعيدة قديمة لا يمكن تعديلها أو أنه سيكون من الصعب للغاية تعديلها. يمكن تنفيذ خصائص الاتصال في العميل دون الحاجة إلى إجراء تغييرات على الخدمة البعيدة. + +* يوفر Ambassador واجهة محلية لخدمة بعيدة. +* يوفر Ambassador سجلات، انقطاع الدائرة، إعادة المحاولات، والأمان في العميل. + +## حالات الاستخدام النموذجية + +* التحكم في الوصول إلى كائن آخر +* تنفيذ السجلات أو السجلات +* تنفيذ انقطاع الدائرة +* تفويض مهام الخدمات البعيدة +* تسهيل الاتصال بالشبكة + +## الاستخدامات المعروفة + +* [بوابة API المدمجة مع Kubernetes للخدمات الصغيرة](https://github.com/datawire/ambassador) + +## الأنماط ذات الصلة + +* [الوكيل (Proxy)](https://java-design-patterns.com/patterns/proxy/) + +## الشكر + +* [نمط Ambassador (وثائق Microsoft باللغة الإنجليزية)](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador) +* [تصميم الأنظمة الموزعة: الأنماط والمفاهيم للخدمات القابلة للتوسع وموثوقة](https://www.amazon.com/s?k=designing+distributed+systems&sprefix=designing+distri%2Caps%2C156&linkCode=ll2&tag=javadesignpat-20&linkId=a12581e625462f9038557b01794e5341&language=en_US&ref_=as_li_ss_tl) + +## ملاحظات المترجم +(*) تشير النسخة الأصلية بالإنجليزية من وثائق Microsoft إلى مصطلح المرونة +وفي الترجمة الإسبانية يتم ترجمته إلى المقاومة، على الرغم من ربطه بالقسم الخاص بنمط الموثوقية. انظر: +* [نسخة الوثائق الخاصة بنمط Ambassador من Microsoft باللغة الإسبانية.](https://learn.microsoft.com/es-es/azure/architecture/patterns/ambassador) diff --git a/localization/ar/ambassador/etc/ambassador.urm.png b/localization/ar/ambassador/etc/ambassador.urm.png new file mode 100644 index 000000000000..9b50a02ad356 Binary files /dev/null and b/localization/ar/ambassador/etc/ambassador.urm.png differ diff --git a/localization/ar/api-gateway/README.md b/localization/ar/api-gateway/README.md new file mode 100644 index 000000000000..a3f33a1c40eb --- /dev/null +++ b/localization/ar/api-gateway/README.md @@ -0,0 +1,170 @@ +--- +title: API Gateway +shortTitle: API Gateway +category: Architectural +language: ar +tag: + - Cloud distributed + - Decoupling + - Microservices +--- + +## الهدف + +إضافة استدعاءات إلى الخدمات الصغيرة في نفس المكان، بوابة API (API Gateway). يقوم المستخدم +بإجراء استدعاء بسيط إلى بوابة API، وتقوم بوابة API بدورها باستدعاء كل خدمة صغيرة ذات صلة. + +## الشرح + +مع نمط الخدمات الصغيرة، قد يحتاج العميل إلى بيانات من عدة خدمات صغيرة. إذا كان +العميل سيستدعي كل خدمة صغيرة بشكل مباشر، فقد يؤدي ذلك إلى أوقات تحميل طويلة، حيث +يجب على العميل إجراء طلب شبكة لكل خدمة صغيرة يتم استدعاؤها. بالإضافة إلى ذلك، وجود +استدعاء العميل لكل خدمة صغيرة يربط العميل مباشرة بتلك الخدمة الصغيرة - إذا حدث تغيير داخلي +في الخدمات الصغيرة (على سبيل المثال، إذا تم دمج خدمتين صغيرتين في وقت ما في المستقبل) أو إذا تغير الموقع (الخادم والمنفذ) لأحد الخدمات الصغيرة، فإن كل +عميل يستخدم تلك الخدمات الصغيرة يجب تحديثه. + +الهدف من نمط بوابة API هو تخفيف بعض هذه المشاكل. في نمط بوابة API، يتم وضع كيان إضافي +(بوابة API) بين العميل والخدمات الصغيرة. +مهمة بوابة API هي إضافة استدعاءات إلى الخدمات الصغيرة. بدلاً من أن يقوم العميل +بإجراء استدعاء لكل خدمة صغيرة على حدة، يقوم العميل باستدعاء بوابة API مرة واحدة فقط. ثم تقوم بوابة +API باستدعاء كل واحدة من الخدمات الصغيرة التي يحتاجها العميل. + +مثال واقعي + +> نحن نطبق نظام خدمات صغيرة وبوابة API لموقع تجارة إلكترونية. في هذا +> النظام تقوم بوابة API بإجراء استدعاءات إلى خدمات Image و Price. (الصورة والسعر) + +بمعنى آخر + +> في نظام يتم تنفيذه باستخدام بنية خدمات صغيرة، تعتبر بوابة API هي النقطة +> الوحيدة للوصول التي تجمع استدعاءات الخدمات الصغيرة الفردية. + +تقول ويكيبيديا + +> بوابة API هي خادم يعمل كواجهة أمامية لـ API، يستقبل طلبات API، ويطبق +> حدودًا وسياسات الأمان، ويرسل الطلبات إلى الخدمة الخلفية ثم يعيد +> الاستجابة إلى الطالب. غالبًا ما تشمل بوابة API محركًا للتحويل لتنظيم +> وتعديل الطلبات والاستجابات أثناء سير العملية. يمكن أن توفر بوابة +> API أيضًا وظائف مثل جمع تحليلات البيانات والتخزين المؤقت. قد +> توفر بوابة API وظائف لدعم المصادقة، والتفويض، والأمان، +> والتدقيق، والامتثال. + +**كود المثال** + +يوضح هذا التنفيذ كيف قد يبدو نمط بوابة API لموقع تجارة إلكترونية. تقوم +`ApiGateway` بإجراء استدعاءات إلى خدمات Image و Price باستخدام +`ImageClientImpl` و `PriceClientImpl` على التوالي. العملاء الذين يشاهدون الموقع +على جهاز مكتبي يمكنهم مشاهدة معلومات الأسعار وصورة المنتج، لذلك تقوم `ApiGateway` +بإجراء استدعاء إلى الخدمات الصغيرة وجمع البيانات في نموذج `DesktopProduct`. +ومع ذلك، فإن مستخدمي الأجهزة المحمولة يرون فقط معلومات الأسعار، ولا يشاهدون صورة المنتج. +بالنسبة لمستخدمي الأجهزة المحمولة، تقوم `ApiGateway` فقط +بالحصول على معلومات الأسعار، والتي تستخدم لإكمال `MobileProduct`. + +إليك تنفيذ خدمة الصورة (Image). + + +```java +public interface ImageClient { + String getImagePath(); +} + +public class ImageClientImpl implements ImageClient { + @Override + public String getImagePath() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50005/image-path")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +إليك تنفيذ خدمة المصغرة للسعر (Price). + +```java +public interface PriceClient { + String getPrice(); +} + +public class PriceClientImpl implements PriceClient { + + @Override + public String getPrice() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50006/price")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +هنا يمكننا أن نرى كيف تقوم بوابة الـ API بتوجيه الطلبات إلى الخدمات المصغرة. + +```java +public class ApiGateway { + + @Resource + private ImageClient imageClient; + + @Resource + private PriceClient priceClient; + + @RequestMapping(path = "/desktop", method = RequestMethod.GET) + public DesktopProduct getProductDesktop() { + var desktopProduct = new DesktopProduct(); + desktopProduct.setImagePath(imageClient.getImagePath()); + desktopProduct.setPrice(priceClient.getPrice()); + return desktopProduct; + } + + @RequestMapping(path = "/mobile", method = RequestMethod.GET) + public MobileProduct getProductMobile() { + var mobileProduct = new MobileProduct(); + mobileProduct.setPrice(priceClient.getPrice()); + return mobileProduct; + } +} +``` + +## مخطط الفئة + +![alt text](./etc/api-gateway.png "API Gateway") + +## التطبيقات + +استخدم نمط API Gateway عندما + +* تكون تستخدم بنية ميكروسيرفيسز وتحتاج إلى نقطة تجميع واحدة لاستدعاءات الميكروسيرفيسز. + +## الدروس التعليمية + +* [Exploring the New Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway) +* [Spring Cloud - Gateway](https://www.tutorialspoint.com/spring_cloud/spring_cloud_gateway.htm) +* [Getting Started With Spring Cloud Gateway](https://dzone.com/articles/getting-started-with-spring-cloud-gateway) + +## الشكر + +* [microservices.io - API Gateway](http://microservices.io/patterns/apigateway.html) +* [NGINX - Building Microservices: Using an API Gateway](https://www.nginx.com/blog/building-microservices-using-an-api-gateway/) +* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=ac7b6a57f866ac006a309d9086e8cfbd) +* [Building Microservices: Designing Fine-Grained Systems](https://www.amazon.com/gp/product/1491950358/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1491950358&linkId=4c95ca9831e05e3f0dadb08841d77bf1) diff --git a/api-gateway/etc/api-gateway.png b/localization/ar/api-gateway/etc/api-gateway.png similarity index 100% rename from api-gateway/etc/api-gateway.png rename to localization/ar/api-gateway/etc/api-gateway.png diff --git a/localization/ar/arrange-act-assert/README.md b/localization/ar/arrange-act-assert/README.md new file mode 100644 index 000000000000..ed99bb686a7f --- /dev/null +++ b/localization/ar/arrange-act-assert/README.md @@ -0,0 +1,142 @@ +--- +title: Arrange/Act/Assert +shortTitle: Arrange/Act/Assert +category: Idiom +language: ar +tag: + - Testing +--- + +## أيضا معروف بـ + +Dado/Cuando/Entonces + +## الغرض + +Arrange/Act/Assert (AAA) هو نمط لتنظيم اختبارات الوحدة. +يقسم اختبارات الوحدة إلى ثلاث خطوات واضحة ومميزة: + +1. Arrange(تنظيم): قم بإعداد التهيئة والتهيئة اللازمة للاختبار. +2. Act(العمل): اتخذ التدابير اللازمة للاختبار. +3. Assert(التأكيد): تحقق من نتائج الاختبار. + +## الشرح + +لهذا النمط العديد من الفوائد الكبيرة. فهو يخلق فصلًا واضحًا بين إعدادات الاختبار، العمليات والنتائج. هذا الهيكل يجعل الكود أسهل في القراءة والفهم. إذا +وضعت الخطوات بالترتيب وصيغت الكود بطريقة تفصلها، يمكنك مسح الاختبار وفهمه بسرعة. + +كما أنه يفرض درجة معينة من الانضباط عند كتابة اختبارات الوحدة. يجب أن تكون قادرًا على تصور +بوضوح الخطوات الثلاث التي سيقوم بها اختبارك. هذا يجعل الاختبارات أكثر بديهية للكتابة مع الحفاظ على هيكل واضح. + +مثال يومي + +> نحتاج إلى كتابة مجموعة من اختبارات الوحدة كاملة وواضحة لفئة. + +بعبارة أخرى + +> Arrange/Act/Assert هو نمط اختبار ينظم الاختبارات إلى ثلاث خطوات واضحة لتسهيل +> الصيانة. + +WikiWikiWeb يقول + +> Arrange/Act/Assert هو نمط لتنظيم وتنسيق الكود في طرق اختبار الوحدة. + +**كود المثال** + +لنلقِ نظرة أولاً على فئتنا `Cash` التي سيتم اختبارها. + + +```java +public class Cash { + + private int amount; + + Cash(int amount) { + this.amount = amount; + } + + void plus(int addend) { + amount += addend; + } + + boolean minus(int subtrahend) { + if (amount >= subtrahend) { + amount -= subtrahend; + return true; + } else { + return false; + } + } + + int count() { + return amount; + } +} +``` + +ثم نكتب اختبارات الوحدة الخاصة بنا بناءً على نمط Arrange/Act/Assert. لاحظ بوضوح الفصل بين الخطوات لكل اختبار وحدة. + + +```java +class CashAAATest { + + @Test + void testPlus() { + //Arrange + var cash = new Cash(3); + //Act + cash.plus(4); + //Assert + assertEquals(7, cash.count()); + } + + @Test + void testMinus() { + //Arrange + var cash = new Cash(8); + //Act + var result = cash.minus(5); + //Assert + assertTrue(result); + assertEquals(3, cash.count()); + } + + @Test + void testInsufficientMinus() { + //Arrange + var cash = new Cash(1); + //Act + var result = cash.minus(6); + //Assert + assertFalse(result); + assertEquals(1, cash.count()); + } + + @Test + void testUpdate() { + //Arrange + var cash = new Cash(5); + //Act + cash.plus(6); + var result = cash.minus(3); + //Assert + assertTrue(result); + assertEquals(8, cash.count()); + } +} +``` + +## القابلية للتطبيق + +استخدم نمط Arrange/Act/Assert عندما + +* تحتاج إلى تنظيم اختبارات الوحدة الخاصة بك لتكون أسهل في القراءة والصيانة والتحسين. + +## الشكر + +* [Arrange, Act, Assert: ¿Qué son las pruebas AAA?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx) +* [Bill Wake: 3A – Arrange, Act, Assert](https://xp123.com/articles/3a-arrange-act-assert/) +* [Martin Fowler: DadoCuandoEntonces](https://martinfowler.com/bliki/GivenWhenThen.html) +* [Patrones de prueba xUnit: Refactorizando Código de prueba](https://www.amazon.com/gp/product/0131495054/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0131495054&linkId=99701e8f4af2f63d0bcf50) +* [Principios, prácticas y patrones UnitTesting](https://www.amazon.com/gp/product/1617296279/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617296279&linkId=74c75cfae3a5aaccae3a5a) +* [Desarrollo basado en pruebas: Ejemplo](https://www.amazon.com/gp/product/0321146530/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321146530&linkId=5c63a93d8c1175b47caef50875) diff --git a/localization/ar/async-method-invocation/README.md b/localization/ar/async-method-invocation/README.md new file mode 100644 index 000000000000..05173d7d6104 --- /dev/null +++ b/localization/ar/async-method-invocation/README.md @@ -0,0 +1,178 @@ +--- +title: Async Method Invocation +shortTitle: Async Method Invocation +category: Concurrency +language: ar +tag: + - Reactive +--- + +## الغرض + +الاستدعاء غير المتزامن للطرق (invocación de método asincrónico) هو نمط حيث لا يتم حظر الخيط أو العملية التي تستدعي الطريقة أثناء انتظار النتائج. يوفر النمط معالجة متوازية للمهام المستقلة المتعددة ويسترجع النتائج عبر +التعريفات الراجعة (callbacks) أو بالانتظار حتى ينتهي الإجراء. + +## الشرح + +مثال يومي + +> إطلاق الصواريخ الفضائية هو عمل مثير. يعطي قائد المهمة أمر الإطلاق و +> بعد فترة غير محددة من الوقت، يتم إطلاق الصاروخ بنجاح أو يفشل بشكل كارثي. + +بعبارة أخرى + +> يستدعي الاستدعاء غير المتزامن للطرق الإجراء ويعود فورًا قبل أن تنتهي المهمة +> يتم إرجاع نتائج الإجراء لاحقًا إلى الاستدعاء (callback). + +حسب ويكيبيديا + +> في البرمجة متعددة العمليات، يعتبر استدعاء الطريقة غير المتزامن (AMI)، المعروف أيضًا بـ +> الاستدعاءات غير المتزامنة أو النمط غير المتزامن هو نمط تصميم حيث لا يتم حظر مكان الاستدعاء +> أثناء انتظار انتهاء الكود المستدعى. بدلاً من ذلك، يتم إخطار خيط الاستدعاء عندما تصل الاستجابة. الاستطلاع للحصول على إجابة هو خيار غير مرغوب فيه. + +**مثال برمجي** + +في هذا المثال، نحن نطلق صواريخ فضائية وننشر مركبات قمرية. + +تُظهر التطبيق ما يفعله نمط الاستدعاء غير المتزامن للطريقة. الأجزاء الرئيسية للنمط هي +`AsyncResult` الذي يعد حاوية وسيطة لقيمة تم تقييمها بشكل غير متزامن، +`AsyncCallback` الذي يمكن توفيره ليتم تنفيذه عند اكتمال المهمة و `AsyncExecutor` الذي +يدير تنفيذ المهام غير المتزامنة. + + +```java +public interface AsyncResult { + boolean isCompleted(); + T getValue() throws ExecutionException; + void await() throws InterruptedException; +} +``` + +```java +public interface AsyncCallback { + void onComplete(T value, Optional ex); +} +``` + +```java +public interface AsyncExecutor { + AsyncResult startProcess(Callable task); + AsyncResult startProcess(Callable task, AsyncCallback callback); + T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException; +} +``` + +`ThreadAsyncExecutor` هو تنفيذ لـ `AsyncExecutor`. يتم تسليط الضوء على بعض من أجزائه الرئيسية أدناه. + + +```java +public class ThreadAsyncExecutor implements AsyncExecutor { + + @Override + public AsyncResult startProcess(Callable task) { + return startProcess(task, null); + } + + @Override + public AsyncResult startProcess(Callable task, AsyncCallback callback) { + var result = new CompletableResult<>(callback); + new Thread( + () -> { + try { + result.setValue(task.call()); + } catch (Exception ex) { + result.setException(ex); + } + }, + "executor-" + idx.incrementAndGet()) + .start(); + return result; + } + + @Override + public T endProcess(AsyncResult asyncResult) + throws ExecutionException, InterruptedException { + if (!asyncResult.isCompleted()) { + asyncResult.await(); + } + return asyncResult.getValue(); + } +} +``` + +الآن كل شيء جاهز لإطلاق بعض الصواريخ لرؤية كيف يعمل كل شيء. + + +```java +public static void main(String[] args) throws Exception { + // الآن كل شيء جاهز لإطلاق بعض الصواريخ لرؤية كيف يعمل كل شيء. + + var executor = new ThreadAsyncExecutor(); + + // يبدأ بعض المهام غير المتزامنة بأوقات معالجة مختلفة، اثنان من الأخيرين مع محركات استرجاع (callback handlers) + + final var asyncResult1 = executor.startProcess(lazyval(10, 500)); + final var asyncResult2 = executor.startProcess(lazyval("test", 300)); + final var asyncResult3 = executor.startProcess(lazyval(50L, 700)); + final var asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Desplegando el rover lunar")); + final var asyncResult5 = + executor.startProcess(lazyval("devolución de llamada callback", 600), callback("Desplegando el rover lunar")); + + // يحاكي المعالجة في الخيط أو العملية الحالية بينما يتم تنفيذ المهام غير المتزامنة في خيوط أو عملياتها الخاصة + + Subproceso.dormir(350); // هيه، نحن نعمل بجد هنا + + log("قائد المهمة يشرب القهوة +"); + + // ينتظر حتى اكتمال المهام + + final var result1 = executor.endProcess(asyncResult1); + final var result2 = executor.endProcess(asyncResult2); + final var result3 = executor.endProcess(asyncResult3); + asyncResult4.await(); + asyncResult5.await(); + +// يسجل نتائج المهام، يتم تسجيل الاسترجاعات فور اكتمالها +log("الصاروخ الفضائي <" + resultado1 + "> أكمل إطلاقه"); +log("الصاروخ الفضائي <" + resultado2 + "> أكمل إطلاقه"); +log("الصاروخ الفضائي <" + result3 + "> أكمل إطلاقه"); + +} +``` + +Here is the output from the program console. + +```java +21:47:08.227 [executor-2] INFO com.iluwatar.async.method.invocation.App - الصاروخ الفضائي تم إطلاقه بنجاح +21:47:08.269 [main] INFO com.iluwatar.async.method.invocation.App - قائد المهمة يشرب القهوة +21:47:08.318 [executor-4] INFO com.iluwatar.async.method.invocation.App - الصاروخ الفضائي <20> تم إطلاقه بنجاح +21:47:08.335 [executor-4] INFO com.iluwatar.async.method.invocation.App - نشر الروفر القمري <20> +21:47:08.414 [executor-1] INFO com.iluwatar.async.method.invocation.App - الصاروخ الفضائي <10> تم إطلاقه بنجاح +21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - الصاروخ الفضائي تم إطلاقه بنجاح +21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - تنفيذ المركبة القمرية +21:47:08.616 [executor-3] INFO com.iluwatar.async.method.invocation.App - الصاروخ الفضائي <50> تم إطلاقه بنجاح +21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - إطلاق الصاروخ الفضائي <10> تم +21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - إطلاق الصاروخ الفضائي تم +21:47:08.618 [main] INFO com.iluwatar.async.method.invocation.App - إطلاق الصاروخ الفضائي <50> تم + +``` + +# مخطط الفئة + +![texto alternativo](./etc/async-method-invocation.png "Invocación de método asíncrono") + +## القابلية للتطبيق + +استخدم نمط استدعاء الطريقة غير المتزامنة عندما + +* يكون لديك مهام مستقلة متعددة يمكن تنفيذها بشكل متوازٍ +* تحتاج إلى تحسين أداء مجموعة من المهام المتسلسلة +* لديك قدرة معالجة محدودة أو مهام تنفيذ طويلة الأمد ولا ينبغي أن تنتظر الدعوة حتى تصبح المهام جاهزة + +## أمثلة يومية + +* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html) +* [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) +* [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) +* [Patrón asíncrono basado en tareas](https://msdn.microsoft.com/en-us/library/hh873175.aspx) diff --git a/async-method-invocation/etc/async-method-invocation.png b/localization/ar/async-method-invocation/etc/async-method-invocation.png similarity index 100% rename from async-method-invocation/etc/async-method-invocation.png rename to localization/ar/async-method-invocation/etc/async-method-invocation.png diff --git a/localization/ar/balking/README.md b/localization/ar/balking/README.md new file mode 100644 index 000000000000..c43480d580bd --- /dev/null +++ b/localization/ar/balking/README.md @@ -0,0 +1,135 @@ +--- +title: Balking +shortTitle: Balking +category: Concurrency +language: ar +tag: + - Decoupling +--- + +## الغرض + +يتم استخدام نمط _Balking_ لمنع كائن من تنفيذ كود معين إذا كان في حالة غير مكتملة أو غير مناسبة. + +## الشرح + +مثال من الحياة الواقعية + +> في غسالة الملابس هناك زر بدء لتشغيل غسل الملابس. عندما تكون الغسالة غير نشطة، يعمل الزر كما هو متوقع، ولكن إذا كانت الغسالة تغسل بالفعل، فإن الزر لا يفعل شيئًا. + +بمعنى آخر + +> باستخدام نمط _Balking_، يتم تنفيذ كود معين فقط إذا كان الكائن في حالة معينة. + +تقول ويكيبيديا + +> نمط _Balking_ هو نمط تصميم برمجي ينفذ إجراء على كائن فقط عندما يكون الكائن في حالة معينة. على سبيل المثال، إذا كان الكائن يقرأ ملفات ZIP واستدعى أسلوب _get_ على الكائن عندما لا يكون الملف ZIP مفتوحًا، فإن الكائن "يرفض" (_balk_) الطلب. + +**مثال برمجي** + +في هذا المثال من التنفيذ، `WashingMachine` هو كائن له حالتان يمكن أن يكونا: _ENABLED_ و _WASHING_ (مفعل و يغسل على التوالي). إذا كانت الغسالة في حالة _ENABLED_، فإن الحالة تتغير إلى _WASHING_ باستخدام طريقة آمنة ضد الخيوط (thread-safe). من ناحية أخرى، إذا كانت الغسالة بالفعل تغسل وأي خيط آخر ينفذ `wash()`، فلن يتم تغيير الحالة وتنتهي تنفيذ الطريقة دون القيام بأي شيء. + +إليك الأجزاء ذات الصلة من فئة `WashingMachine`. + + +```java +@Slf4j +public class WashingMachine { + + private final DelayProvider delayProvider; + private WashingMachineState washingMachineState; + + public WashingMachine(DelayProvider delayProvider) { + this.delayProvider = delayProvider; + this.washingMachineState = WashingMachineState.ENABLED; + } + + public WashingMachineState getWashingMachineState() { + return washingMachineState; + } + + public void wash() { + synchronized (this) { + var machineState = getWashingMachineState(); + LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState); + if (this.washingMachineState == WashingMachineState.WASHING) { + LOGGER.error("Cannot wash if the machine has been already washing!"); + return; + } + this.washingMachineState = WashingMachineState.WASHING; + } + LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); + this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing); + } + + public synchronized void endOfWashing() { + washingMachineState = WashingMachineState.ENABLED; + LOGGER.info("{}: Washing completed.", Thread.currentThread().getId()); + } +} +``` + +هنا الواجهة البسيطة `DelayProvider` المستخدمة من قبل `WashingMachine`. + + +```java +public interface DelayProvider { + void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task); +} +``` + +الآن نقدم التطبيق باستخدام `WashingMachine`. + + +```java +public static void main(String... args) { + final var washingMachine = new WashingMachine(); + var executorService = Executors.newFixedThreadPool(3); + for (int i = 0; i < 3; i++) { + executorService.execute(washingMachine::wash); + } + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + LOGGER.error("ERROR: Waiting on executor service shutdown!"); + Thread.currentThread().interrupt(); + } +} +``` + +إليك مخرجات التطبيق في وحدة التحكم. + + +``` +14:02:52.268 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Actual machine state: ENABLED +14:02:52.272 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Doing the washing +14:02:52.272 [pool-1-thread-3] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-3: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-3] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.273 [pool-1-thread-1] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-1: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-1] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.324 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - 14: Washing completed. +``` + +## مخطط الفئات + + +![alt text](./etc/balking.png "Balking") + +## القابلية للتطبيق + +استخدم نمط _Balking_ عندما + +* يجب على كائن تنفيذ كود معين فقط عندما يكون في حالة معينة. +* الكائنات في حالة معرضة للتوقف مؤقتًا، ولكن لفترة زمنية غير محددة. + +## الأنماط ذات الصلة + + +* [Guarded Suspension Pattern](https://java-design-patterns.com/patterns/guarded-suspension/) +* [Double Checked Locking Pattern](https://java-design-patterns.com/patterns/double-checked-locking/) + +## المراجع + + +* [Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML, 2nd Edition, Volume 1](https://www.amazon.com/gp/product/0471227293/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0471227293&linkId=0e39a59ffaab93fb476036fecb637b99) diff --git a/localization/ar/balking/etc/balking.png b/localization/ar/balking/etc/balking.png new file mode 100644 index 000000000000..f409eaacbb95 Binary files /dev/null and b/localization/ar/balking/etc/balking.png differ diff --git a/localization/ar/bridge/README.md b/localization/ar/bridge/README.md new file mode 100644 index 000000000000..2c47f65ea747 --- /dev/null +++ b/localization/ar/bridge/README.md @@ -0,0 +1,216 @@ +--- +title: Bridge +shortTitle: Bridge +category: Structural +language: ar +tag: + - Gang of Four +--- + +## أيضًا معروف باسم + +Handle/Body + +## الهدف + +فصل التجريد عن تنفيذه بحيث يمكن لكل منهما التغيير بشكل مستقل. + +## الشرح + +مثال من الحياة الواقعية + +> تخيل أن لديك سلاحًا مع تعاويذ مختلفة، ومن المفترض أن تسمح بخلط أسلحة مختلفة مع تعاويذ مختلفة. ماذا ستفعل؟ هل ستقوم بإنشاء نسخ متعددة من كل سلاح لكل تعويذة من التعاويذ أو ببساطة تقوم بإنشاء تعويذة منفصلة وتحددها للسلاح حسب الحاجة؟ نمط Bridge يتيح لك القيام بالأمر الثاني. + +ببساطة + +> يتعلق نمط Bridge بتفضيل التركيب على الوراثة. يتم دفع تفاصيل التنفيذ من هرم إلى كائن آخر مع هرم منفصل. + +تقول ويكيبيديا + +> نمط Bridge هو نمط تصميم يستخدم في هندسة البرمجيات يهدف إلى "فصل التجريد عن تنفيذه بحيث يمكن لكل منهما التغيير بشكل مستقل." + +**مثال برمجي** + +نقلًا لمثال السلاح المذكور أعلاه. هنا لدينا واجهة السلاح `Weapon`: + + +```java +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; + } +} +``` + +إليك واجهة التعاويذ `Enchantment` المنفصلة: + + +```java +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."); + } +} +``` + +إليك كلا الواجهتين في العمل: + + +```java +LOGGER.info("The knight receives an enchanted sword."); +var enchantedSword = new Sword(new SoulEatingEnchantment()); +enchantedSword.wield(); +enchantedSword.swing(); +enchantedSword.unwield(); + +LOGGER.info("The valkyrie receives an enchanted hammer."); +var hammer = new Hammer(new FlyingEnchantment()); +hammer.wield(); +hammer.swing(); +hammer.unwield(); +``` + +إليك مخرجات التطبيق في وحدة التحكم. + + +``` +The knight receives an enchanted sword. +The sword is wielded. +The item spreads bloodlust. +The sword is swung. +The item eats the soul of enemies. +The sword is unwielded. +Bloodlust slowly disappears. +The valkyrie receives an enchanted hammer. +The hammer is wielded. +The item begins to glow faintly. +The hammer is swung. +The item flies and strikes the enemies finally returning to owner's hand. +The hammer is unwielded. +The item's glow fades. +``` + +## مخطط الفئات + + +![alt text](./etc/bridge.urm.png "Bridge diagrama de clases") + +## القابلية للتطبيق + +استخدم نمط Bridge عندما + +* ترغب في تجنب الربط الدائم بين التجريد وتنفيذه. قد يكون هذا هو الحال، على سبيل المثال، عندما يجب اختيار أو تغيير التنفيذ في وقت التشغيل. +* يجب أن تكون كل من التجريدات وتنفيذاتها قابلة للتوسيع عبر الوراثة. في هذه الحالة، يتيح لك نمط Bridge دمج التجريدات والتنفيذات المختلفة وتوسيعها بشكل مستقل. +* يجب ألا تؤثر التغييرات في تنفيذ التجريد على العملاء؛ أي أنه لا يجب أن يحتاج الكود الخاص بهم إلى إعادة تجميع. +* لديك تكاثر في الفئات. تشير مثل هذه الهرميات إلى الحاجة إلى تقسيم كائن إلى جزئين. يستخدم Rumbaugh مصطلح "التعميمات المتداخلة" للإشارة إلى مثل هذه الهرميات من الفئات. +* ترغب في مشاركة تنفيذ بين عدة كائنات (ربما باستخدام عد مرجعي)، ويجب إخفاء هذه الحقيقة عن العميل. مثال بسيط هو فئة String لـ Coplien، حيث يمكن لعدة كائنات مشاركة نفس تمثيل السلسلة. + +## الدروس التعليمية + +* [Bridge Pattern Tutorial](https://www.journaldev.com/1491/bridge-design-pattern-java) + +## الاعتمادات + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/ar/bridge/etc/bridge.urm.png b/localization/ar/bridge/etc/bridge.urm.png new file mode 100644 index 000000000000..785585bf8163 Binary files /dev/null and b/localization/ar/bridge/etc/bridge.urm.png differ diff --git a/localization/ar/builder/README.md b/localization/ar/builder/README.md new file mode 100644 index 000000000000..1edfb4b826db --- /dev/null +++ b/localization/ar/builder/README.md @@ -0,0 +1,147 @@ +--- +title: Builder +shortTitle: Builder +category: Creational +language: ar +tag: + - Gang of Four +--- + +## الهدف + +فصل بناء كائن معقد عن تمثيله بحيث يمكن لنفس عملية البناء إنشاء تمثيلات مختلفة. + +## الشرح + +مثال من الحياة الواقعية + +> تخيل مولد شخصيات للعبة تقمص أدوار. الخيار الأسهل هو السماح للكمبيوتر بإنشاء الشخصية نيابة عنك. إذا أردت تحديد تفاصيل الشخصية يدويًا مثل المهنة، الجنس، لون الشعر، إلخ، فإن إنشاء الشخصية يصبح عملية خطوة بخطوة تكتمل عندما تكون جميع الاختيارات جاهزة. + +ببساطة + +> يسمح بإنشاء نكهات مختلفة من كائن دون تلويث الباني. مفيد عندما يمكن أن يكون هناك عدة نكهات لكائن ما، أو عندما تكون هناك العديد من الخطوات المعنية في إنشاء الكائن. + +تقول ويكيبيديا + +> نمط البناء هو نمط تصميم برمجي لإنشاء الكائنات بهدف إيجاد حل لمضاد النمط الخاص بالباني المنطقي. + +مع ذلك، دعني أضيف بعض المعلومات حول ما هو مضاد النمط للباني المنطقي. في وقت ما أو آخر، رأينا جميعًا بانيًا مثل التالي: + + +```java +public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) { +} +``` + +كما ترى، قد يخرج عدد معلمات الباني عن السيطرة بسرعة، وقد يصبح من الصعب فهم ترتيب المعلمات. بالإضافة إلى ذلك، قد تستمر هذه القائمة في النمو إذا أردت إضافة المزيد من الخيارات في المستقبل. يسمى هذا مضاد النمط للباني المنطقي. + +**مثال برمجي** + +البديل الحكيم هو استخدام نمط Builder. أولاً، لدينا بطلنا `Hero` الذي نريد إنشائه: + + +```java +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; + } +} +``` + +ثم لدينا الباني: + + +```java + 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); + } + } +``` + +إذن يمكن استخدامه كما يلي: + + +```java +var mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build(); +``` + +## مخطط الفئات + +![alt text](./etc/builder.urm.png "مخطط فئات Builder") + +## القابلية للتطبيق + +استخدم نمط Builder عندما + +* يجب أن يكون الخوارزمية لإنشاء كائن معقدة مستقلة عن الأجزاء التي تتكون منها الكائن وكيفية تجميعها. +* يجب أن تسمح عملية البناء بتمثيلات مختلفة للكائن الذي يتم بناؤه. + +## الدروس التعليمية + +* [Refactoring Guru](https://refactoring.guru/design-patterns/builder) +* [مدونة Oracle](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) +* [Journal Dev](https://www.journaldev.com/1425/builder-design-pattern-in-java) + +## الاستخدامات في العالم الواقعي + +* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) +* [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) بالإضافة إلى غيرها من المخازن المؤقتة مثل FloatBuffer و IntBuffer، إلخ. +* [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) +* جميع التطبيقات من [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) +* [بناة Apache Camel](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## الاعتمادات + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/ar/builder/etc/builder.urm.png b/localization/ar/builder/etc/builder.urm.png new file mode 100644 index 000000000000..d77808d36097 Binary files /dev/null and b/localization/ar/builder/etc/builder.urm.png differ diff --git a/localization/ar/business-delegate/README.md b/localization/ar/business-delegate/README.md new file mode 100644 index 000000000000..13fe05b32db3 --- /dev/null +++ b/localization/ar/business-delegate/README.md @@ -0,0 +1,194 @@ +--- +title: Business Delegate +shortTitle: Business Delegate +category: Structural +language: ar +tag: + - Decoupling +--- + +## الغرض + +نمط **Business Delegate** يضيف طبقة من التجريد بين مستويات العرض والأعمال. باستخدام هذا النمط، نحقق ارتباطًا مرنًا بين المستويات ونعزل المعرفة حول كيفية تحديد المواقع والاتصال والتفاعل مع الكائنات التجارية التي تشكل التطبيق. + +## أيضًا معروف باسم + +مُمثل الخدمة + +## الشرح + +مثال من العالم الحقيقي + +> تطبيق للهواتف المحمولة يعد ببث أي فيلم موجود إلى جهازك. يقوم التطبيق بالتقاط سلسلة البحث من المستخدم ويمررها إلى **Business Delegate**. يقوم **Business Delegate** باختيار خدمة البث الأكثر ملاءمة ويبدأ في تشغيل الفيديو. + +بكلمات أبسط + +> يضيف **Business Delegate** طبقة من التجريد بين مستويات العرض والأعمال. + +تقول ويكيبيديا + +> **Business Delegate** هو نمط تصميم في Java EE. هذا النمط يهدف إلى تقليل الترابط بين خدمات الأعمال ومستوى العرض المتصل، وإخفاء تفاصيل التنفيذ الخاصة بالخدمات (بما في ذلك البحث والوصول إلى بنية EJB). يعمل **Business Delegate** كـ **مهايئ** لاستدعاء كائنات الأعمال من طبقة العرض. + +**مثال برمجي** + +أولاً، لدينا تجريد لخدمات البث عبر الفيديو `VideoStreamingService` مع زوج من التطبيقات `NetflixService` و `YouTubeService`. + + +```java +public interface VideoStreamingService { + void doProcessing(); +} + +@Slf4j +public class NetflixService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("NetflixService is now processing"); + } +} + +@Slf4j +public class YouTubeService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("YouTubeService is now processing"); + } +} +``` + +التالي، لدينا خدمة البحث `BusinessLookup` التي تقرر أي خدمة بث الفيديو يجب استخدامها. + + +```java + +@Setter +public class BusinessLookup { + + private NetflixService netflixService; + private YouTubeService youTubeService; + + public VideoStreamingService getBusinessService(String movie) { + if (movie.toLowerCase(Locale.ROOT).contains("die hard")) { + return netflixService; + } else { + return youTubeService; + } + } +} +``` + +يستخدم **Delegado de Negocio** `BusinessDelegate` بحث الأعمال لتوجيه طلبات تشغيل الأفلام إلى خدمة بث الفيديو المناسبة. + + +```java + +@Setter +public class BusinessDelegate { + + private BusinessLookup lookupService; + + public void playbackMovie(String movie) { + VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie); + videoStreamingService.doProcessing(); + } +} +``` + +العميل المحمول `MobileClient` يستخدم **Business Delegate** لاستدعاء مستوى الأعمال. + + +```java +public class MobileClient { + + private final BusinessDelegate businessDelegate; + + public MobileClient(BusinessDelegate businessDelegate) { + this.businessDelegate = businessDelegate; + } + + public void playbackMovie(String movie) { + businessDelegate.playbackMovie(movie); + } +} +``` + +أخيرًا، يمكننا عرض المثال الكامل أثناء التنفيذ. + + +```java + public static void main(String[]args){ + + // preparar los objetos + var businessDelegate=new BusinessDelegate(); + var businessLookup=new BusinessLookup(); + businessLookup.setNetflixService(new NetflixService()); + businessLookup.setYouTubeService(new YouTubeService()); + businessDelegate.setLookupService(businessLookup); + + // crear el cliente y utilizar el Business Delegate + var client=new MobileClient(businessDelegate); + client.playbackMovie("Die Hard 2"); + client.playbackMovie("Maradona: The Greatest Ever"); + } +``` + +إليك مخرجات وحدة التحكم. + + +``` +21:15:33.790 [main] INFO com.iluwatar.business.delegate.NetflixService - NetflixService is now processing +21:15:33.794 [main] INFO com.iluwatar.business.delegate.YouTubeService - YouTubeService is now processing +``` + +## مخطط الفئات + +![مخطط الفئات](./etc/business-delegate.urm.png "Business Delegate") + +## الأنماط ذات الصلة + +* [نمط تحديد الموقع للخدمات](https://java-design-patterns.com/patterns/service-locator/) + +## القابلية للتطبيق + +استخدم نمط Business Delegate عندما + +* ترغب في تقليل الترابط بين مستويات العرض والأعمال. +* ترغب في تنسيق المكالمات إلى خدمات أعمال متعددة. +* ترغب في تجميع عمليات البحث والمكالمات إلى الخدمات. +* من الضروري تجريد وتغليف الاتصال بين طبقة العميل وخدمات الأعمال. + +## دروس + +* [نمط Business Delegate في TutorialsPoint](https://www.tutorialspoint.com/design_pattern/business_delegate_pattern.htm) + +## الاستخدامات المعروفة + +* التطبيقات المؤسسية التي تستخدم Java EE (Java Platform, Enterprise Edition) +* التطبيقات التي تتطلب الوصول عن بُعد إلى خدمات الأعمال + +## العواقب + +الفوائد: + +* فك الترابط بين مستويات العرض والأعمال: يسمح بمواصلة تطور مستوى العميل والخدمات المؤسسية بشكل مستقل. +* شفافية الموقع: لا يتأثر العملاء بتغييرات الموقع أو التهيئة لخدمات الأعمال. +* إعادة الاستخدام وقابلية التوسع: يمكن إعادة استخدام كائنات Business Delegate بواسطة عملاء متعددين، ويدعم النمط التوازن في الحمل وقابلية التوسع. + +العيوب: + +* التعقيد: يضيف طبقات وتجريدات إضافية قد تزيد من التعقيد. +* تحميل الأداء: قد يؤدي الإشارة الإضافية إلى خفض طفيف في الأداء. + +## الأنماط ذات الصلة + +* [محدد خدمات](https://java-design-patterns.com/patterns/service-locator/): يستخدم Delegado de Negocio ( + Business Delegate) محدد خدمات (Service Locator) للعثور على خدمات الأعمال. +* [واجهة الجلسة](https://java-design-patterns.com/patterns/session-facade/): يمكن لـ Delegado de Negocio (Business + Delegate) استخدام واجهة الجلسة (Session Facade) لتوفير واجهة موحدة لمجموعة من خدمات الأعمال. +* [كائن مركب](https://java-design-patterns.com/patterns/composite-entity/): يمكن لـ Delegado de Negocio (Business Delegate) + استخدام الكائن المركب (Composite Entity) لإدارة حالة خدمات الأعمال. + +## الشكر + +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Core J2EE Patterns: Best Practices and Design Strategies](https://www.amazon.com/gp/product/0130648841/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0130648841&linkId=a0100de2b28c71ede8db1757fb2b5947) diff --git a/localization/ar/business-delegate/etc/business-delegate.urm.png b/localization/ar/business-delegate/etc/business-delegate.urm.png new file mode 100644 index 000000000000..4dca6c263b99 Binary files /dev/null and b/localization/ar/business-delegate/etc/business-delegate.urm.png differ diff --git a/localization/ar/bytecode/README.md b/localization/ar/bytecode/README.md new file mode 100644 index 000000000000..d5c046b4fccf --- /dev/null +++ b/localization/ar/bytecode/README.md @@ -0,0 +1,264 @@ +--- +title: Bytecode +shortTitle: Bytecode +category: Behavioral +language: ar +tag: + - Game programming +--- + +## الغرض + +يسمح بترميز السلوك كتعليمات لجهاز افتراضي. + +## الشرح + +مثال من العالم الواقعي + +> فريق يعمل على لعبة جديدة حيث يتقاتل السحرة مع بعضهم البعض. يحتاج سلوك السحرة إلى تعديل دقيق وتجربة مئات المرات من خلال اختبارات اللعبة. ليس من المثالي أن يطلب من المبرمج إجراء تغييرات في كل مرة يريد فيها مصمم اللعبة تعديل السلوك، لذلك يتم تنفيذ سلوك الساحر كجهاز افتراضي يعتمد على البيانات. + +بكلمات بسيطة + +> نمط Bytecode يسمح بسلوك موجه بالبيانات بدلاً من الكود. + +[Gameprogrammingpatterns.com](https://gameprogrammingpatterns.com/bytecode.html) يوضح الوثائق: + +> مجموعة من التعليمات تحدد العمليات منخفضة المستوى التي يمكن تنفيذها. يتم ترميز سلسلة من التعليمات كدورة من البايتات. يقوم الجهاز الافتراضي بتنفيذ هذه التعليمات واحدة تلو الأخرى، باستخدام مكدس للقيم الوسيطة. يسمح الجمع بين التعليمات بتعريف سلوكيات معقدة وعالية المستوى. + +**مثال برمجي** + +أحد الكائنات الأكثر أهمية في اللعبة هو فئة ماغو `Wizard`. + + +```java + +@AllArgsConstructor +@Setter +@Getter +@Slf4j +public class Wizard { + + private int health; + private int agility; + private int wisdom; + private int numberOfPlayedSounds; + private int numberOfSpawnedParticles; + + public void playSound() { + LOGGER.info("Playing sound"); + numberOfPlayedSounds++; + } + + public void spawnParticles() { + LOGGER.info("Spawning particles"); + numberOfSpawnedParticles++; + } +} +``` + +بعد ذلك، نعرض التعليمات المتاحة لجهازنا الافتراضي. لكل تعليمات دلالتها الخاصة حول كيفية التعامل مع بيانات المكدس. على سبيل المثال، تقوم التعليمة ADD بأخذ العنصرين العلويين من المكدس، وتجمعهما، ثم تضع النتيجة في المكدس. + + +```java + +@AllArgsConstructor +@Getter +public enum Instruction { + + LITERAL(1), // e.g. "LITERAL 0", push 0 to stack + SET_HEALTH(2), // e.g. "SET_HEALTH", pop health and wizard number, call set health + SET_WISDOM(3), // e.g. "SET_WISDOM", pop wisdom and wizard number, call set wisdom + SET_AGILITY(4), // e.g. "SET_AGILITY", pop agility and wizard number, call set agility + PLAY_SOUND(5), // e.g. "PLAY_SOUND", pop value as wizard number, call play sound + SPAWN_PARTICLES(6), // e.g. "SPAWN_PARTICLES", pop value as wizard number, call spawn particles + GET_HEALTH(7), // e.g. "GET_HEALTH", pop value as wizard number, push wizard's health + GET_AGILITY(8), // e.g. "GET_AGILITY", pop value as wizard number, push wizard's agility + GET_WISDOM(9), // e.g. "GET_WISDOM", pop value as wizard number, push wizard's wisdom + ADD(10), // e.g. "ADD", pop 2 values, push their sum + DIVIDE(11); // e.g. "DIVIDE", pop 2 values, push their division + // ... +} +``` + +في قلب مثالنا توجد فئة `VirtualMachine`. تأخذ التعليمات كمدخلات وتنفذها لتوفير سلوك كائن اللعبة. + + +```java + +@Getter +@Slf4j +public class VirtualMachine { + + private final Stack stack = new Stack<>(); + + private final Wizard[] wizards = new Wizard[2]; + + public VirtualMachine() { + wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), + 0, 0); + wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), + 0, 0); + } + + public VirtualMachine(Wizard wizard1, Wizard wizard2) { + wizards[0] = wizard1; + wizards[1] = wizard2; + } + + public void execute(int[] bytecode) { + for (var i = 0; i < bytecode.length; i++) { + Instruction instruction = Instruction.getInstruction(bytecode[i]); + switch (instruction) { + case LITERAL: + // Read the next byte from the bytecode. + int value = bytecode[++i]; + // Push the next value to stack + stack.push(value); + break; + case SET_AGILITY: + var amount = stack.pop(); + var wizard = stack.pop(); + setAgility(wizard, amount); + break; + case SET_WISDOM: + amount = stack.pop(); + wizard = stack.pop(); + setWisdom(wizard, amount); + break; + case SET_HEALTH: + amount = stack.pop(); + wizard = stack.pop(); + setHealth(wizard, amount); + break; + case GET_HEALTH: + wizard = stack.pop(); + stack.push(getHealth(wizard)); + break; + case GET_AGILITY: + wizard = stack.pop(); + stack.push(getAgility(wizard)); + break; + case GET_WISDOM: + wizard = stack.pop(); + stack.push(getWisdom(wizard)); + break; + case ADD: + var a = stack.pop(); + var b = stack.pop(); + stack.push(a + b); + break; + case DIVIDE: + a = stack.pop(); + b = stack.pop(); + stack.push(b / a); + break; + case PLAY_SOUND: + wizard = stack.pop(); + getWizards()[wizard].playSound(); + break; + case SPAWN_PARTICLES: + wizard = stack.pop(); + getWizards()[wizard].spawnParticles(); + break; + default: + throw new IllegalArgumentException("Invalid instruction value"); + } + LOGGER.info("Executed " + instruction.name() + ", Stack contains " + getStack()); + } + } + + public void setHealth(int wizard, int amount) { + wizards[wizard].setHealth(amount); + } + // other setters -> + // ... +} +``` + +الآن يمكننا عرض المثال الكامل باستخدام الآلة الافتراضية. + +```java + public static void main(String[]args){ + + var vm=new VirtualMachine( + new Wizard(45,7,11,0,0), + new Wizard(36,18,8,0,0)); + + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_HEALTH")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_AGILITY")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_WISDOM")); + vm.execute(InstructionConverterUtil.convertToByteCode("ADD")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 2")); + vm.execute(InstructionConverterUtil.convertToByteCode("DIVIDE")); + vm.execute(InstructionConverterUtil.convertToByteCode("ADD")); + vm.execute(InstructionConverterUtil.convertToByteCode("SET_HEALTH")); + } +``` + +إليك مخرجات وحدة التحكم. + + +``` +16:20:10.193 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0] +16:20:10.196 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_HEALTH, Stack contains [0, 45] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_AGILITY, Stack contains [0, 45, 7] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 7, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_WISDOM, Stack contains [0, 45, 7, 11] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 45, 18] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 18, 2] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed DIVIDE, Stack contains [0, 45, 9] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 54] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed SET_HEALTH, Stack contains [] +``` + +## مخطط الفئات + + +![alt text](./etc/bytecode.urm.png "Bytecode class diagram") + +## القابلية للتطبيق + + +## القابلية للتطبيق + +استخدم نمط Bytecode عندما تحتاج إلى تعريف العديد من السلوكيات ولغة تنفيذ لعبتك ليست مناسبة لأن: + +* إنها منخفضة المستوى جدًا، مما يجعل البرمجة مملة أو عرضة للأخطاء. +* التكرار فيها يستغرق وقتًا طويلًا بسبب بطء وقت الترجمة أو مشاكل أخرى في الأدوات. +* إنها تحتوي على ثقة مفرطة. إذا كنت ترغب في التأكد من أن السلوك المحدد لا يمكن أن يتسبب في كسر اللعبة، يجب أن تفصله عن باقي قاعدة الكود. + +## الاستخدامات المعروفة + +* تستخدم Java Virtual Machine (JVM) bytecode لتمكين برامج Java من العمل على أي جهاز يحتوي على JVM. +* تقوم Python بترجمة سكربتاتها إلى bytecode، الذي يتم تفسيره بعد ذلك بواسطة آلة افتراضية Python. +* يستخدم .NET Framework نوعًا من bytecode يسمى Microsoft Intermediate Language (MSIL). + +## العواقب + +### المزايا: + +* القابلية للنقل: يمكن تنفيذ البرامج على أي منصة تحتوي على آلة افتراضية متوافقة. +* الأمان: يمكن للآلة الافتراضية تطبيق ضوابط أمان على كود البايت. +* الأداء: يمكن للمترجمات JIT تحسين كود البايت في وقت التشغيل، مما يحسن الأداء المحتمل مقارنة بالكود المفسر. + +### العيوب: + +* الحمل الزائد: تنفيذ bytecode يتضمن عادةً مزيدًا من الحمل الزائد مقارنةً بتنفيذ الكود الأصلي، مما قد يؤثر على الأداء. +* التعقيد: تنفيذ وصيانة آلة افتراضية يضيف تعقيدًا للنظام. + +## الأنماط المرتبطة + +* [مترجم](https://java-design-patterns.com/patterns/interpreter/) يستخدم غالبًا داخل تنفيذ آلات افتراضية لتفسير تعليمات bytecode. +* [أمر](https://java-design-patterns.com/patterns/command/): يمكن اعتبار تعليمات bytecode أوامر يتم تنفيذها بواسطة الآلة الافتراضية. +* [طريقة المصنع](https://java-design-patterns.com/patterns/factory-method/): قد تستخدم الآلات الافتراضية طرق المصنع لإنشاء العمليات أو التعليمات المحددة في bytecode. + +## الشكر + +* [أنماط برمجة الألعاب](http://gameprogrammingpatterns.com/bytecode.html) +* [برمجة لغات البرمجة](https://amzn.to/49Tusnn) diff --git a/localization/ar/bytecode/etc/bytecode.urm.png b/localization/ar/bytecode/etc/bytecode.urm.png new file mode 100644 index 000000000000..51335fa0a4b4 Binary files /dev/null and b/localization/ar/bytecode/etc/bytecode.urm.png differ diff --git a/localization/ar/chain-of-responsibility/README.md b/localization/ar/chain-of-responsibility/README.md new file mode 100644 index 000000000000..f3cc1a2f3b20 --- /dev/null +++ b/localization/ar/chain-of-responsibility/README.md @@ -0,0 +1,207 @@ +--- +title: Chain of responsibility +shortTitle: Chain of responsibility +category: Behavioral +language: ar +tag: + - Gang of Four + - Decoupling +--- + +## أيضًا معروف بـ + +* سلسلة الأوامر +* سلسلة الكائنات +* سلسلة المسؤولية + +## الغرض + +يمنع ربط مُرسل الطلب بمستقبله من خلال إعطاء أكثر من كائن الفرصة لإدارة الطلب. يربط الكائنات المستقبلية معًا ويمرر الطلب عبر السلسلة حتى يتمكن أحد الكائنات من معالجته. + +## الشرح + +مثال من الحياة الواقعية + +> الملك الأورك يعطي أوامر بصوت عالٍ لجيشه. أقرب شخص للرد هو القائد، ثم الضابط، ثم الجندي. القائد، الضابط، والجندي يشكلون سلسلة من المسؤولية. + +بكلمات بسيطة + +> يساعد في بناء سلسلة من الكائنات. يدخل الطلب من طرف ويتنقل عبر كائنات متعددة حتى يجد مديرًا مناسبًا. + +تقول ويكيبيديا + +> في التصميم الموجه للكائنات، نمط سلسلة المسؤولية هو نمط تصميم يتكون من مصدر لأوامر الكائنات وسلسلة من كائنات المعالجة. يحتوي كل كائن معالجة على منطق يحدد أنواع أوامر الكائنات التي يمكنه التعامل معها؛ يتم تمرير البقية إلى كائن المعالجة التالي في السلسلة. + +**مثال برمجي** + +ترجمة لمثالنا مع الأورك أعلاه. أولًا، لدينا الكلاس `Request`: + + +```java +import lombok.Getter; + +@Getter +public class Request { + + private final RequestType requestType; + private final String requestDescription; + private boolean handled; + + public Request(final RequestType requestType, final String requestDescription) { + this.requestType = Objects.requireNonNull(requestType); + this.requestDescription = Objects.requireNonNull(requestDescription); + } + + public void markHandled() { + this.handled = true; + } + + @Override + public String toString() { + return getRequestDescription(); + } +} + +public enum RequestType { + DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX +} +``` + +أدناه، نعرض تسلسل هرم مدير الطلبات. + + +```java +public interface RequestHandler { + + boolean canHandleRequest(Request req); + + int getPriority(); + + void handle(Request req); + + String name(); +} + +@Slf4j +public class OrcCommander implements RequestHandler { + @Override + public boolean canHandleRequest(Request req) { + return req.getRequestType() == RequestType.DEFEND_CASTLE; + } + + @Override + public int getPriority() { + return 2; + } + + @Override + public void handle(Request req) { + req.markHandled(); + LOGGER.info("{} handling request \"{}\"", name(), req); + } + + @Override + public String name() { + return "Orc commander"; + } +} + +// يتم تعريف OrcOfficer و OrcSoldier بطريقة مشابهة لـ OrcCommander + + +``` + +الملك أورك يعطي الأوامر ويشكل السلسلة. + + +```java +public class OrcKing { + + private List handlers; + + public OrcKing() { + buildChain(); + } + + private void buildChain() { + handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier()); + } + + public void makeRequest(Request req) { + handlers + .stream() + .sorted(Comparator.comparing(RequestHandler::getPriority)) + .filter(handler -> handler.canHandleRequest(req)) + .findFirst() + .ifPresent(handler -> handler.handle(req)); + } +} +``` + +سلسلة المسؤولية في العمل. + + +```java +var king=new OrcKing(); + king.makeRequest(new Request(RequestType.DEFEND_CASTLE,"defend castle")); + king.makeRequest(new Request(RequestType.TORTURE_PRISONER,"torture prisoner")); + king.makeRequest(new Request(RequestType.COLLECT_TAX,"collect tax")); +``` + +إخراج وحدة التحكم. + + +``` +Orc commander handling request "defend castle" +Orc officer handling request "torture prisoner" +Orc soldier handling request "collect tax" +``` + +## مخطط الفئات + +![alt text](./etc/chain-of-responsibility.urm.png "مخطط الفئات لسلسلة المسؤولية") + +## التطبيقية + +استخدم سلسلة المسؤولية عندما + +* يمكن لعدة كائنات معالجة الطلب، ولا يتم التعرف على المعالج مسبقًا. يجب تحديد المعالج تلقائيًا. +* ترغب في إرسال طلب إلى أحد الكائنات دون تحديد المستقبل بشكل صريح. +* يجب تحديد مجموعة الكائنات التي يمكنها معالجة الطلب ديناميكيًا. + +## الاستخدامات المعروفة + +* التفاعل مع الأحداث في إطارات واجهات المستخدم الرسومية حيث يمكن معالجة الحدث في عدة مستويات من تسلسل مكونات واجهة المستخدم. +* إطارات عمل الوسطاء حيث يمر الطلب عبر سلسلة من كائنات المعالجة. +* أنظمة السجلات حيث يمكن أن تمر الرسائل عبر سلسلة من المسجلين، مع إمكانية معالجتها بطرق مختلفة. +* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) +* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) +* [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-) + +## العواقب + +المزايا: + +* تقليل الترابط. لا يحتاج مُرسل الطلب إلى معرفة المعالج المحدد الذي سيعالج الطلب. +* مرونة أكبر في تخصيص المسؤوليات للكائنات. يمكن إضافة أو تغيير المسؤوليات لإدارة الطلب عن طريق تغيير أعضاء وترتيب السلسلة. +* يتيح تعيين معالج افتراضي إذا لم يكن هناك معالج محدد يمكنه معالجة الطلب. + +العيوب: + +* قد يكون من الصعب تصحيح الأخطاء وفهم التدفق، خاصة إذا كانت السلسلة طويلة ومعقدة. +* قد يبقى الطلب دون معالجة إذا كانت السلسلة لا تحتوي على معالج "التقاط الكل". +* قد تنشأ مشكلات في الأداء بسبب إمكانية مرور الطلب عبر عدة معالجات قبل العثور على المعالج المناسب، أو عدم العثور عليه على الإطلاق. + +## الأنماط ذات الصلة + +* [الأمر](https://java-design-patterns.com/patterns/command/): يمكن استخدامه لتغليف طلب ككائن، يمكن تمريره عبر السلسلة. +* [التركيب](https://java-design-patterns.com/patterns/composite/): غالبًا ما يتم تطبيق نمط سلسلة المسؤولية مع نمط التركيب. +* [الزخرفة](https://java-design-patterns.com/patterns/decorator/): يمكن ربط الزخارف بشكل مشابه للمسؤوليات في نمط سلسلة المسؤولية. + +## الاعتمادات + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3PAJUg5) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) +* [Pattern languages of program design 3](https://amzn.to/4a4NxTH) diff --git a/localization/ar/chain-of-responsibility/etc/chain-of-responsibility.urm.png b/localization/ar/chain-of-responsibility/etc/chain-of-responsibility.urm.png new file mode 100644 index 000000000000..af1bd105455b Binary files /dev/null and b/localization/ar/chain-of-responsibility/etc/chain-of-responsibility.urm.png differ diff --git a/localization/ar/client-session/README.md b/localization/ar/client-session/README.md new file mode 100644 index 000000000000..a6892e80b239 --- /dev/null +++ b/localization/ar/client-session/README.md @@ -0,0 +1,118 @@ +--- +title: Client Session +shortTitle: Client Session +category: Behavioral +language: ar +tags: + - Session management + - Web development +--- + +## أيضًا معروف باسم + +* جلسة المستخدم + +## الهدف + +يهدف نمط التصميم "جلسة العميل" إلى الحفاظ على حالة وبيانات المستخدم عبر طلبات متعددة ضمن تطبيق ويب، مما يضمن تجربة مستخدم مستمرة وشخصية. + +## الشرح + +مثال واقعي + +> ترغب في إنشاء تطبيق لإدارة البيانات يسمح للمستخدمين بإرسال طلبات إلى الخادم لتعديل وإجراء تغييرات على البيانات المخزنة على أجهزتهم. هذه الطلبات صغيرة والبيانات فردية لكل مستخدم، مما يلغي الحاجة إلى تنفيذ قاعدة بيانات واسعة النطاق. باستخدام نمط جلسة العميل، يمكن إدارة عدة طلبات في نفس الوقت، مع تحقيق توازن في تحميل العملاء عبر خوادم مختلفة بسهولة لأن الخوادم تظل بدون حالة. كما يتم القضاء على الحاجة إلى تخزين معرفات الجلسة على الخادم لأن العملاء يقدمون كل المعلومات التي يحتاجها الخادم لمعالجة طلباتهم. + +بإيجاز + +> بدلاً من تخزين معلومات عن العميل الحالي والمعلومات التي يتم الوصول إليها على الخادم، يتم الاحتفاظ بها فقط على جانب العميل. يجب على العميل إرسال بيانات الجلسة مع كل طلب إلى الخادم ويجب عليه إرسال حالة محدثة مرة أخرى إلى العميل، التي يتم تخزينها على جهاز العميل. لا يتعين على الخادم تخزين معلومات العميل. ([مرجع](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client)) + +**مثال برمجي** + +إليك كود مثال لوصف نمط جلسة العميل. في الكود التالي، نقوم أولاً بإنشاء مثيل للخادم. سيتم استخدام هذا المثيل بعد ذلك للحصول على كائنات الجلسة لعميلين. كما ترى في الكود التالي، يمكن استخدام كائن الجلسة لتخزين أي معلومات ذات صلة يحتاجها الخادم لمعالجة طلب العميل. سيتم تمرير هذه الكائنات مع كل طلب إلى الخادم. سيتضمن الطلب كائن الجلسة الذي يخزن التفاصيل ذات الصلة بالعميل مع البيانات المطلوبة لمعالجة الطلب. تساعد معلومات الجلسة في كل طلب الخادم في التعرف على العميل ومعالجة الطلب بناءً على ذلك. + + +```java +public class App { + + public static void main(String[] args) { + var server = new Server("localhost", 8080); + var session1 = server.getSession("Session1"); + var session2 = server.getSession("Session2"); + var request1 = new Request("Data1", session1); + var request2 = new Request("Data2", session2); + server.process(request1); + server.process(request2); + } +} + +@Data +@AllArgsConstructor +public class Session { + + /** + * Session id. + */ + private String id; + + /** + * Client name. + */ + private String clientName; + +} + +@Data +@AllArgsConstructor +public class Request { + + private String data; + + private Session session; + +} +``` + +## مخطط الهيكلية + +![alt text](./etc/session_state_pattern.png "نمط حالة الجلسة") + +## قابلية التطبيق + +استخدم نمط حالة الجلسة عندما: + +* التطبيقات الويب التي تتطلب مصادقة وتفويض المستخدم. +* التطبيقات التي تحتاج إلى تتبع أنشطة وتفضيلات المستخدم عبر طلبات أو زيارات متعددة. +* الأنظمة التي يحتاج فيها موارد الخادم إلى التحسين عن طريق تحميل إدارة الحالة إلى جانب العميل. + +## الاستخدامات المعروفة + +* مواقع التجارة الإلكترونية لتتبع محتويات سلة التسوق عبر الجلسات. +* المنصات عبر الإنترنت التي تقدم محتوى مخصص بناءً على تفضيلات وسجل المستخدم. +* تطبيقات الويب التي تتطلب تسجيل دخول المستخدم للوصول إلى المحتوى المخصص أو الآمن. + +## العواقب + +الفوائد: + +* تحسين أداء الخادم من خلال تقليل الحاجة لتخزين حالة المستخدم على الخادم. +* تحسين تجربة المستخدم من خلال المحتوى المخصص والتنقل السلس عبر أجزاء التطبيق المختلفة. +* مرونة في إدارة الجلسات من خلال عدة آليات تخزين على جانب العميل (مثل الكوكيز، Web Storage API). + +العيوب: + +* مخاطر محتملة للأمان إذا تم تخزين معلومات حساسة في جلسات العميل دون التشفير والتحقق المناسب. +* الاعتماد على قدرات وضبط العميل، مثل سياسات الكوكيز التي قد تختلف حسب المتصفح وإعدادات المستخدم. +* زيادة التعقيد في منطق إدارة الجلسات، خاصة في إدارة انتهاء الصلاحية، التجديد ومزامنة الجلسات عبر الأجهزة أو النوافذ المتعددة. + +## الأنماط ذات الصلة + +* جلسة الخادم: غالباً ما يُستخدم جنباً إلى جنب مع نمط جلسة العميل لتوفير توازن بين كفاءة جانب العميل والتحكم في جانب الخادم. +* [سينجلتون](https://java-design-patterns.com/patterns/singleton/): ضمان وجود مثيل واحد فقط من جلسة المستخدم في التطبيق بأكمله. +* [حالة](https://java-design-patterns.com/patterns/state/): إدارة تحولات الحالة في الجلسة مثل الحالات المصادق عليها، الضيف أو المنتهية. + +## الفضل + +* [DZone - Practical PHP patterns](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client) +* [نمط حالة جلسة العميل - Ram N Java](https://www.youtube.com/watch?v=ycOSj9g41pc) +* [Java الاحترافي لتطبيقات الويب](https://amzn.to/4aazY59) +* [تأمين تطبيقات الويب باستخدام Spring Security](https://amzn.to/3PCCEA1) diff --git a/localization/ar/client-session/etc/session_state_pattern.png b/localization/ar/client-session/etc/session_state_pattern.png new file mode 100644 index 000000000000..f1e23be95766 Binary files /dev/null and b/localization/ar/client-session/etc/session_state_pattern.png differ diff --git a/localization/ar/collecting-parameter/README.md b/localization/ar/collecting-parameter/README.md new file mode 100644 index 000000000000..c799bb0223de --- /dev/null +++ b/localization/ar/collecting-parameter/README.md @@ -0,0 +1,222 @@ +--- +title: Collecting Parameter +shortTitle: Collecting Parameter +category: Behavioral +language: ar +tag: + - Accumulation + - Generic +--- + +## أيضًا يُعرف بـ + +* جامع +* مُجمّع + +## الهدف + +يهدف إلى تبسيط الطرق التي تجمع المعلومات من خلال تمرير كائن جمع واحد عبر عدة استدعاءات للطرق، مما يسمح لها بإضافة النتائج إلى هذه المجموعة بدلاً من أن يقوم كل طريقة بإنشاء مجموعة خاصة بها. + +## الشرح + +### مثال من العالم الحقيقي + +داخل مبنى تجاري كبير، توجد طابعات مُشتركة تعد مجموعة من جميع وظائف الطباعة المعلقة حاليًا. تحتوي الطوابق المختلفة على طرز مختلفة من الطابعات، ولكل منها سياسة طباعة مختلفة. يجب علينا بناء برنامج يمكنه إضافة مهام الطباعة المناسبة بشكل مستمر إلى مجموعة تسمى *معامل الجمع*. + +### ببساطة + +بدلاً من وجود دالة ضخمة تحتوي على العديد من السياسات لجمع المعلومات في متغير، يمكننا إنشاء العديد من الدوال الصغيرة التي تأخذ كل معلم، وتضيف معلومات جديدة. يمكننا تمرير المعامل إلى كل من هذه الدوال الصغيرة وفي النهاية، سيكون لدينا ما أردناه في الأصل. في هذه المرة، يكون الكود أنظف وأسهل في الفهم. نظرًا لأن الدالة الكبيرة قد تم تقسيمها، فإن الكود أيضًا أسهل في التعديل حيث يتم تحديد التغييرات في الدوال الصغيرة. + +### تقول ويكيبيديا + +في اصطلاح المعاملات الجامعية، يتم تمرير مجموعة (قائمة، خريطة، إلخ) بشكل متكرر كمعامل إلى دالة تضيف العناصر إلى المجموعة. + +### مثال برمجي + +بتشفير مثالنا السابق، يمكننا استخدام مجموعة `النتيجة` كمعامل جامع. يتم تنفيذ القيود التالية: + +- إذا كان ورق A4 ملونًا، يجب أن يكون أيضًا من جهة واحدة. يتم قبول جميع الأوراق غير الملونة الأخرى. +- لا يجب أن يكون ورق A3 ملونًا ويجب أن يكون من جهة واحدة. +- يجب أن يكون ورق A2 من صفحة واحدة، من جهة واحدة وغير ملون. + + +```java +package com.iluwatar.collectingparameter; + +import java.util.LinkedList; +import java.util.Queue; + +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + /* + Initialising the printer queue with jobs + */ + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A2, 5, false, false)); + + /* + This variable is the collecting parameter. + */ + var result = new LinkedList(); + + /* + * Using numerous sub-methods to collaboratively add information to the result collecting parameter + */ + addA4Papers(result); + addA3Papers(result); + addA2Papers(result); + } +} +``` + +نستخدم الطرق `addA4Paper` و `addA3Paper` و `addA2Paper` لملء معامل الجمع `النتيجة` بالوظائف المناسبة للطباعة وفقًا للسياسة الموصوفة سابقًا. يتم ترميز السياسات الثلاث كما يلي: + + +```java +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + + /** + * Adds A4 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA4Papers(Queue printerItemsCollection) { + /* + Iterate through the printer queue, and add A4 papers according to the correct policy to the collecting parameter, + which is 'printerItemsCollection' in this case. + */ + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A4)) { + var isColouredAndSingleSided = + nextItem.isColour && !nextItem.isDoubleSided; + if (isColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } else if (!nextItem.isColour) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A3 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate + * the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA3Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A3)) { + + // Encoding the policy into a Boolean: the A3 paper cannot be coloured and double-sided at the same time + var isNotColouredAndSingleSided = + !nextItem.isColour && !nextItem.isDoubleSided; + if (isNotColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A2 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate + * the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA2Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A2)) { + + // Encoding the policy into a Boolean: the A2 paper must be single page, single-sided, and non-coloured. + var isNotColouredSingleSidedAndOnePage = + nextItem.pageCount == 1 && + !nextItem.isDoubleSided + && !nextItem.isColour; + if (isNotColouredSingleSidedAndOnePage) { + printerItemsCollection.add(nextItem); + } + } + } + } +} +``` + +كل طريقة تأخذ كمعامل معلمة جمع. بعد ذلك، تضيف العناصر، المأخوذة من متغير عالمي، إلى هذه المعلمة إذا كانت كل عنصر يفي بمعيار معين. يمكن أن تحتوي هذه الطرق على السياسة التي يرغب فيها العميل. + +في هذا المثال البرمجي، يتم إضافة ثلاث مهام طباعة إلى الطابور. فقط أول مهمتين للطباعة يجب إضافتهما إلى معلمة الجمع وفقًا للسياسة. العناصر في متغير `النتيجة` بعد التنفيذ هي: + +| حجم الورق | عدد الصفحات | مزدوج الوجه | ملون | +|-----------|-------------|-------------|------| +| A4 | 5 | false | false | +| A3 | 2 | false | false | + +وهذا هو ما توقعناه. + +## مخطط الفئات + +![alt text](./etc/collecting-parameter.urm.png "معامل الجمع") + +## قابلية التطبيق + +استخدم نمط التصميم جمع المعاملات عندما: + +- عندما تنتج عدة طرق مجموعة من النتائج وتريد إضافة هذه النتائج بطريقة موحدة. +- في السيناريوهات حيث يمكن أن يحسن تقليل عدد المجموعات التي يتم إنشاؤها بواسطة الطرق من كفاءة الذاكرة والأداء. +- عند إعادة هيكلة الطرق الكبيرة التي تقوم بعدة مهام، بما في ذلك جمع النتائج من عمليات متعددة. + +## الدروس التعليمية + +الدروس التعليمية لهذه الطريقة موجودة في: + +- [Refactoring To Patterns](http://www.tarrani.net/RefactoringToPatterns.pdf) بواسطة Joshua Kerivsky +- [Smalltalk Best Practice Patterns](https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf) بواسطة Kent Beck + +## الاستخدامات المعروفة + +يوضح Joshua Kerivsky مثالًا واقعيًا في كتابه 'Refactoring to Patterns'. يقدم مثالًا لاستخدام نمط التصميم "جمع المعاملات" لإنشاء طريقة `toString()` لشجرة XML. بدون استخدام هذا النمط، سيحتاج ذلك إلى وظيفة ضخمة تحتوي على شروط ودمج النصوص مما سيزيد من صعوبة قراءة الشيفرة. يمكن تقسيم مثل هذه الطريقة إلى طرق أصغر، حيث يضيف كل منها مجموعة خاصة من المعلومات إلى معلمة الجمع. انظر إلى هذا في [Refactoring To Patterns](http://www.tarrani.net/RefactoringToPatterns.pdf). + +أمثلة أخرى هي: + +- إضافة رسائل الخطأ أو فشل التحقق في عملية تحقق معقدة. +- جمع العناصر أو المعلومات أثناء التنقل في هيكل بيانات معقد. +- إعادة هيكلة الوظائف المعقدة للتقارير حيث يتم إنشاء أجزاء متعددة من التقرير باستخدام طرق مختلفة. + +## العواقب + +المزايا: + +- يقلل من تكرار الشيفرة من خلال تجميع معالجة المجموعات في مكان واحد. +- يحسن الوضوح وقابلية الصيانة من خلال توضيح مكان وكيفية جمع النتائج. +- يحسن الأداء عن طريق تقليل إنشاء وإدارة كائنات جمع متعددة. + +العيوب: + +- يزيد من الترابط بين المنادي والطرق المنادى عليها، حيث يجب أن يتفقوا على المجموعة المستخدمة. +- قد يقدم آثار جانبية في الطرق إذا لم تتم إدارتها بعناية، حيث لم تعد الطرق مستقلة في إدارة النتائج. + +## الأنماط ذات الصلة + +- [Composite](https://java-design-patterns.com/patterns/composite/): يمكن استخدامه مع جمع المعاملات عند العمل مع الهياكل الهرمية، مما يسمح بجمع النتائج عبر هيكل مركب. +- [Visitor](https://java-design-patterns.com/patterns/visitor/): يستخدم غالبًا معًا، حيث يتولى Visitor المرور وإجراء العمليات في هيكل، بينما يقوم جمع المعاملات بتراكم النتائج. +- [Command](https://java-design-patterns.com/patterns/command/): يمكن للأوامر استخدام معلمة الجمع لإضافة نتائج عدة عمليات يتم تنفيذها بواسطة كائنات الأمر. + +## الشكر + +- [Refactoring To Patterns](http://www.tarrani.net/RefactoringToPatterns.pdf) بواسطة Joshua Kerivsky +- [Smalltalk Best Practice Patterns](https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf) بواسطة Kent Beck +- [Wiki](https://wiki.c2.com/?CollectingParameter) +- [Refactoring: Improving the Design of Existing Code](https://amzn.to/3TVEgaB) +- [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/4aApLP0) diff --git a/localization/ar/collecting-parameter/etc/collecting-parameter.urm.png b/localization/ar/collecting-parameter/etc/collecting-parameter.urm.png new file mode 100644 index 000000000000..785d6ecc2da1 Binary files /dev/null and b/localization/ar/collecting-parameter/etc/collecting-parameter.urm.png differ diff --git a/localization/ar/command/README.md b/localization/ar/command/README.md new file mode 100644 index 000000000000..af20644ab502 --- /dev/null +++ b/localization/ar/command/README.md @@ -0,0 +1,245 @@ +--- +title: Command +shortTitle: Command +category: Behavioral +language: ar +tag: + - Gang of Four +--- + +## أيضًا يعرف بـ + +* إجراء +* معاملة + +## الهدف + +يُغلف نمط التصميم Command الطلب ككائن، مما يسمح بتمرير العملاء مع قوائم الانتظار، الطلبات، والعمليات. كما يدعم أيضًا التراجع عن العمليات. + +## الشرح + +### مثال واقعي + +> يوجد ساحر يلقي تعويذات على عفريت. يتم تنفيذ التعويذات على العفريت واحدة تلو الأخرى. التعويذة الأولى تصغر العفريت والتعويذة الثانية تجعله غير مرئي. بعد ذلك، يقوم الساحر بالتراجع عن التعويذات واحدة تلو الأخرى. كل تعويذة هي كائن أمر يمكن التراجع عنها. + +### بكلمات بسيطة: + +> تخزين الطلبات ككائنات أمر يسمح بتنفيذ الإجراء أو التراجع عنه في وقت لاحق. + +### تقول ويكيبيديا: + +> في البرمجة الكائنية التوجه، نمط الأمر هو نمط تصميم سلوكي حيث يتم استخدام كائن لتغليف كافة المعلومات اللازمة لتنفيذ إجراء أو تحفيز حدث في وقت لاحق. + +### مثال برمجي + +إليك الكود البرمجي مع الساحر `Wizard` والعفريت `Goblin`. دعونا نبدأ بفئة الساحر `Wizard`. + + +```java + +@Slf4j +public class Wizard { + + private final Deque undoStack = new LinkedList<>(); + private final Deque redoStack = new LinkedList<>(); + + public Wizard() { + } + + public void castSpell(Runnable runnable) { + runnable.run(); + undoStack.offerLast(runnable); + } + + public void undoLastSpell() { + if (!undoStack.isEmpty()) { + var previousSpell = undoStack.pollLast(); + redoStack.offerLast(previousSpell); + previousSpell.run(); + } + } + + public void redoLastSpell() { + if (!redoStack.isEmpty()) { + var previousSpell = redoStack.pollLast(); + undoStack.offerLast(previousSpell); + previousSpell.run(); + } + } + + @Override + public String toString() { + return "Wizard"; + } +} +``` + +### التالي، لدينا العفريت `Goblin` الذي هو الهدف `Target` للتعويذات. + + +```java + +@Slf4j +public abstract class Target { + + private Size size; + + private Visibility visibility; + + public Size getSize() { + return size; + } + + public void setSize(Size size) { + this.size = size; + } + + public Visibility getVisibility() { + return visibility; + } + + public void setVisibility(Visibility visibility) { + this.visibility = visibility; + } + + @Override + public abstract String toString(); + + public void printStatus() { + LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); + } +} + +public class Goblin extends Target { + + public Goblin() { + setSize(Size.NORMAL); + setVisibility(Visibility.VISIBLE); + } + + @Override + public String toString() { + return "Goblin"; + } + + public void changeSize() { + var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL; + setSize(oldSize); + } + + public void changeVisibility() { + var visible = getVisibility() == Visibility.INVISIBLE + ? Visibility.VISIBLE : Visibility.INVISIBLE; + setVisibility(visible); + } +} +``` + +### أخيرًا، لدينا الساحر في الدالة الرئيسية وهو يلقي التعويذات. + + +```java +public static void main(String[]args){ + var wizard=new Wizard(); + var goblin=new Goblin(); + + // casts shrink/unshrink spell + wizard.castSpell(goblin::changeSize); + + // casts visible/invisible spell + wizard.castSpell(goblin::changeVisibility); + + // undo and redo casts + wizard.undoLastSpell(); + wizard.redoLastSpell(); +``` + +### هذا هو المثال قيد التنفيذ. + + +```java +var wizard=new Wizard(); + var goblin=new Goblin(); + + goblin.printStatus(); + wizard.castSpell(goblin::changeSize); + goblin.printStatus(); + + wizard.castSpell(goblin::changeVisibility); + goblin.printStatus(); + + wizard.undoLastSpell(); + goblin.printStatus(); + + wizard.undoLastSpell(); + goblin.printStatus(); + + wizard.redoLastSpell(); + goblin.printStatus(); + + wizard.redoLastSpell(); + goblin.printStatus(); +``` + +### إليك مخرجات البرنامج: + + +```java +Goblin,[size=normal][visibility=visible] + Goblin,[size=small][visibility=visible] + Goblin,[size=small][visibility=invisible] + Goblin,[size=small][visibility=visible] + Goblin,[size=normal][visibility=visible] + Goblin,[size=small][visibility=visible] + Goblin,[size=small][visibility=invisible] +``` + +## تطبيق + +استخدم نمط الأمر (Command) في الحالات التالية: + +* لتحديد كائنات باستخدام إجراء لتنفيذه. يمكنك التعبير عن هذه التحديدات باستخدام لغة إجراء مع دالة رد اتصال، أي دالة يتم تسجيلها في مكان ما ليتم استدعاؤها في وقت لاحق. الأوامر هي بديل موجه للكائنات لردود الاتصال. +* لتحديد، وضع في طابور وتنفيذ الطلبات في أوقات مختلفة. يمكن أن يكون لكائن الأمر حياة مستقلة عن الطلب الأصلي. إذا كان يمكن تمثيل مستلم الطلب بطريقة مستقلة عن مساحة العناوين، فيمكنك نقل كائن الأمر للطلب إلى عملية مختلفة وتنفيذ الطلب هناك. +* دعم الإلغاء. يمكن لعملية تنفيذ الأمر تخزين الحالة لإلغاء تأثيراتها في نفس الأمر. يجب أن تحتوي واجهة الأمر على عملية إضافية لإلغاء التنفيذ التي تعيد تأثيرات استدعاء سابق لتنفيذ. يتم تخزين الأوامر التي تم تنفيذها في قائمة تاريخ. يمكن تحقيق وظيفة التراجع وإعادة التنفيذ بشكل غير محدود من خلال استعراض هذه القائمة للأمام والخلف عن طريق استدعاء إلغاء التنفيذ والتنفيذ، على التوالي. +* دعم تسجيل التغييرات بحيث يمكن تطبيقها مرة أخرى في حال حدوث عطل في النظام. من خلال إضافة عمليات تحميل وتخزين إلى واجهة الأوامر، يمكنك الاحتفاظ بسجل مستمر للتغييرات. يتطلب استعادة العطل إعادة تحميل الأوامر المسجلة من القرص وتنفيذها مرة أخرى باستخدام عملية التنفيذ. +* هيكلة النظام حول عمليات عالية المستوى مبنية على عمليات بدائية. هذه الهيكلة شائعة في أنظمة المعلومات التي تدعم المعاملات. المعاملة تحتوي على مجموعة من التغييرات في البيانات. يوفر نمط الأمر طريقة لنمذجة المعاملات. تحتوي الأوامر على واجهة مشتركة تسمح باستدعاء جميع المعاملات بنفس الطريقة. كما يسهل النمط توسيع النظام مع معاملات جديدة. +* الحفاظ على سجل من الطلبات. +* تنفيذ وظيفة رد الاتصال. +* تنفيذ وظيفة التراجع. + +## الاستخدامات المعروفة + +* الأزرار في واجهة المستخدم الرسومية وعناصر القائمة في تطبيقات سطح المكتب. +* العمليات في أنظمة قواعد البيانات والأنظمة المعاملاتية التي تدعم التراجع (rollback). +* تسجيل الماكرو في التطبيقات مثل محرري النصوص وجداول البيانات. +* [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) +* [org.junit.runners.model.Statement](https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/model/Statement.java) +* [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki) +* [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html) + +## العواقب + +المزايا: + +* يفصل الكائن الذي يستدعي العملية عن الكائن الذي يعرف كيفية تنفيذها. +* من السهل إضافة أوامر جديدة، لأنه لا يتعين عليك تغيير الفئات الموجودة. +* يمكنك تجميع مجموعة من الأوامر في أمر مركب. + +العيوب: + +* يزيد عدد الفئات لكل أمر فردي. +* قد يعقد التصميم عند إضافة طبقات متعددة بين المرسلين والمستلمين. + +## الأنماط ذات الصلة + +* [Composite](https://java-design-patterns.com/patterns/composite/): يمكن تجميع الأوامر باستخدام نمط المركب لإنشاء أوامر كبيرة. +* [Memento](https://java-design-patterns.com/patterns/memento/): يمكن استخدامه لتنفيذ آليات التراجع. +* [Observer](https://java-design-patterns.com/patterns/observer/): يمكن ملاحظة النمط لتغييرات التي تفعّل الأوامر. + +## المصادر + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3PFUqSY) diff --git a/localization/ar/command/etc/command.png b/localization/ar/command/etc/command.png new file mode 100644 index 000000000000..0f026464ecc4 Binary files /dev/null and b/localization/ar/command/etc/command.png differ diff --git a/localization/ar/commander/README.md b/localization/ar/commander/README.md new file mode 100644 index 000000000000..2cb0b72e17f1 --- /dev/null +++ b/localization/ar/commander/README.md @@ -0,0 +1,136 @@ +--- +title: Commander +shortTitle: Commander +category: Behavioral +language: ar +tag: + - Cloud distributed + - Microservices + - Transactions +--- + +## أيضا يُعرف باسم + +* منسق المعاملات الموزعة +* منسق المعاملات + +## الهدف + +الهدف من نمط "المنسق" في سياق المعاملات الموزعة هو إدارة وتنسيق المعاملات المعقدة عبر العديد من المكونات أو الخدمات الموزعة، مما يضمن التناسق والنزاهة للمعاملة العالمية. يقوم بتغليف أوامر المعاملات ومنطق التنسيق، مما يسهل تنفيذ بروتوكولات المعاملات الموزعة مثل الالتزام ذو المرحلتين أو ساغا. + +## الشرح + +مثال حقيقي + +> تخيل أنك تنظم مهرجان موسيقي دولي كبير، حيث من المقرر أن تؤدي عدة فرق من جميع أنحاء العالم. وصول كل فرقة، واختبار الصوت، والأداء، كل منها يعد معاملة فردية في نظام موزع. يتصرف منظم المهرجان كـ "منسق"، منسقًا هذه المعاملات لضمان أنه إذا تأخر طيران إحدى الفرق (مثل فشل المعاملة)، فهناك خطة احتياطية مثل إعادة جدولة أو تبادل الفترات الزمنية مع فرقة أخرى (إجراءات تعويضية)، للحفاظ على سير البرنامج العام. تعكس هذه الإعدادات نمط المنسق في المعاملات الموزعة، حيث يجب تنسيق العديد من المكونات لتحقيق نتيجة مرضية رغم الفشل الفردي. + +بكلمات بسيطة + +> يقوم نمط "المنسق" بتحويل الطلب إلى كائن مستقل، مما يسمح بمعلمة الأوامر، ووضع الإجراءات في طابور، وتنفيذ عمليات التراجع. + +**مثال برمجي** + +إدارة المعاملات عبر خدمات مختلفة في نظام موزع، مثل منصة للتجارة الإلكترونية تحتوي على خدمات منفصلة للدفع والشحن، تتطلب تنسيقًا دقيقًا لتجنب المشكلات. عندما يقدم المستخدم طلبًا ولكن خدمة واحدة (مثل الدفع) غير متوفرة بينما الخدمة الأخرى (مثل الشحن) جاهزة، نحتاج إلى حل قوي للتعامل مع هذا التفاوت. + +إحدى الاستراتيجيات لحل هذه المشكلة هي استخدام مكون منسق لتنظيم العملية. في البداية، تتم معالجة الطلب من قبل الخدمة المتاحة (الشحن في هذه الحالة). ثم يحاول المنسق مزامنة الطلب مع الخدمة غير المتوفرة في ذلك الوقت (الدفع) من خلال تخزين تفاصيل الطلب في قاعدة بيانات أو وضعه في طابور للمعالجة في المستقبل. يجب أن يأخذ هذا النظام في الحسبان الفشل المحتمل عند إضافة الطلبات إلى الطابور. + +يحاول المنسق بشكل متكرر معالجة الطلبات في الطابور لضمان أن تعكس جميع الخدمات أخيرًا نفس بيانات المعاملة. يتضمن هذا العملية ضمان التكرارية، مما يعني أنه حتى إذا تم إجراء نفس طلب مزامنة الطلبات عدة مرات، فسيتم تنفيذه مرة واحدة فقط، مما يمنع المعاملات المكررة. الهدف هو تحقيق التناسق النهائي بين الخدمات، حيث تتزامن جميع الأنظمة بمرور الوقت على الرغم من الفشل أو التأخير الأولي. + +في الكود المقدم، يُستخدم نمط المنسق لإدارة المعاملات الموزعة عبر العديد من الخدمات (خدمة الدفع، خدمة الشحن، خدمة الرسائل، إدارة الموظفين). كل خدمة تحتوي على قاعدة بيانات خاصة بها ويمكن أن تُطلق استثناءات لمحاكاة الفشل. + +فئة المنسق هي الجزء المركزي من هذا النمط. تأخذ الفئة المنسق مثيلات لجميع الخدمات وقواعد بياناتها، جنبًا إلى جنب مع بعض معلمات التكوين. تُستخدم دالة placeOrder في فئة المنسق لتنفيذ الطلب، مما يتطلب التفاعل مع جميع الخدمات. + + +```java +public class Commander { + // ... constructor and other methods ... + + public void placeOrder(Order order) { + // ... implementation ... + } +} +``` + +تمثل الفئات "المستخدم" و "الطلب" مستخدمًا وطلبًا على التوالي. يتم إجراء الطلب بواسطة المستخدم. + + +```java +public class User { + // ... constructor and other methods ... +} + +public class Order { + // ... constructor and other methods ... +} +``` + +كل خدمة (على سبيل المثال، خدمة الدفع، خدمة الشحن، خدمة الرسائل، إدارة الموظفين) لديها قاعدة بيانات خاصة بها ويمكن أن تُطلق استثناءات لمحاكاة الأعطال. على سبيل المثال، قد تقوم خدمة الدفع بإطلاق استثناء DatabaseUnavailableException إذا كانت قاعدة بياناتها غير متاحة. + + +```java +public class PaymentService { + // ... constructor and other methods ... +} +``` + +تمثل الفئات DatabaseUnavailableException و ItemUnavailableException و ShippingNotPossibleException أنواعًا مختلفة من الاستثناءات التي قد تحدث. + + +```java +public class DatabaseUnavailableException extends Exception { + // ... constructor and other methods ... +} + +public class ItemUnavailableException extends Exception { + // ... constructor and other methods ... +} + +public class ShippingNotPossibleException extends Exception { + // ... constructor and other methods ... +} +``` + +في الطريقة الرئيسية لكل فئة (AppQueueFailCases و AppShippingFailCases)، يتم محاكاة سيناريوهات مختلفة عن طريق إنشاء مثيلات من فئة Commander مع تكوينات مختلفة واستدعاء طريقة placeOrder. + +## مخطط الفئات + +![alt text](./etc/commander.urm.png "مخطط فئة Commander") + +## قابلية التطبيق + +استخدم نمط Commander للمعاملات الموزعة عندما: + +* تحتاج إلى ضمان اتساق البيانات بين الخدمات الموزعة في حالة حدوث فشل جزئي في النظام. +* تشمل المعاملات عدة خدمات ميكروسيرفيس أو مكونات موزعة تتطلب commit أو rollback منسق. +* تقوم بتنفيذ معاملات طويلة الأجل تتطلب إجراءات تعويضية للإلغاء. + +## الاستخدامات المعروفة + +* بروتوكولات Two-Phase Commit (2PC): التنسيق بين commit أو rollback عبر قواعد البيانات أو الخدمات الموزعة. +* تنفيذات نمط Saga: إدارة عمليات الأعمال طويلة الأجل التي تشمل العديد من الميكروسيرفيس، مع وجود إجراء تعويضي لكل خطوة للإلغاء. +* المعاملات الموزعة في بنية الميكروسيرفيس: تنسيق العمليات المعقدة بين الميكروسيرفيس مع الحفاظ على تكامل البيانات واتساقها. + +## العواقب + +الفوائد: + +* يوفر آلية واضحة لإدارة المعاملات الموزعة المعقدة، مما يحسن موثوقية النظام. +* يسمح بتنفيذ المعاملات التعويضية، وهي ضرورية للحفاظ على التناسق في المعاملات طويلة الأجل. +* يسهل دمج الأنظمة المتجانسة في سياق المعاملات. + +العيوب: + +* يزيد من التعقيد، خاصة في حالات الفشل، بسبب الحاجة إلى آليات التراجع المنسقة. +* قد يؤثر على الأداء بسبب الحمل الزائد للتنسيق وفحوصات التناسق. +* قد تؤدي التنفيذات المعتمدة على Saga إلى زيادة التعقيد في فهم سير العملية التجارية العامة. + +## الأنماط المرتبطة + +[Nمط Saga](https://java-design-patterns.com/patterns/saga/): غالبًا ما يتم مناقشته مع نمط Commander للمعاملات الموزعة، مع التركيز على المعاملات طويلة الأجل مع إجراءات تعويضية. + +## الشكر + +* [المعاملات الموزعة: جبال الجليد في الميكروسيرفيس](https://www.grahamlea.com/2016/08/distributed-transactions-microservices-icebergs/) +* [أنماط الميكروسيرفيس: مع أمثلة في جافا](https://amzn.to/4axjnYW) +* [تصميم التطبيقات المعتمدة على البيانات: الأفكار الكبيرة وراء الأنظمة القابلة للاعتماد، القابلة للتوسع، والقابلة للصيانة](https://amzn.to/4axHwOV) +* [أنماط تكامل المؤسسات: تصميم وبناء ونشر حلول الرسائل](https://amzn.to/4aATcRe) diff --git a/localization/ar/commander/etc/commander.urm.png b/localization/ar/commander/etc/commander.urm.png new file mode 100644 index 000000000000..6b5ebba75bd6 Binary files /dev/null and b/localization/ar/commander/etc/commander.urm.png differ diff --git a/localization/ar/composite-entity/README.md b/localization/ar/composite-entity/README.md new file mode 100644 index 000000000000..0e04ae3efe03 --- /dev/null +++ b/localization/ar/composite-entity/README.md @@ -0,0 +1,159 @@ +--- +title: Composite Entity +shortTitle: Composite Entity +category: Structural +language: ar +tag: + - Client-server + - Data access + - Enterprise patterns +--- + +## أيضا يُعرف بـ + +* الكيان ذو الحبيبات الخشنة + +## الهدف + +هدف نمط التصميم **الكيان المركب** هو إدارة مجموعة من الكائنات المستمرة المترابطة كما لو كانت كيانًا واحدًا. يتم استخدامه عادة في سياق **Enterprise JavaBeans (EJB)** وأطر العمل التجارية المماثلة لتمثيل الهياكل البيانية للبيانات ضمن نماذج الأعمال، مما يتيح للعملاء التعامل معها كوحدة واحدة. + +## الشرح + +مثال واقعي + +> في وحدة التحكم، قد يكون هناك العديد من الواجهات التي تحتاج إلى إدارة ومراقبة. باستخدام نمط الكيان المركب، يمكن دمج الكائنات المعتمدة مثل الرسائل والإشارات والسيطرة عليها باستخدام كائن واحد. + +بكلمات بسيطة + +> نمط الكيان المركب يسمح بتمثيل وإدارة مجموعة من الكائنات المرتبطة من خلال كائن موحد. + +**مثال برمجي** + +نحتاج إلى حل عام للمشكلة. لذلك، سنقدم نمطًا عامًا للكيان المركب. + + +```java +public abstract class DependentObject { + + T data; + + public void setData(T message) { + this.data = message; + } + + public T getData() { + return data; + } +} + +public abstract class CoarseGrainedObject { + + DependentObject[] dependentObjects; + + public void setData(T... data) { + IntStream.range(0, data.length).forEach(i -> dependentObjects[i].setData(data[i])); + } + + public T[] getData() { + return (T[]) Arrays.stream(dependentObjects).map(DependentObject::getData).toArray(); + } +} + +``` + +الكائن المركب المتخصص `consola` يرث من هذه الفئة الأساسية بالطريقة التالية. + + +```java +public class MessageDependentObject extends DependentObject { + +} + +public class SignalDependentObject extends DependentObject { + +} + +public class ConsoleCoarseGrainedObject extends CoarseGrainedObject { + + @Override + public String[] getData() { + super.getData(); + return new String[] { + dependentObjects[0].getData(), dependentObjects[1].getData() + }; + } + + public void init() { + dependentObjects = new DependentObject[] { + new MessageDependentObject(), new SignalDependentObject()}; + } +} + +public class CompositeEntity { + + private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); + + public void setData(String message, String signal) { + console.setData(message, signal); + } + + public String[] getData() { + return console.getData(); + } +} +``` + +إدارة الآن تخصيص كائنات الرسالة والإشارة مع الكائن المركب `consola`. + + +```java +var console=new CompositeEntity(); + console.init(); + console.setData("No Danger","Green Light"); + Arrays.stream(console.getData()).forEach(LOGGER::info); + console.setData("Danger","Red Light"); + Arrays.stream(console.getData()).forEach(LOGGER::info); +``` + +## مخطط الفئات + +![alt text](./etc/composite_entity.urm.png "نمط الكائن المركب") + +## القابلية للتطبيق + +* مفيد في التطبيقات التجارية حيث تكون الكائنات التجارية معقدة وتنطوي على عدة كائنات مترابطة. +* مثالي للسيناريوهات التي يحتاج فيها العملاء للعمل مع واجهة موحدة لمجموعة من الكائنات بدلاً من الكائنات الفردية. +* قابل للتطبيق في الأنظمة التي تتطلب عرضًا مبسطًا لنموذج بيانات معقد للعملاء أو الخدمات الخارجية. + +## الاستخدامات المعروفة + +* التطبيقات التجارية ذات النماذج التجارية المعقدة، وخاصة تلك التي تستخدم EJB أو أطر عمل تجارية مشابهة. +* الأنظمة التي تتطلب تجريدًا فوق مخططات قواعد بيانات معقدة لتبسيط التفاعلات مع العملاء. +* التطبيقات التي تحتاج إلى تعزيز التناسق أو المعاملات عبر عدة كائنات في كائن تجاري واحد. + +## العواقب + +الفوائد: + +* يبسط تفاعلات العميل مع النماذج الكائنية المعقدة من خلال توفير واجهة موحدة. +* يعزز إعادة الاستخدام والصيانة في طبقة الأعمال عن طريق فصل كود العميل عن المكونات الداخلية المعقدة للكائنات التجارية. +* يسهل إدارة المعاملات وتطبيق التناسق في مجموعة من الكائنات المترابطة. + +السلبيات: + +* قد يقدم مستوى من الاستدلال الذي قد يؤثر على الأداء. +* قد يؤدي إلى واجهات ذات حبوب خشنة جدًا قد لا تكون مرنة لجميع احتياجات العملاء. +* يتطلب تصميمًا دقيقًا لتجنب الكائنات المركبة المتضخمة التي يصعب إدارتها. + +## الأنماط ذات الصلة + +* [الزخرفة](https://java-design-patterns.com/patterns/decorator/): لإضافة سلوك ديناميكي للكائنات الفردية داخل الكائن المركب دون التأثير على الهيكل. +* [الواجهة](https://java-design-patterns.com/patterns/facade/): يوفر واجهة مبسطة لنظام فرعي معقد، بشكل مشابه لكيفية تبسيط الكائن المركب الوصول إلى مجموعة من الكائنات. +* [الوزن الخفيف](https://java-design-patterns.com/patterns/flyweight/): مفيد لإدارة الكائنات المشتركة داخل الكائن المركب لتقليل بصمة الذاكرة. + +## الاعتمادات + +* [نمط الكائن المركب في ويكيبيديا](https://en.wikipedia.org/wiki/Composite_entity_pattern) +* [أفضل الممارسات واستراتيجيات التصميم في الأنماط الأساسية لـ J2EE](https://amzn.to/4cAbDap) +* [أنماط المؤسسة و MDA: بناء البرمجيات الأفضل باستخدام أنماط الأركيتايب و UML](https://amzn.to/49mslqS) +* [أنماط بنية التطبيقات المؤسسية](https://amzn.to/3xjKdpe) diff --git a/localization/ar/composite-entity/etc/composite_entity.urm.png b/localization/ar/composite-entity/etc/composite_entity.urm.png new file mode 100644 index 000000000000..d6c29a718837 Binary files /dev/null and b/localization/ar/composite-entity/etc/composite_entity.urm.png differ diff --git a/localization/ar/composite-view/README.md b/localization/ar/composite-view/README.md new file mode 100644 index 000000000000..dcd543c43a2f --- /dev/null +++ b/localization/ar/composite-view/README.md @@ -0,0 +1,353 @@ +--- +title: Composite View +shortTitle: Composite View +category: Structural +language: ar +tag: + - Enterprise patterns + - Presentation +--- + +## الغرض + +الهدف الرئيسي من نمط التصميم "عرض مركب" هو تكوين الكائنات في هياكل شجرية لتمثيل الهيراركية جزء-كامل. هذا يتيح للعملاء التعامل مع الكائنات الفردية وتركيبات الكائنات بشكل موحد، مما يبسط إدارة الهياكل المعقدة. + +## التفسير + +مثال من العالم الحقيقي + +> موقع إخباري يريد عرض التاريخ الحالي والأخبار لعدة مستخدمين بناءً على تفضيلات كل مستخدم. سيستبدل الموقع في مكونات تغذية الأخبار المختلفة حسب اهتمامات المستخدم، مع الأخبار المحلية كافتراضي. + +بإيجاز + +> نمط العرض المركب يتكون من عرض رئيسي مكون من عروض فرعية أصغر. يعتمد تصميم هذا العرض المركب على قالب. ثم يقرر مدير العرض أي العروض الفرعية يجب تضمينها في هذا القالب. + +تقول ويكيبيديا + +> العروض المركبة التي تتكون من العديد من العروض الفرعية الذرية. يمكن تضمين كل مكون من القالب ديناميكيًا في المجموعة ويمكن إدارة تصميم الصفحة بشكل مستقل عن المحتوى. يتيح هذا الحل إنشاء عرض مركب استنادًا إلى تضمين واستبدال أجزاء قابلة لإعادة الاستخدام من القوالب الديناميكية والثابتة. يعزز التصميم المعياري من خلال تشجيع إعادة استخدام أجزاء الذرة من العرض. + +**مثال برمجي** + +نظرًا لأن هذا نمط تطوير ويب، فإن الخادم مطلوب لعرضه. يستخدم هذا المثال Tomcat 10.0.13 لتشغيل السيرفلت، ولن يعمل هذا المثال البرمجي إلا مع Tomcat 10+. + +أولاً، يوجد `AppServlet` الذي هو `HttpServlet` يعمل في Tomcat 10+. + + +```java +public class AppServlet extends HttpServlet { + private String msgPartOne = "

    This Server Doesn't Support"; + private String msgPartTwo = "Requests

    \n" + + "

    Use a GET request with boolean values for the following parameters

    \n" + + "

    'name'

    \n

    'bus'

    \n

    'sports'

    \n

    'sci'

    \n

    'world'

    "; + + private String destination = "newsDisplay.jsp"; + + public AppServlet() { + + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination); + ClientPropertiesBean reqParams = new ClientPropertiesBean(req); + req.setAttribute("properties", reqParams); + requestDispatcher.forward(req, resp); + } + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Post " + msgPartTwo); + + } + + @Override + public void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Delete " + msgPartTwo); + + } + + @Override + public void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Put " + msgPartTwo); + + } +} + +``` + +هذا السيرفلت لا يشكل جزءًا من النمط، ويقوم ببساطة بإعادة توجيه طلبات GET إلى JSP الصحيح. الطلبات PUT و POST و DELETE غير مدعومة وستعرض ببساطة رسالة خطأ. + +إدارة العرض في هذا المثال تتم من خلال فئة javabean: `ClientPropertiesBean`، التي تخزن تفضيلات المستخدم. + + +```java +public class ClientPropertiesBean implements Serializable { + + private static final String WORLD_PARAM = "world"; + private static final String SCIENCE_PARAM = "sci"; + private static final String SPORTS_PARAM = "sport"; + private static final String BUSINESS_PARAM = "bus"; + private static final String NAME_PARAM = "name"; + + private static final String DEFAULT_NAME = "DEFAULT_NAME"; + private boolean worldNewsInterest; + private boolean sportsInterest; + private boolean businessInterest; + private boolean scienceNewsInterest; + private String name; + + public ClientPropertiesBean() { + worldNewsInterest = true; + sportsInterest = true; + businessInterest = true; + scienceNewsInterest = true; + name = DEFAULT_NAME; + + } + + public ClientPropertiesBean(HttpServletRequest req) { + worldNewsInterest = Boolean.parseBoolean(req.getParameter(WORLD_PARAM)); + sportsInterest = Boolean.parseBoolean(req.getParameter(SPORTS_PARAM)); + businessInterest = Boolean.parseBoolean(req.getParameter(BUSINESS_PARAM)); + scienceNewsInterest = Boolean.parseBoolean(req.getParameter(SCIENCE_PARAM)); + String tempName = req.getParameter(NAME_PARAM); + if (tempName == null || tempName == "") { + tempName = DEFAULT_NAME; + } + name = tempName; + } + // getters and setters generated by Lombok +} +``` + +هذا السيرفلت لا يشكل جزءًا من النمط، ويقوم ببساطة بإعادة توجيه طلبات GET إلى JSP الصحيح. الطلبات PUT و POST و DELETE غير مدعومة وستعرض ببساطة رسالة خطأ. + +إدارة العرض في هذا المثال تتم من خلال فئة javabean: `ClientPropertiesBean`، التي تخزن تفضيلات المستخدم. + + +```html + + + + + + +<%ClientPropertiesBean propertiesBean = (ClientPropertiesBean) request.getAttribute("properties");%> +

    Welcome <%= propertiesBean.getName()%>

    + + + + + + <% if(propertiesBean.isWorldNewsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isBusinessInterest()) { %> + + <% } else { %> + + <% } %> + + <% if(propertiesBean.isSportsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isScienceNewsInterest()) { %> + + <% } else { %> + + <% } %> + + +
    <%@include file="worldNews.jsp"%><%@include file="localNews.jsp"%>
    <%@include file="businessNews.jsp"%><%@include file="localNews.jsp"%><%@include file="sportsNews.jsp"%><%@include file="localNews.jsp"%>
    <%@include file="scienceNews.jsp"%><%@include file="localNews.jsp"%>
    + + +``` + +هذه الصفحة JSP هي القالب. تقوم بإعلان جدول يحتوي على ثلاث صفوف، مع مكون في الصف الأول، واثنين من المكونات في الصف الثاني، ومكون واحد في الصف الثالث. + +تعتبر السكربتات في الملف جزءًا من استراتيجية إدارة العرض التي تتضمن مختلف العناصر الفرعية الذرية بناءً على تفضيلات المستخدم في الجافابين. + +فيما يلي مثالان على العناصر الفرعية الذرية المُحاكاة المستخدمة في التكوين: `businessNews.jsp`. + + +```html + + + + + + +

    + Generic Business News +

    + + + + + + + + + +
    Stock prices up across the worldNew tech companies to invest in
    Industry leaders unveil new projectPrice fluctuations and what they mean
    + + +``` + +`localNews.jsp` + +```html + + + +
    +

    + Generic Local News +

    +
      +
    • + Mayoral elections coming up in 2 weeks +
    • +
    • + New parking meter rates downtown coming tomorrow +
    • +
    • + Park renovations to finish by the next year +
    • +
    • + Annual marathon sign ups available online +
    • +
    +
    + + +``` + +النتائج هي كما يلي: + +1) وضع المستخدم اسمه كـ `Tammy` في معلمات الطلب ولم يضع أي تفضيلات: ![alt text](./etc/images/noparam.png) +2) وضع المستخدم اسمه كـ `Johnny` في معلمات الطلب ولديه تفضيل للأخبار عن العالم، الأعمال والعلوم: ![alt text](./etc/images/threeparams.png) + +يتم تضمين العناصر الفرعية المختلفة مثل `worldNews.jsp`، `businessNews.jsp`، وغيرها بشكل مشروط بناءً على معلمات الطلب. + +**كيفية الاستخدام** + +لاختبار هذا المثال، تأكد من أن لديك Tomcat 10+ مثبتًا. قم بتكوين IDE الخاص بك لإنشاء ملف WAR من الوحدة ونشر هذا الملف على الخادم. + +IntelliJ: + +في `تشغيل` و `تحرير التكوينات` تأكد من أن خادم Tomcat هو أحد تكوينات التنفيذ. اذهب إلى تبويب النشر وتأكد من أنه يتم بناء artifact يسمى `composite-view:war exploded`. إذا لم يكن موجودًا، أضف واحدًا. + +تأكد من أن artifact يتم بناؤه من محتويات مجلد `web` ونتائج تجميع الوحدة. وجه مخرجات artifact إلى مكان مناسب. نفذ التكوين وشاهد الصفحة المستهدفة، واتبع التعليمات في تلك الصفحة للمتابعة. + +## مخطط الفئات + +![alt text](./etc/composite_view.png) + +يُظهر مخطط الفئات هنا الجافابين الذي يُعتبر مدير العرض. العروض هي ملفات JSP داخل مجلد الويب. + +## القابلية للتطبيق: + +استخدم نمط التصميم Composite View عندما: + +## تريد تمثيل الهياكل الجزئية للأشياء. + +* تتوقع أن الهياكل المركبة قد تتضمن مكونات جديدة في المستقبل. +* ترغب في أن يتمكن العملاء من تجاهل الفرق بين تكوينات الكائنات والكائنات الفردية. سيتعامل العملاء مع جميع الكائنات في الهيكل المركب بشكل موحد. + +## الاستخدامات المعروفة + +* واجهات المستخدم الرسومية (GUI) التي يمكن أن تحتوي فيها الأدوات على أدوات أخرى (على سبيل المثال، نافذة تحتوي على لوحات وأزرار وحقول نصية). +* هياكل الوثائق، مثل تمثيل الجداول التي تحتوي على صفوف، تحتوي هذه الصفوف بدورها على خلايا، والتي يمكن معالجتها جميعًا كعناصر في تسلسل هرمي موحد. + +## العواقب + +الفوائد: + +* مرونة كبيرة في إضافة مكونات جديدة: بما أن المكونات المركبة والعقد الورقية يتم التعامل معها بشكل موحد، يكون من الأسهل إضافة أنواع جديدة من المكونات. +* تبسيط الشيفرة البرمجية للعملاء: يمكن للعملاء التعامل مع الهياكل المركبة والعناصر الفردية بشكل موحد، مما يقلل من تعقيد الشيفرة البرمجية للعملاء. + +العيوب: + +* التعميم المفرط: قد يصبح تصميم النظام أكثر تعقيدًا إذا جعلت كل شيء مركبًا، خاصة إذا كانت تطبيقك لا يتطلب ذلك. +* صعوبة تطبيق القيود: قد يكون من الأصعب تقييد مكونات المركب لتكون من أنواع معينة فقط. + +## الأنماط ذات الصلة + +* [المزخرف](https://java-design-patterns.com/patterns/decorator/): بينما يستخدم مزخرف لإضافة مسؤوليات إلى الكائنات، يتم تصميم Composite لبناء هياكل كائنات. +* [الوزن الخفيف](https://java-design-patterns.com/patterns/flyweight/): يمكن دمج Composite غالبًا مع Flyweight لتنفيذ العقد الورقية المشتركة في هيكل مركب، مما يقلل من بصمة الذاكرة. +* [سلسلة المسؤولية](https://java-design-patterns.com/patterns/chain-of-responsibility/): يمكن استخدامها مع Composite للسماح للمكونات بتمرير الطلبات عبر التسلسل الهرمي. +* [المركب](https://java-design-patterns.com/patterns/composite/) +* [مساعد العرض](https://www.oracle.com/java/technologies/viewhelper.html) + +## الاعتمادات + +* [Core J2EE Patterns - Composite View](https://www.oracle.com/java/technologies/composite-view.html) +* [Composite View Design Pattern – Core J2EE Patterns](https://www.dineshonjava.com/composite-view-design-pattern/) +* [Patterns of Enterprise Application Architecture](https://amzn.to/49jpQG3) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3xfntGJ) diff --git a/localization/ar/composite-view/etc/composite_view.png b/localization/ar/composite-view/etc/composite_view.png new file mode 100644 index 000000000000..66215d9416b8 Binary files /dev/null and b/localization/ar/composite-view/etc/composite_view.png differ diff --git a/localization/ar/composite-view/etc/images/noparam.png b/localization/ar/composite-view/etc/images/noparam.png new file mode 100644 index 000000000000..2979cf2bc657 Binary files /dev/null and b/localization/ar/composite-view/etc/images/noparam.png differ diff --git a/localization/ar/composite-view/etc/images/threeparams.png b/localization/ar/composite-view/etc/images/threeparams.png new file mode 100644 index 000000000000..9338dedb8885 Binary files /dev/null and b/localization/ar/composite-view/etc/images/threeparams.png differ diff --git a/localization/ar/composite/README.md b/localization/ar/composite/README.md new file mode 100644 index 000000000000..a90040cc02ab --- /dev/null +++ b/localization/ar/composite/README.md @@ -0,0 +1,222 @@ +--- +title: Composite +shortTitle: Composite +category: Structural +language: ar +tag: + - Gang of Four + - Object composition + - Recursion +--- + +## أيضًا يُعرف بـ + +* شجرة الكائنات +* الهيكل المركب + +## الهدف + +تركيب الكائنات في هياكل شجرية لتمثيل التسلسل الهرمي "جزء-كامل". يسمح نمط المركب للعملاء بمعاملة الكائنات الفردية وتركيبات الكائنات بطريقة موحدة. + +## الشرح + +مثال واقعي + +> تتكون كل جملة من كلمات، وكل كلمة تتكون بدورها من أحرف. كل واحد من هذه الكائنات قابل للطباعة ويمكن أن يكون له شيء مطبوع قبله أو بعده، مثلًا الجملة دائمًا تنتهي بنقطة، والكلمة دائمًا تملك مسافة قبلها. + +بكلمات بسيطة + +> يسمح نمط المركب للعملاء بمعاملة الكائنات الفردية بطريقة موحدة. + +تقول ويكيبيديا + +> في هندسة البرمجيات، نمط المركب هو نمط تصميم تقسيمي. يصف هذا النمط أنه يجب معاملة مجموعة من الكائنات بنفس الطريقة التي يتم بها معاملة كائن واحد. الهدف من المركب هو "تركيب" الكائنات في هياكل شجرية لتمثيل التسلسل الهرمي "جزء-كامل". يسمح تنفيذ نمط التركيب للعملاء بمعاملة الكائنات الفردية وتركيبات الكائنات بطريقة موحدة. + +**مثال برمجي** + +باستخدام مثالنا السابق، هنا لدينا الفئة الأساسية `LetterComposite` وأنواع مختلفة من الكائنات القابلة للطباعة مثل `Letter`, `Word`, و `Sentence`. + + +```java +public abstract class LetterComposite { + + private final 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(); + children.forEach(LetterComposite::print); + printThisAfter(); + } +} + +public class Letter extends LetterComposite { + + private final char character; + + public Letter(char c) { + this.character = c; + } + + @Override + protected void printThisBefore() { + System.out.print(character); + } +} + +public class Word extends LetterComposite { + + public Word(List letters) { + letters.forEach(this::add); + } + + public Word(char... letters) { + for (char letter : letters) { + this.add(new Letter(letter)); + } + } + + @Override + protected void printThisBefore() { + System.out.print(" "); + } +} + +public class Sentence extends LetterComposite { + + public Sentence(List words) { + words.forEach(this::add); + } + + @Override + protected void printThisAfter() { + System.out.print("."); + } +} +``` + +## لدينا الآن مرسل لنقل الرسائل: + +```java +public class Messenger { + + LetterComposite messageFromOrcs() { + + var words = List.of( + new Word('W', 'h', 'e', 'r', 'e'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'h', 'i', 'p'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'a', 'y') + ); + + return new Sentence(words); + + } + + LetterComposite messageFromElves() { + + var words = List.of( + new Word('M', 'u', 'c', 'h'), + new Word('w', 'i', 'n', 'd'), + new Word('p', 'o', 'u', 'r', 's'), + new Word('f', 'r', 'o', 'm'), + new Word('y', 'o', 'u', 'r'), + new Word('m', 'o', 'u', 't', 'h') + ); + + return new Sentence(words); + + } + +} +``` + +## وبالتالي يمكن استخدامه كالتالي: + +```java +var messenger=new Messenger(); + + LOGGER.info("Message from the orcs: "); + messenger.messageFromOrcs().print(); + + LOGGER.info("Message from the elves: "); + messenger.messageFromElves().print(); +``` + +## مخرجات وحدة التحكم: + + + +``` +Message from the orcs: + Where there is a whip there is a way. +Message from the elves: + Much wind pours from your mouth. +``` + +## Diagrama de clases + +![alt text](./etc/composite.urm.png "Diagrama de clases compuestas") + +## Applicabilidad + +استخدم نمط **Composite** عندما: + +* ترغب في تمثيل الهياكل الجزئية للأشياء. +* ترغب في أن يتجاهل العملاء الفرق بين تراكيب الأشياء والأشياء الفردية. سيعالج العملاء جميع الكائنات في الهيكل المركب بشكل موحد. + +## الاستخدامات المعروفة + +* واجهات المستخدم الرسومية حيث يمكن للمكونات أن تحتوي على مكونات أخرى (مثل الألواح التي تحتوي على أزرار، تسميات، وألواح أخرى). +* تمثيلات أنظمة الملفات حيث يمكن للأدلة أن تحتوي على ملفات وأدلة أخرى. +* الهياكل التنظيمية حيث يمكن للقسم أن يحتوي على أقسام فرعية وموظفين. +* [java.awt.Container](http://docs.oracle.com/javase/8/docs/api/java/awt/Container.html) + و [java.awt.Component](http://docs.oracle.com/javase/8/docs/api/java/awt/Component.html) +* شجرة المكونات [Apache Wicket](https://github.com/apache/wicket)، + انظر [Component](https://github.com/apache/wicket/blob/91e154702ab1ff3481ef6cbb04c6044814b7e130/wicket-core/src/main/java/org/apache/wicket/Component.java) + و [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java) + +## العواقب + +### الفوائد: + +* يبسط الكود الخاص بالعميل، حيث يمكنه التعامل مع الهياكل المركبة والأشياء الفردية بشكل موحد. +* يسهل إضافة أنواع جديدة من المكونات، حيث لا يتعين تعديل الكود الموجود. + +### العيوب: + +* قد يجعل التصميم عامًا جدًا. قد يكون من الصعب تقييد مكونات المركب. +* قد يصعب تحديد أنواع المكونات في المركب. + +## الأنماط المتعلقة + +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): يمكن لـ Composite استخدام Flyweight لمشاركة + مثيلات المكونات بين عدة مركبات. +* [Iterador](https://java-design-patterns.com/patterns/iterator/): يمكن استخدامه لتصفح الهياكل المركبة. +* [Visitante](https://java-design-patterns.com/patterns/visitor/): يمكن تطبيق عملية على الهيكل المركب. + +## الائتمانات + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3xoLAmi) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3vBKXWb) diff --git a/localization/ar/composite/etc/composite.urm.png b/localization/ar/composite/etc/composite.urm.png new file mode 100644 index 000000000000..93c160f6450a Binary files /dev/null and b/localization/ar/composite/etc/composite.urm.png differ diff --git a/localization/ar/context-object/README.md b/localization/ar/context-object/README.md new file mode 100644 index 000000000000..77fd8d8b754c --- /dev/null +++ b/localization/ar/context-object/README.md @@ -0,0 +1,188 @@ +--- +title: Context object +shortTitle: Context object +category: Creational +language: ar +tags: + - Data access +--- + +## الاسم / التصنيف + +كائن السياق + +## يعرف أيضًا باسم + +السياق، تجميع السياق + +## الغرض + +فصل البيانات عن الفئات الخاصة بالبروتوكول وتخزين بيانات السياق في كائن مستقل عن التكنولوجيا الخاصة بالبروتوكول الأساسي. + +## الشرح + +مثال من العالم الواقعي + +> يحتوي هذا التطبيق على طبقات مختلفة موسومة مثل A وB وC، كل واحدة منها تستخرج معلومات محددة من سياق مشابه لاستخدامها لاحقًا في البرنامج. تمرير كل قطعة من المعلومات بشكل فردي سيكون غير فعال، لذا هناك حاجة إلى طريقة لتخزين وتمرير المعلومات بشكل فعال. +> بكلمات بسيطة + +> أنشئ كائنًا وخزن البيانات هناك، ثم مرر هذا الكائن حيثما كان مطلوبًا. + +[Core J2EE Patterns](http://corej2eepatterns.com/ContextObject.htm) يقول + +> استخدم كائن السياق (Context Object) لتغليف الحالة بطريقة مستقلة عن البروتوكول ليتم مشاركتها عبر تطبيقك. + +**مثال برمجي** + +نحدد البيانات التي يحتوي عليها كائن السياق (Context Object) للخدمة `ServiceContext`. + + +```Java +public class ServiceContext { + + String ACCOUNT_SERVICE, SESSION_SERVICE, SEARCH_SERVICE; + + public void setACCOUNT_SERVICE(String ACCOUNT_SERVICE) { + this.ACCOUNT_SERVICE = ACCOUNT_SERVICE; + } + + public void setSESSION_SERVICE(String SESSION_SERVICE) { + this.SESSION_SERVICE = SESSION_SERVICE; + } + + public void setSEARCH_SERVICE(String SEARCH_SERVICE) { + this.SEARCH_SERVICE = SEARCH_SERVICE; + } + + public String getACCOUNT_SERVICE() { + return ACCOUNT_SERVICE; + } + + public String getSESSION_SERVICE() { + return SESSION_SERVICE; + } + + public String getSEARCH_SERVICE() { + return SEARCH_SERVICE; + } + + public String toString() { return ACCOUNT_SERVICE + " " + SESSION_SERVICE + " " + SEARCH_SERVICE;} +} +``` + +يتم إنشاء واجهة `ServiceContextFactory` تُستخدم في أجزاء من التطبيق لإنشاء كائنات السياق. + + +```Java +public class ServiceContextFactory { + + public static ServiceContext createContext() { + return new ServiceContext(); + } +} +``` + +إنشاء كائن السياق في الطبقة الأولى `LayerA` والطبقة المجاورة `LayerB` حتى يتم استدعاء السياق في الطبقة الحالية `LayerC`، التي تقوم بترتيب الكائن. + + +```Java +public class LayerA { + + private static ServiceContext context; + + public LayerA() { + context = ServiceContextFactory.createContext(); + } + + public static ServiceContext getContext() { + return context; + } + + public void addAccountInfo(String accountService) { + context.setACCOUNT_SERVICE(accountService); + } +} + +public class LayerB { + + private static ServiceContext context; + + public LayerB(LayerA layerA) { + this.context = layerA.getContext(); + } + + public static ServiceContext getContext() { + return context; + } + + public void addSessionInfo(String sessionService) { + context.setSESSION_SERVICE(sessionService); + } +} + +public class LayerC { + + public static ServiceContext context; + + public LayerC(LayerB layerB) { + this.context = layerB.getContext(); + } + + public static ServiceContext getContext() { + return context; + } + + public void addSearchInfo(String searchService) { + context.setSEARCH_SERVICE(searchService); + } +} +``` + +إليك كائن السياق والطبقات قيد التنفيذ. + + +```Java +var layerA = new LayerA(); +layerA.addAccountInfo(SERVICE); +LOGGER.info("Context = {}",layerA.getContext()); +var layerB = new LayerB(layerA); +layerB.addSessionInfo(SERVICE); +LOGGER.info("Context = {}",layerB.getContext()); +var layerC = new LayerC(layerB); +layerC.addSearchInfo(SERVICE); +LOGGER.info("Context = {}",layerC.getContext()); +``` + +إخراج البرنامج: + + +```Java +Context = SERVICE null null +Context = SERVICE SERVICE null +Context = SERVICE SERVICE SERVICE +``` + +## رسم توضيحي للفئات + +![alt text](./etc/context-object.png "كائن السياق") + +## القابلية للتطبيق + +استخدم نمط كائن السياق (Context Object) لـ: + +* مشاركة المعلومات بين الطبقات المختلفة للنظام. +* فصل البيانات عن السياقات المحددة للبروتوكولات. +* عرض واجهات البرمجة ذات الصلة فقط ضمن السياق. + +## الاستخدامات المعروفة + +* [Spring: ApplicationContext](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html) +* [Oracle: SecurityContext](https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/SecurityContext.html) +* [Oracle: ServletContext](https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html) + +## الفضل + +* [Core J2EE Design Patterns](https://amzn.to/3IhcY9w) +* [موقع Core J2EE Design Patterns - كائن السياق](http://corej2eepatterns.com/ContextObject.htm) +* [Allan Kelly - نمط تجميع السياق](https://accu.org/journals/overload/12/63/kelly_246/) +* [Arvid S. Krishna وآخرون - كائن السياق](https://www.dre.vanderbilt.edu/~schmidt/PDF/Context-Object-Pattern.pdf) diff --git a/localization/ar/context-object/etc/context-object.png b/localization/ar/context-object/etc/context-object.png new file mode 100644 index 000000000000..a1f670812f7b Binary files /dev/null and b/localization/ar/context-object/etc/context-object.png differ diff --git a/localization/ar/converter/README.md b/localization/ar/converter/README.md new file mode 100644 index 000000000000..cef553e1da32 --- /dev/null +++ b/localization/ar/converter/README.md @@ -0,0 +1,102 @@ +--- +title: Converter +shortTitle: Converter +category: Creational +language: ar +tag: + - Decoupling +--- + +## الهدف + +الهدف من نمط المحول (Converter) هو توفير وسيلة عامة وشائعة للتحويل الثنائي الاتجاه بين الأنواع المقابلة، مما يتيح تنفيذًا نظيفًا حيث لا يحتاج الأنواع إلى معرفة بعضها البعض. علاوة على ذلك، يقدم نمط المحول تعيينًا ثنائي الاتجاه للمجموعات الثنائية الاتجاه، مما يقلل من الكود المكرر إلى الحد الأدنى. + +## الشرح + +مثال من الحياة الواقعية + +> في التطبيقات الواقعية، غالبًا ما يحدث أن يتكون طبقة قاعدة البيانات من كيانات تحتاج إلى أن يتم تحويلها إلى DTO لاستخدامها في طبقة منطق الأعمال. يتم إجراء تحويل مشابه لعدد potentially ضخم من الفئات ونحتاج إلى طريقة عامة لتحقيق ذلك. + +ببساطة + +> يسهل نمط التحويل (Converter) تعيين الكائنات من فئة إلى كائنات من فئة أخرى. + +**مثال برمجي** + +نحتاج إلى حل عام لمشكلة التعيين. لذلك، دعونا نقدم محولًا عامًا. + + +```java +public class Converter { + + private final Function fromDto; + private final Function fromEntity; + + public Converter(final Function fromDto, final Function fromEntity) { + this.fromDto = fromDto; + this.fromEntity = fromEntity; + } + + public final U convertFromDto(final T dto) { + return fromDto.apply(dto); + } + + public final T convertFromEntity(final U entity) { + return fromEntity.apply(entity); + } + + public final List createFromDtos(final Collection dtos) { + return dtos.stream().map(this::convertFromDto).collect(Collectors.toList()); + } + + public final List createFromEntities(final Collection entities) { + return entities.stream().map(this::convertFromEntity).collect(Collectors.toList()); + } +} +``` + +## المحولات المتخصصة ترث من هذه الفئة الأساسية كما يلي. + + +```java +public class UserConverter extends Converter { + + public UserConverter() { + super(UserConverter::convertToEntity, UserConverter::convertToDto); + } + + private static UserDto convertToDto(User user) { + return new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), user.getUserId()); + } + + private static User convertToEntity(UserDto dto) { + return new User(dto.getFirstName(), dto.getLastName(), dto.isActive(), dto.getEmail()); + } + +} +``` + +الآن يصبح التحويل بين `User` و `UserDto` أمرًا تافهًا. + + +```java +var userConverter = new UserConverter(); +var dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); +var user = userConverter.convertFromDto(dtoUser); +``` + +## مخطط الفئات + +![alt text](./etc/converter.png "نمط المحول") + +## القابلية للتطبيق + +استخدم نمط المحول في الحالات التالية: + +* عندما يكون لديك أنواع تتطابق منطقيًا مع بعضها البعض وتحتاج إلى تحويل الكيانات بينهما. +* عندما ترغب في توفير أشكال مختلفة لتحويل الأنواع اعتمادًا على السياق. +* كلما قدمت كائن نقل البيانات (DTO)، من المحتمل أن تحتاج إلى تحويله إلى معادله في المجال. + +## الاعتمادات + +* [نمط المحول في Java 8](http://www.xsolve.pl/blog/converter-pattern-in-java-8/) diff --git a/localization/ar/converter/etc/converter.png b/localization/ar/converter/etc/converter.png new file mode 100644 index 000000000000..01435ef5ae29 Binary files /dev/null and b/localization/ar/converter/etc/converter.png differ diff --git a/localization/ar/crtp/README.md b/localization/ar/crtp/README.md new file mode 100644 index 000000000000..f7ab6de3a210 --- /dev/null +++ b/localization/ar/crtp/README.md @@ -0,0 +1,139 @@ +--- +title: Curiously Recurring Template Pattern +language: ar +category: Structural +tag: +- Extensibility +- Instantiation +--- + +## الاسم / التصنيف + +نمط القالب المتكرر بغرابة + +## المعروف أيضًا باسم + +الحدود النوعية المتكررة، الجينيريك المتكرر + +## الهدف + +السماح للمكونات المشتقة بالوراثة من بعض الوظائف من مكون أساسي تكون متوافقة مع النوع المشتق. + +## الشرح + +مثال حقيقي + +> لتنظيم حدث للفنون القتالية المختلطة، من المهم التأكد من أن المباريات تتم بين رياضيين في نفس فئة الوزن. هذا يضمن تجنب المواجهات بين مقاتلين من أحجام مختلفة للغاية، مثل الوزن الثقيل ضد الوزن الخفيف. + +ببساطة + +> جعل بعض الطرق داخل نوع ما تقبل المعاملات الخاصة بأنواعه الفرعية. + +تقول ويكيبيديا + +> نمط القالب المتكرر بغرابة (CRTP) هو أسلوب برمجي، بدأ في C++، حيث تقوم فئة X بالاشتقاق من تطبيق قالب فئة باستخدام X نفسها كحجة للقالب. + +**مثال برمجي** + +لنحدد الواجهة العامة Fighter + + +```java +public interface Fighter { + + void fight(T t); + +} +``` + +تستخدم فئة `MMAFighter` لإنشاء مقاتلين يتميزون بفئة وزنهم. + + +```java +public class MmaFighter> implements Fighter { + + private final String name; + private final String surname; + private final String nickName; + private final String speciality; + + public MmaFighter(String name, String surname, String nickName, String speciality) { + this.name = name; + this.surname = surname; + this.nickName = nickName; + this.speciality = speciality; + } + + @Override + public void fight(T opponent) { + LOGGER.info("{} is going to fight against {}", this, opponent); + } + + @Override + public String toString() { + return name + " \"" + nickName + "\" " + surname; + } +} +``` + +فيما يلي بعض الأنواع الفرعية لـ `MMAFighter`: + + +```java +class MmaBantamweightFighter extends MmaFighter { + + public MmaBantamweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } + +} + +public class MmaHeavyweightFighter extends MmaFighter { + + public MmaHeavyweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } + +} +``` + +يمكن للمقاتل أن يواجه خصمًا من نفس فئة الوزن، وإذا كان الخصم من فئة وزن مختلفة يحدث خطأ. + + +```java +MmaBantamweightFighter fighter1 = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai"); +MmaBantamweightFighter fighter2 = new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo"); +fighter1.fight(fighter2); // This is fine + +MmaHeavyweightFighter fighter3 = new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing"); +MmaHeavyweightFighter fighter4 = new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu"); +fighter3.fight(fighter4); // This is fine too + +fighter1.fight(fighter3); // This will raise a compilation error +``` + +## Diagrama de clases + +![alt text](./etc/crtp.png "Diagrama de clases CRTP") + +## قابلية التطبيق + +استخدم نمط "القالب المتكرر بشكل غريب" عندما: + +* تواجه تعارضات في الأنواع عند ربط الأساليب في هيكل الكائنات +* ترغب في استخدام طريقة من الفئة معلمة يمكن أن تقبل الفئات الفرعية كوسائط، مما يسمح بتطبيقها على الكائنات التي ترث من هذه الفئة +* ترغب في أن تعمل بعض الأساليب فقط مع كائنات من نفس النوع، على سبيل المثال، لتحقيق المقارنة المتبادلة. + +## دروس تعليمية + +* [مدونة NuaH](https://nuah.livejournal.com/328187.html) +* إجابة من Yogesh Umesh Vaity على [ماذا يعني "الحدود التكرارية للنوع" في الأنواع العامة؟](https://stackoverflow.com/questions/7385949/what-does-recursive-type-bound-in-generics-mean) + +## الاستخدامات المعروفة + +* [java.lang.Enum](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Enum.html) + +## الاعتمادات + +* [كيف أفك تشفير "Enum>"؟](http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ106) +* الفصل 5 Generics، العنصر 30 في [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) diff --git a/localization/ar/crtp/etc/crtp.png b/localization/ar/crtp/etc/crtp.png new file mode 100644 index 000000000000..a348c8af6175 Binary files /dev/null and b/localization/ar/crtp/etc/crtp.png differ diff --git a/localization/ar/data-locality/README.md b/localization/ar/data-locality/README.md new file mode 100644 index 000000000000..9150d2b51bc6 --- /dev/null +++ b/localization/ar/data-locality/README.md @@ -0,0 +1,30 @@ +--- +title: Data Locality +shortTitle: Data Locality +category: Behavioral +language: ar +tag: + - Game programming + - Performance +--- + +## الهدف +يُسرع الوصول إلى الذاكرة من خلال تنظيم البيانات للاستفادة من ذاكرة التخزين المؤقت في وحدة المعالجة المركزية. + +تحتوي وحدات المعالجة المركزية الحديثة على ذاكرات تخزين مؤقت لتسريع الوصول إلى الذاكرة. يمكنها الوصول بسرعة أكبر إلى الذاكرة المجاورة لذاكرة تم الوصول إليها مؤخرًا. استفد من ذلك لتحسين الأداء عن طريق زيادة محلية البيانات، من خلال الحفاظ عليها في ذاكرة متجاورة بالترتيب الذي تعالجها فيه. + +## مخطط الفئات +![alt text](./etc/data-locality.urm.png "Data Locality pattern class diagram") + +## قابلية التطبيق + +* كما هو الحال مع معظم التحسينات، القاعدة الأولى لاستخدام نمط "محلية البيانات" هي عندما يكون لديك مشكلة في الأداء. +* مع هذا النمط بشكل خاص، ستحتاج أيضًا إلى التأكد من أن مشاكل الأداء ناتجة عن فقدان الذاكرة المؤقتة. + +## مثال من العالم الحقيقي + +* محرك الألعاب [Artemis](http://gamadu.com/artemis/) هو واحد من أولى وأكثر الأطر شهرة التي تستخدم معرفات بسيطة لكائنات اللعبة. + +## الاعتمادات + +* [أنماط برمجة الألعاب - أنماط التحسين: محلية البيانات](http://gameprogrammingpatterns.com/data-locality.html) diff --git a/localization/ar/data-locality/etc/data-locality.urm.png b/localization/ar/data-locality/etc/data-locality.urm.png new file mode 100644 index 000000000000..d19873739551 Binary files /dev/null and b/localization/ar/data-locality/etc/data-locality.urm.png differ diff --git a/localization/ar/decorator/README.md b/localization/ar/decorator/README.md new file mode 100644 index 000000000000..e36cc2695d79 --- /dev/null +++ b/localization/ar/decorator/README.md @@ -0,0 +1,164 @@ +--- +title: Decorator +shortTitle: Decorator +category: Structural +language: ar +tag: + - Gang of Four + - Extensibility +--- + +## المعروف أيضا باسم + +التغليف + +## الهدف + +إضافة مسؤوليات إضافية إلى كائن بطريقة ديناميكية. يوفر الزخرفة بديلاً مرنًا للوراثة لتوسيع الوظائف. + +## الشرح + +مثال من العالم الحقيقي + +> في التلال القريبة يعيش تيرول غاضب. عادة ما يكون يده عارية، ولكن في بعض الأحيان يحمل سلاحًا. لتسليح التيرول لا يتطلب الأمر إنشاء تيرول جديد بل تزيينه ديناميكيًا بسلاح مناسب. + +ببساطة + +> يتيح لك نمط الزخرفة تغيير سلوك كائن ديناميكيًا أثناء وقت التشغيل من خلال تغليفه في كائن من فئة الزخرفة. + +يقول Wikipedia + +> في البرمجة الكائنية التوجه، يعتبر نمط الزخرفة نمط تصميم يسمح بإضافة سلوك إلى كائن فردي، سواء بطريقة ثابتة أو ديناميكية، دون التأثير على سلوك الكائنات الأخرى من نفس الفئة. يُعتبر نمط الزخرفة مفيدًا للامتثال لمبدأ المسؤولية الفردية، حيث يسمح بتقسيم الوظائف بين الفئات ذات مجالات الاهتمام الفريدة، وكذلك لمبدأ الانفتاح-الإغلاق، من خلال السماح بتمديد وظائف الفئة دون تعديلها. + +**مثال برمجي** + +لنأخذ مثال التيرول. في البداية لدينا `SimpleTroll` الذي ينفذ الواجهة `Troll`: + + +```java +public interface Troll { + void atacar(); + int getPoderAtaque(); + void huirBatalla(); +} + +@Slf4j +public class SimpleTroll implements Troll { + + @Override + public void atacar() { + LOGGER.info("¡El troll intenta atraparte!"); + } + + @Override + public int getPoderAtaque() { + return 10; + } + + @Override + public void huirBatalla() { + LOGGER.info("¡El troll chilla de horror y huye!"); + } +} +``` + +بعد ذلك، نريد إضافة عصا للتيرول. يمكننا فعل ذلك بشكل ديناميكي باستخدام الزخرفة: + + +```java +@Slf4j +public class TrollConGarrote implements Troll { + + private final Troll decorado; + + public TrollConGarrote(Troll decorado) { + this.decorado = decorado; + } + + @Override + public void atacar() { + decorado.atacar(); + LOGGER.info("¡El troll te golpea con un garrote!"); + } + + @Override + public int getPoderAtaque() { + return decorado.getPoderAtaque() + 10; + } + + @Override + public void huirBatalla() { + decorado.huirBatalla(); + } +} +``` + +إليك التيرول في العمل: + + +```java +// التيرول البسيط +LOGGER.info("تيرول ذو مظهر بسيط يقترب."); +var troll = new SimpleTroll(); +troll.atacar(); +troll.huirBatalla(); +LOGGER.info("قوة التيرول البسيط: {}.\n", troll.getPoderAtaque()); + +// تغيير سلوك التيرول البسيط عن طريق إضافة ديكور +LOGGER.info("تيرول يحمل عصا ضخمة يفاجئك."); +var trollConGarrote = new TrollConGarrote(troll); +trollConGarrote.atacar(); +trollConGarrote.huirBatalla(); +LOGGER.info("قوة التيرول مع العصا: {}.\n", trollConGarrote.getPoderAtaque()); + +``` + +نتيجة البرنامج: + +```java +تيرول ذو مظهر بسيط يقترب. +!التيرول يحاول الإمساك بك! +!التيرول يصرخ من الرعب ويهرب! +قوة التيرول البسيط: 10. + +تيرول يحمل عصا ضخمة يفاجئك. +!التيرول يحاول الإمساك بك! +!التيرول يضربك بعصا ضخمة! +!التيرول يصرخ من الرعب ويهرب! +قوة التيرول مع العصا: 20. + +``` + +## مخطط الفئات + +![alt text](./etc/decorator.urm.png "مخطط فئات نمط الديكور") + +## القابلية للتطبيق + +يُستخدم نمط الديكور لـ: + +* إضافة مسؤوليات إلى كائنات فردية بشكل ديناميكي وشفاف، أي دون التأثير على الكائنات الأخرى. +* للمسؤوليات التي يمكن إزالتها. +* عندما يكون التوسيع بواسطة الفئات الفرعية غير عملي. في بعض الأحيان، قد يكون من الممكن إضافة عدد كبير من الامتدادات المستقلة التي قد تؤدي إلى انفجار في الفئات الفرعية لدعم كل مجموعة من التركيبات. أو قد تكون تعريفات الفئات مخفية أو غير متاحة للفئات الفرعية. + +## الدروس التعليمية + +* [دورة نمط الديكور](https://www.journaldev.com/1540/decorator-design-pattern-in-java-example) + +## الاستخدامات المعروفة + +* [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html)، [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html)، + [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) + و [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) +* [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-) +* [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-) +* [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-) + +## الاعتمادات + +* [تصميم الأنماط: عناصر البرمجيات القابلة لإعادة الاستخدام](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [البرمجة الوظيفية في جافا: تسخير قوة تعبيرات لامبدا في جافا 8](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) +* [أنماط تصميم J2EE](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [رأس الأنماط: دليل سهل الفهم](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [إعادة الهيكلة إلى الأنماط](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [أنماط تصميم J2EE](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/ar/decorator/etc/decorator.urm.png b/localization/ar/decorator/etc/decorator.urm.png new file mode 100644 index 000000000000..141c0563f0c6 Binary files /dev/null and b/localization/ar/decorator/etc/decorator.urm.png differ diff --git a/localization/ar/delegation/README.md b/localization/ar/delegation/README.md new file mode 100644 index 000000000000..1f0d84734dd1 --- /dev/null +++ b/localization/ar/delegation/README.md @@ -0,0 +1,119 @@ +--- +title: Delegation +shortTitle: Delegation +category: Structural +language: ar +tag: + - Decoupling +--- + +## يُعرف أيضًا بـ + +نمط الوكيل (Proxy Pattern) + +## الهدف + +هي تقنية يتم من خلالها أن يعبر كائن عن سلوك معين للخارج ولكنه في الواقع يفوض مسؤولية تنفيذ ذلك السلوك إلى كائن مرتبط. + +## الشرح + +مثال من الواقع + +> لنتخيل أن لدينا مغامرين يقاتلون ضد وحوش بأسلحة مختلفة حسب مهاراتهم وقدراتهم. يجب أن نكون قادرين على تجهيزهم بأسلحة مختلفة دون الحاجة لتعديل الشيفرة المصدرية لكل سلاح. يقوم نمط التفويض بهذا من خلال تفويض العمل بشكل ديناميكي إلى كائن معين يقوم بتنفيذ واجهة بها الطرق ذات الصلة. + +يقول ويكيبيديا + +> في البرمجة الشيئية، يشير التفويض إلى تقييم أحد الأعضاء (خاصية أو طريقة) لكائن (المستقبل) في سياق كائن آخر أصلي (المرسل). يمكن أن يتم التفويض بشكل صريح، عن طريق تمرير الكائن المرسل إلى الكائن المستقبل، وهو ما يمكن القيام به في أي لغة برمجة موجهة للكائنات؛ أو ضمنيًا، من خلال قواعد البحث عن الأعضاء في اللغة، وهو ما يتطلب دعم اللغة لهذه الوظيفة. + +**مثال برمجي** + +لدينا واجهة `Printer` وثلاثة تطبيقات هي `CanonPrinter`، `EpsonPrinter` و `HpPrinter`. + +```java +public interface Printer { + void print(final String message); +} + +@Slf4j +public class CanonPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("Canon Printer : {}", message); + } +} + +@Slf4j +public class EpsonPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("Epson Printer : {}", message); + } +} + +@Slf4j +public class HpPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("HP Printer : {}", message); + } +} +``` + +El `PrinterController` puede ser utilizado como un `Printer` delegando cualquier trabajo manejado por este +a un objeto que la implemente. + +```java +public class PrinterController implements Printer { + + private final Printer printer; + + public PrinterController(Printer printer) { + this.printer = printer; + } + + @Override + public void print(String message) { + printer.print(message); + } +} +``` + +الآن في شفرة العميل، يمكن لوحدات تحكم الطابعة طباعة الرسائل بطرق مختلفة اعتمادًا على الكائن الذي يتم تفويض العمل إليه. + + +```java +private static final String MESSAGE_TO_PRINT = "hello world"; + +var hpPrinterController = new PrinterController(new HpPrinter()); +var canonPrinterController = new PrinterController(new CanonPrinter()); +var epsonPrinterController = new PrinterController(new EpsonPrinter()); + +hpPrinterController.print(MESSAGE_TO_PRINT); +canonPrinterController.print(MESSAGE_TO_PRINT); +epsonPrinterController.print(MESSAGE_TO_PRINT) +``` + +مخرجات البرنامج: + + +```java +HP Printer : hello world +Canon Printer : hello world +Epson Printer : hello world +``` + +## مخطط الفئات + +![alt text](./etc/delegation.png "Delegate") + +## القابلية للتطبيق + +استخدم نمط التفويض لتحقيق ما يلي: + +* تقليل ارتباط الأساليب بالفئة الخاصة بها +* مكونات تتصرف بشكل متطابق، مع مراعاة أن هذا الوضع قد يتغير في المستقبل. + +## الاعتمادات + +* [نمط التفويض: ويكيبيديا](https://en.wikipedia.org/wiki/Delegation_pattern) +* [نمط الوكيل: ويكيبيديا](https://en.wikipedia.org/wiki/Proxy_pattern) diff --git a/localization/ar/delegation/etc/delegation.png b/localization/ar/delegation/etc/delegation.png new file mode 100644 index 000000000000..375ef4d6b00f Binary files /dev/null and b/localization/ar/delegation/etc/delegation.png differ diff --git a/localization/ar/dependency-injection/README.md b/localization/ar/dependency-injection/README.md new file mode 100644 index 000000000000..9b45931c6f03 --- /dev/null +++ b/localization/ar/dependency-injection/README.md @@ -0,0 +1,101 @@ +--- +title: Dependency Injection +shortTitle: Dependency Injection +category: Creational +language: ar +tag: + - Decoupling +--- + +## الغرض + +حقن التبعيات هو نمط تصميم برمجي يتم فيه حقن واحدة أو أكثر من التبعيات (أو الخدمات) إلى كائن تابع (أو عميل) وتصبح جزءاً من حالة العميل. يفصل النمط بين إنشاء التبعيات للعميل وسلوكه الخاص، مما يسمح بتصاميم برامج منخفضة الارتباط وتلتزم بمبادئ عكس التحكم والمسؤولية الواحدة. + +## الشرح + +مثال من العالم الحقيقي + +> يحب الساحر العجوز ملء غليونه والتدخين من وقت لآخر. ومع ذلك، لا يريد أن يعتمد على علامة تجارية واحدة من التبغ، بل يحب أن يتمكن من الاستمتاع بها جميعاً بشكل قابل للتبادل. + +بكلمات بسيطة + +> حقن التبعيات يفصل إنشاء التبعيات للعميل عن سلوكه الخاص. + +تقول ويكيبيديا + +> في هندسة البرمجيات، حقن التبعيات هو تقنية يحصل فيها كائن على كائنات أخرى يعتمد عليها. تُسمى هذه الكائنات الأخرى بالتبعيات. + +**مثال برمجي** + +لنقم أولاً بتقديم واجهة التبغ `Tobacco` والعلامات التجارية المحددة. + + +```java +@Slf4j +public abstract class Tobacco { + + public void smoke(Wizard wizard) { + LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(), + this.getClass().getSimpleName()); + } +} + +public class SecondBreakfastTobacco extends Tobacco { +} + +public class RivendellTobacco extends Tobacco { +} + +public class OldTobyTobacco extends Tobacco { +} +``` + +التالي هو واجهة `Wizard` وتنفيذها. + + +```java +public interface Wizard { + + void smoke(); +} + +public class AdvancedWizard implements Wizard { + + private final Tobacco tobacco; + + public AdvancedWizard(Tobacco tobacco) { + this.tobacco = tobacco; + } + + @Override + public void smoke() { + tobacco.smoke(this); + } +} +``` + +وأخيراً يمكننا أن نثبت مدى سهولة إعطاء التبغ `Tobacco` لأي علامة تجارية قديمة للساحر. + + +```java + var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco()); + advancedWizard.smoke(); +``` + +## Class Diagram + +![alt text](./etc/dependency-injection.png "Dependency Injection") + +## Applicability + +Use the Dependency Injection pattern when: + +* You need to eliminate the knowledge of the concrete implementation of the object. +* To allow unit testing of classes in isolation using mock objects or stubs. + +## Credits + +* [Dependency Injection Principles, Practices, and Patterns](https://www.amazon.com/gp/product/161729473X/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=161729473X&linkId=57079257a5c7d33755493802f3b884bd) +* [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.com/gp/product/0132350882/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0132350882&linkCode=as2&tag=javadesignpat-20&linkId=2c390d89cc9e61c01b9e7005c7842871) +* [Java 9 Dependency Injection: Write loosely coupled code with Spring 5 and Guice](https://www.amazon.com/gp/product/1788296257/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=1788296257&linkId=4e9137a3bf722a8b5b156cce1eec0fc1) +* [Google Guice: Agile Lightweight Dependency Injection Framework](https://www.amazon.com/gp/product/1590599977/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1590599977&linkId=3b10c90b7ba480a1b7777ff38000f956) diff --git a/localization/ar/dependency-injection/etc/dependency-injection.png b/localization/ar/dependency-injection/etc/dependency-injection.png new file mode 100644 index 000000000000..2a92c9eb228b Binary files /dev/null and b/localization/ar/dependency-injection/etc/dependency-injection.png differ diff --git a/localization/ar/dirty-flag/README.md b/localization/ar/dirty-flag/README.md new file mode 100644 index 000000000000..4c9b5742e942 --- /dev/null +++ b/localization/ar/dirty-flag/README.md @@ -0,0 +1,28 @@ +--- +title: Dirty Flag +shortTitle: Dirty Flag +category: Behavioral +language: ar +tag: + - Game programming + - Performance +--- + +## Also known as +* IsDirty pattern + +## Purpose +Avoid the costly re-acquisition of resources. Resources retain their identity, are stored in some fast-access storage, and are reused to avoid having to acquire them again. + +## Class Diagram +![alt text](./etc/dirty-flag.png "Dirty Flag") + +## Applicability +Use the Dirty Flag pattern when + +* The repetitive acquisition, initialization, and release of the same resource causes unnecessary performance overhead. + +## Credits + +* [Design Patterns: Dirty Flag](https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) diff --git a/localization/ar/dirty-flag/etc/dirty-flag.png b/localization/ar/dirty-flag/etc/dirty-flag.png new file mode 100644 index 000000000000..98d4f679d17c Binary files /dev/null and b/localization/ar/dirty-flag/etc/dirty-flag.png differ diff --git a/localization/ar/double-buffer/README.md b/localization/ar/double-buffer/README.md new file mode 100644 index 000000000000..46b47a33ef48 --- /dev/null +++ b/localization/ar/double-buffer/README.md @@ -0,0 +1,245 @@ +--- +title: Double Buffer +shortTitle: Double Buffer +category: Behavioral +language: ar +tag: + - Performance + - Game programming +--- + +## الهدف + +الذاكرة المزدوجة هي مصطلح يُستخدم لوصف جهاز يحتوي على مخزنين. استخدام المخازن المتعددة يزيد من الأداء العام للجهاز ويساعد في تجنب الاختناقات. يُظهر هذا المثال استخدام الذاكرة المزدوجة في الرسومات. يُستخدم لعرض صورة أو إطار بينما يتم تخزين إطار آخر في المخزن ليتم عرضه لاحقًا. هذه الطريقة تجعل الرسوم المتحركة والألعاب تبدو أكثر واقعية مقارنة بتلك التي تُعرض باستخدام الذاكرة الفردية. + +## الشرح + +مثال من الحياة الواقعية +> مثال نموذجي، ويجب أن تتعامل معه جميع محركات الألعاب، هو التقديم. عندما يرسم اللعبة العالم الذي يراه المستخدمون، تقوم بذلك قطعة قطعة: الجبال البعيدة، التلال المتدحرجة، الأشجار، كل منها على حدة. إذا رأى المستخدم كيف يتم رسم العرض بشكل تدريجي، فسوف تنكسر الوهم لعالم متماسك. يجب تحديث المشهد بسلاسة وسرعة، مع عرض سلسلة من الإطارات المكتملة، يظهر كل منها فورًا. يحل التقديم المزدوج هذه المشكلة. + +ببساطة +> يضمن حالة يتم عرضها بشكل صحيح بينما يتم تعديل تلك الحالة تدريجيًا. يتم استخدامه كثيرًا في الرسومات الحاسوبية. + +ويكيبيديا تقول +> في علوم الكمبيوتر، التخزين في الذاكرة المتعددة هو استخدام أكثر من مخزن واحد لحمل كتلة من البيانات، بحيث يرى "القارئ" نسخة كاملة (على الرغم من أنها قديمة) من البيانات، بدلاً من نسخة محدثة جزئيًا من البيانات التي يقوم "الكاتب" بإنشائها. يُستخدم ذلك كثيرًا في الصور الحاسوبية. + +**مثال برمجي** + +واجهة `Buffer` التي تضمن الوظائف الأساسية للمخزن. + +```java +/** + * Buffer interface. + */ +public interface Buffer { + + /** + * Clear the pixel in (x, y). + * + * @param x X coordinate + * @param y Y coordinate + */ + void clear(int x, int y); + + /** + * Draw the pixel in (x, y). + * + * @param x X coordinate + * @param y Y coordinate + */ + void draw(int x, int y); + + /** + * Clear all the pixels. + */ + void clearAll(); + + /** + * Get all the pixels. + * + * @return pixel list + */ + Pixel[] getPixels(); + +} +``` + +إحدى تطبيقات واجهة `Buffer`. + + +```java +/** + * FrameBuffer implementation class. + */ +public class FrameBuffer implements Buffer { + + public static final int WIDTH = 10; + public static final int HEIGHT = 8; + + private final Pixel[] pixels = new Pixel[WIDTH * HEIGHT]; + + public FrameBuffer() { + clearAll(); + } + + @Override + public void clear(int x, int y) { + pixels[getIndex(x, y)] = Pixel.WHITE; + } + + @Override + public void draw(int x, int y) { + pixels[getIndex(x, y)] = Pixel.BLACK; + } + + @Override + public void clearAll() { + Arrays.fill(pixels, Pixel.WHITE); + } + + @Override + public Pixel[] getPixels() { + return pixels; + } + + private int getIndex(int x, int y) { + return x + WIDTH * y; + } +} +``` + +```java +/** + * Pixel enum. Each pixel can be white (not drawn) or black (drawn). + */ +public enum Pixel { + + WHITE, BLACK; +} +``` + +`Scene` representa la escena del juego en la que ya se ha renderizado el búfer actual. + +```java +/** + * Scene class. Render the output frame. + */ +@Slf4j +public class Scene { + + private final Buffer[] frameBuffers; + + private int current; + + private int next; + + /** + * Constructor of Scene. + */ + public Scene() { + frameBuffers = new FrameBuffer[2]; + frameBuffers[0] = new FrameBuffer(); + frameBuffers[1] = new FrameBuffer(); + current = 0; + next = 1; + } + + /** + * Draw the next frame. + * + * @param coordinateList list of pixels of which the color should be black + */ + public void draw(List> coordinateList) { + LOGGER.info("Start drawing next frame"); + LOGGER.info("Current buffer: " + current + " Next buffer: " + next); + frameBuffers[next].clearAll(); + coordinateList.forEach(coordinate -> { + var x = coordinate.getKey(); + var y = coordinate.getValue(); + frameBuffers[next].draw(x, y); + }); + LOGGER.info("Swap current and next buffer"); + swap(); + LOGGER.info("Finish swapping"); + LOGGER.info("Current buffer: " + current + " Next buffer: " + next); + } + + public Buffer getBuffer() { + LOGGER.info("Get current buffer: " + current); + return frameBuffers[current]; + } + + private void swap() { + current = current ^ next; + next = current ^ next; + current = current ^ next; + } + +} +``` + +```java +public static void main(String[] args) { + final var scene = new Scene(); + var drawPixels1 = List.of(new MutablePair<>(1, 1), new MutablePair<>(5, 6), new MutablePair<>(3, 2)); + scene.draw(drawPixels1); + var buffer1 = scene.getBuffer(); + printBlackPixelCoordinate(buffer1); + + var drawPixels2 = List.of(new MutablePair<>(3, 7), new MutablePair<>(6, 1)); + scene.draw(drawPixels2); + var buffer2 = scene.getBuffer(); + printBlackPixelCoordinate(buffer2); +} + +private static void printBlackPixelCoordinate(Buffer buffer) { + StringBuilder log = new StringBuilder("Black Pixels: "); + var pixels = buffer.getPixels(); + for (var i = 0; i < pixels.length; ++i) { + if (pixels[i] == Pixel.BLACK) { + var y = i / FrameBuffer.WIDTH; + var x = i % FrameBuffer.WIDTH; + log.append(" (").append(x).append(", ").append(y).append(")"); + } + } + LOGGER.info(log.toString()); +} +``` + +مخرجات وحدة التحكم + + +```text +[main] INFO com.iluwatar.doublebuffer.Scene - Start drawing next frame +[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 0 Next buffer: 1 +[main] INFO com.iluwatar.doublebuffer.Scene - Swap current and next buffer +[main] INFO com.iluwatar.doublebuffer.Scene - Finish swapping +[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 1 Next buffer: 0 +[main] INFO com.iluwatar.doublebuffer.Scene - Get current buffer: 1 +[main] INFO com.iluwatar.doublebuffer.App - Black Pixels: (1, 1) (3, 2) (5, 6) +[main] INFO com.iluwatar.doublebuffer.Scene - Start drawing next frame +[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 1 Next buffer: 0 +[main] INFO com.iluwatar.doublebuffer.Scene - Swap current and next buffer +[main] INFO com.iluwatar.doublebuffer.Scene - Finish swapping +[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 0 Next buffer: 1 +[main] INFO com.iluwatar.doublebuffer.Scene - Get current buffer: 0 +[main] INFO com.iluwatar.doublebuffer.App - Black Pixels: (6, 1) (3, 7) +``` + +## مخطط الفئات + +![alt text](./etc/double-buffer.urm.png "مخطط فئة نمط المخزن المؤقت المزدوج") + +## القابلية للتطبيق + +هذا النمط هو أحد الأنماط التي ستعرف متى تحتاج إليها. إذا كان لديك نظام يفتقر إلى المخزن المؤقت المزدوج، فمن المحتمل أن يبدو بشكل غير صحيح مرئيًا (تمزق الصورة، إلخ) أو سيعمل بشكل غير صحيح. ولكن قول "ستعرف متى تحتاج إليه" لا يعطي الكثير من التوضيح. بشكل أكثر تحديدًا، هذا النمط مناسب عندما يكون كل هذا صحيحًا: + +- لدينا حالة يتم تعديلها بشكل تدريجي. +- يمكن الوصول إلى نفس الحالة في منتصف التعديل. +- نريد تجنب أن يرى الكود الذي يصل إلى الحالة العمل الجاري. +- نريد أن نتمكن من قراءة الحالة دون الحاجة إلى الانتظار أثناء الكتابة. + +## المصادر + +* [Game Programming Patterns - Double Buffer](http://gameprogrammingpatterns.com/double-buffer.html) + diff --git a/localization/ar/double-buffer/etc/double-buffer.urm.png b/localization/ar/double-buffer/etc/double-buffer.urm.png new file mode 100644 index 000000000000..072ec4dad8be Binary files /dev/null and b/localization/ar/double-buffer/etc/double-buffer.urm.png differ diff --git a/localization/ar/embedded-value/README.md b/localization/ar/embedded-value/README.md new file mode 100644 index 000000000000..c147fef4edab --- /dev/null +++ b/localization/ar/embedded-value/README.md @@ -0,0 +1,131 @@ +--- +title: Embedded Value +shortTitle: Embedded Value +category: Structural +language: ar +tag: + - Data Access + - Enterprise Application Pattern +--- + +## معروف أيضًا باسم + +التخصيص المدمج، المُركب + +## الهدف + +العديد من الكائنات الصغيرة تكون منطقية في نظام البرمجة الكائنية ولا تكون منطقية كجداول في قاعدة بيانات. القيمة المدمجة تخصيص قيم كائن إلى حقول سجل الكائن المالك. + +## الشرح + +مثال من الواقع + +> بعض الأمثلة تشمل الكائنات النقدية والفترات الزمنية. على الرغم من أن التفكير الافتراضي هو تخزين كائن كجدول، إلا أنه لا أحد في عقله السليم يرغب في جدول للقيم النقدية. +> مثال آخر هو الطلبات عبر الإنترنت التي تحتوي على عنوان الشحن مثل الشارع، المدينة، الدولة. نقوم بتخصيص هذه القيم من كائن عنوان الشحن إلى حقول سجل كائن الطلب. + +بكلمات بسيطة + +> يسمح نمط القيم المدمجة بتخصيص كائن لعدة حقول في جدول كائن آخر. + +**مثال برمجي** + +لنأخذ مثالًا من طلب عبر الإنترنت حيث لدينا تفاصيل العنصر المطلوب وعنوان الشحن. لدينا +عنوان الشحن مدمج في كائن الطلب. ولكن في قاعدة البيانات نقوم بتخصيص قيم عنوان الشحن في سجل الطلب بدلاً من إنشاء جدول منفصل لعنوان الشحن واستخدام مفتاح خارجي للإشارة إلى كائن الطلب. + +أولاً، لدينا كائنات `Order` و `ShippingAddress`. + + +```java +public class Order { + + private int id; + private String item; + private String orderedBy; + private ShippingAddress ShippingAddress; + + public Order(String item, String orderedBy, ShippingAddress ShippingAddress) { + this.item = item; + this.orderedBy = orderedBy; + this.ShippingAddress = ShippingAddress; + } +} +``` + +```java +public class ShippingAddress { + + private String city; + private String state; + private String pincode; + + public ShippingAddress(String city, String state, String pincode) { + this.city = city; + this.state = state; + this.pincode = pincode; + } +} +``` + +الآن، علينا إنشاء جدول واحد فقط للطلب مع الحقول الخاصة بسمات عنوان الشحن. + + +```Sql +CREATE TABLE Orders (Id INT AUTO_INCREMENT, item VARCHAR(50) NOT NULL, orderedBy VARCHAR(50) city VARCHAR(50), state VARCHAR(50), pincode CHAR(6) NOT NULL, PRIMARY KEY(Id)) +``` + +أثناء إجراء الاستفسارات والإدخالات في قاعدة البيانات، نقوم بتغليف وفك تغليف تفاصيل عناوين الشحن. + + +```java +final String INSERT_ORDER = "INSERT INTO Orders (item, orderedBy, city, state, pincode) VALUES (?, ?, ?, ?, ?)"; + +public boolean insertOrder(Order order) throws Exception { + var insertOrder = new PreparedStatement(INSERT_ORDER); + var address = order.getShippingAddress(); + conn.setAutoCommit(false); + insertIntoOrders.setString(1, order.getItem()); + insertIntoOrders.setString(2, order.getOrderedBy()); + insertIntoOrders.setString(3, address.getCity()); + insertIntoOrders.setString(4, address.getState()); + insertIntoOrders.setString(5, address.getPincode()); + + var affectedRows = insertIntoOrders.executeUpdate(); + if(affectedRows == 1){ + Logger.info("Inserted successfully"); + }else{ + Logger.info("Couldn't insert " + order); + } +} +``` + +## مخطط الفئات + +![alt text](./etc/embedded-value.urm.png "مخطط فئة القيمة المدمجة") + +## القابلية للتطبيق + +استخدم نمط القيمة المدمجة عندما: + +* تكون العديد من الكائنات الصغيرة ذات معنى في نظام OO ولكن ليس لها معنى كجداول في قاعدة بيانات. +* الحالات الأبسط للقيمة المدمجة هي الكائنات ذات القيم الواضحة والبسيطة مثل المال ونطاق التواريخ. +* إذا كنت تقوم بربط إلى مخطط موجود، يمكنك استخدام هذا النمط عندما تحتوي إحدى الجداول على بيانات ترغب في تقسيمها إلى أكثر من كائن في الذاكرة. قد يحدث هذا عندما ترغب في استخراج بعض السلوك في نموذج الكائنات. +* في معظم الحالات، ستستخدم القيمة المدمجة فقط في كائن مرجعي عندما تكون العلاقة بينهما ذات قيمة واحدة في كلا الطرفين (علاقة واحد إلى واحد). + +## الدروس التعليمية + +* [Dzone](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-3) +* [Ram N Java](https://ramj2ee.blogspot.com/2013/08/embedded-value-design-pattern.html) +* [Five's Weblog](https://powerdream5.wordpress.com/2007/10/09/embedded-value/) + +## العواقب + +* الميزة الكبرى للقيمة المدمجة هي أنها تسمح بإجراء استفسارات SQL ضد قيم الكائن التابع. +* الكائن ذو القيمة المدمجة ليس له سلوك استمرارية. +* عند استخدام هذا، يجب أن تكون حذرًا من أن أي تغيير في التابع سيجعل المالك يعتبره "متسخًا" — وهو ما لا يمثل مشكلة مع الكائنات ذات القيمة التي يتم استبدالها في المالك. +* مشكلة أخرى هي التحميل والحفظ. إذا كنت تقوم بتحميل ذاكرة الكائن المدمج فقط عندما تقوم بتحميل المالك، فهذا حجة لحفظ كلاهما في نفس الجدول. +* قضية أخرى هي ما إذا كنت ترغب في الوصول إلى بيانات الكائنات المدمجة بشكل منفصل عبر SQL. قد يكون هذا مهمًا إذا كنت تقوم بإعداد تقارير عبر SQL وليس لديك قاعدة بيانات منفصلة للتقارير. + +## الائتمان + +* [Fowler, Martin - Patterns of enterprise application architecture-Addison-Wesley](https://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420) +* [Ram N Java](https://ramj2ee.blogspot.com/2013/08/embedded-value-design-pattern.html) diff --git a/localization/ar/embedded-value/etc/embedded-value.urm.png b/localization/ar/embedded-value/etc/embedded-value.urm.png new file mode 100644 index 000000000000..52d3ffb62352 Binary files /dev/null and b/localization/ar/embedded-value/etc/embedded-value.urm.png differ diff --git a/localization/ar/event-aggregator/README.md b/localization/ar/event-aggregator/README.md new file mode 100644 index 000000000000..03eae11fbe3c --- /dev/null +++ b/localization/ar/event-aggregator/README.md @@ -0,0 +1,167 @@ +--- +title: Event Aggregator +shortTitle: Event Aggregator +category: Structural +language: ar +tag: + - Reactive +--- + +## الاسم + +مجمع الأحداث + +## النية + +قد يصبح النظام الذي يحتوي على العديد من الكائنات معقدًا عندما يريد العميل الاشتراك في الأحداث. يجب على العميل +البحث والتسجيل في +كل كائن على حدة، وإذا كان كل كائن يحتوي على العديد من الأحداث فإن كل حدث يتطلب اشتراكًا +منفصلًا. يعمل مجمع الأحداث كمصدر واحد +للأحداث للعديد من الكائنات. يقوم بالتسجيل في جميع الأحداث للكائنات المتعددة مما يسمح للعملاء +بالتسجيل فقط مع المجمع. + +## الشرح + +مثال واقعي + +> يجلس الملك جوفري على عرش الحديد ويحكم الممالك السبع في وينترفل. يحصل على معظم معلوماته الهامة من يد الملك، +> وهو ثاني أقوى شخص في المملكة. يد الملك لديها العديد من المستشارين المقربين الذين يوفرون له معلومات هامة حول الأحداث التي تحدث في المملكة. + +بكلمات بسيطة + +> مجمع الأحداث هو وسيط للأحداث يقوم بجمع الأحداث من مصادر متعددة وتقديمها للمراقبين المسجلين. + +**مثال برمجي** + +في مثالنا البرمجي، نعرض تنفيذ نمط مجمع الأحداث. بعض الكائنات +هي مستمعون للأحداث، وبعضها الآخر هو مرسلو أحداث، والمجمع للأحداث يقوم بكلتا الوظيفتين. + + +```java +public interface EventObserver { + void onEvent(Event e); +} + +public abstract class EventEmitter { + + private final Map> observerLists; + + public EventEmitter() { + observerLists = new HashMap<>(); + } + + public final void registerObserver(EventObserver obs, Event e) { + ... + } + + protected void notifyObservers(Event e) { + ... + } +} +``` + +`KingJoffrey` يستمع إلى أحداث `KingsHand`. + + +```java +@Slf4j +public class KingJoffrey implements EventObserver { + @Override + public void onEvent(Event e) { + LOGGER.info("Received event from the King's Hand: {}", e.toString()); + } +} +``` + +`ReyMano` يستمع إلى الأحداث من مرؤوسيه `LordBaelish`، `LordVarys` و `Scout`. +ما يسمعه منهم، ينقله إلى "الملك جوفري". + + +```java +public class KingsHand extends EventEmitter implements EventObserver { + + public KingsHand() { + } + + public KingsHand(EventObserver obs, Event e) { + super(obs, e); + } + + @Override + public void onEvent(Event e) { + notifyObservers(e); + } +} +``` + +على سبيل المثال، `LordVarys` يجد خائنًا كل يوم أحد ويقوم بإبلاغ `KingsHand`. + + +```java +@Slf4j +public class LordVarys extends EventEmitter implements EventObserver { + @Override + public void timePasses(Weekday day) { + if (day == Weekday.SATURDAY) { + notifyObservers(Event.TRAITOR_DETECTED); + } + } +} +``` + +الجزء التالي يوضح كيفية بناء وربط الكائنات. + + +```java + var kingJoffrey = new KingJoffrey(); + + var kingsHand = new KingsHand(); + kingsHand.registerObserver(kingJoffrey, Event.TRAITOR_DETECTED); + kingsHand.registerObserver(kingJoffrey, Event.STARK_SIGHTED); + kingsHand.registerObserver(kingJoffrey, Event.WARSHIPS_APPROACHING); + kingsHand.registerObserver(kingJoffrey, Event.WHITE_WALKERS_SIGHTED); + + var varys = new LordVarys(); + varys.registerObserver(kingsHand, Event.TRAITOR_DETECTED); + varys.registerObserver(kingsHand, Event.WHITE_WALKERS_SIGHTED); + + var scout = new Scout(); + scout.registerObserver(kingsHand, Event.WARSHIPS_APPROACHING); + scout.registerObserver(varys, Event.WHITE_WALKERS_SIGHTED); + + var baelish = new LordBaelish(kingsHand, Event.STARK_SIGHTED); + + var emitters = List.of( + kingsHand, + baelish, + varys, + scout + ); + + Arrays.stream(Weekday.values()) + .>map(day -> emitter -> emitter.timePasses(day)) + .forEachOrdered(emitters::forEach); +``` + +الناتج في وحدة التحكم بعد تنفيذ المثال. + +``` +18:21:52.955 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: Warships approaching +18:21:52.960 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: White walkers sighted +18:21:52.960 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: Stark sighted +18:21:52.960 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: Traitor detected +``` + +## قابلية الاستخدام + +استخدم نمط "مجمّع الأحداث" عندما + +* يعد مجمّع الأحداث خيارًا جيدًا عندما يكون لديك العديد من الكائنات التي تعد مصادر محتملة للأحداث. بدلاً من جعل المراقب يتعامل مع التسجيل مع كل منها، يمكنك مركزية منطق التسجيل في مجمّع الأحداث. بالإضافة إلى تبسيط التسجيل، يبسط مجمّع الأحداث أيضًا مشكلات إدارة الذاكرة في استخدام المراقبين. + +## الأنماط المتعلقة + +* [Observer](https://java-design-patterns.com/patterns/observer/) + +## الاعتمادات + +* [مارتن فاولر - مجمّع الأحداث](http://martinfowler.com/eaaDev/EventAggregator.html) diff --git a/localization/ar/event-aggregator/etc/classes.png b/localization/ar/event-aggregator/etc/classes.png new file mode 100644 index 000000000000..295719ea3712 Binary files /dev/null and b/localization/ar/event-aggregator/etc/classes.png differ diff --git a/localization/ar/extension-objects/README.md b/localization/ar/extension-objects/README.md new file mode 100644 index 000000000000..0f96c8a0a516 --- /dev/null +++ b/localization/ar/extension-objects/README.md @@ -0,0 +1,149 @@ +--- +title: Extension objects +shortTitle: Extension objects +category: Behavioral +language: ar +tag: + - Extensibility +--- + +# نمط كائنات التوسيع (Extension Objects Pattern) + +## الهدف +التنبؤ بأنه يجب توسيع واجهة كائن ما في المستقبل. يتم تعريف الواجهات الإضافية من خلال كائنات التوسيع (Extension objects). + +## الشرح +مثال واقعي + +> افترض أنك تطور لعبة تعتمد على Java لعميل، وأثناء عملية التطوير، يُقترح عليك إضافة وظائف جديدة. يسمح لك نمط كائنات التوسيع بتكييف برنامجك مع التغييرات غير المتوقعة مع الحد الأدنى من إعادة الهيكلة، خاصة عند دمج وظائف إضافية في مشروعك. + +ببساطة + +> يتم استخدام نمط كائنات التوسيع لإضافة وظائف ديناميكيًا إلى الكائنات دون تعديل فئاتها الرئيسية. إنه نمط تصميم سلوكي يستخدم لإضافة وظائف جديدة إلى الفئات والكائنات الموجودة داخل البرنامج. يوفر هذا النمط للمبرمجين القدرة على تمديد/تعديل وظائف الفئات دون الحاجة إلى إعادة هيكلة الكود المصدر الحالي. + +تقول ويكيبيديا + +> في البرمجة الكائنية التوجه، يعتبر نمط كائنات التوسيع نمط تصميم يضاف إلى كائن بعد أن يتم تجميع الكائن الأصلي. الكائن المعدل غالبًا ما يكون فئة أو نموذجًا أو نوعًا. تعتبر أنماط كائنات التوسيع سمة من سمات بعض لغات البرمجة الكائنية التوجه. لا يوجد فرق نحوي بين استدعاء طريقة توسيع وطريقة معرفة في تعريف النوع. + +**مثال برمجي** + +الهدف من استخدام نمط كائنات التوسيع (Extension objects) هو تنفيذ ميزات/وظائف جديدة دون الحاجة إلى إعادة هيكلة كل فئة. +توضح الأمثلة التالية استخدام هذا النمط في فئة "العدو" التي تمتد من "الكيان" داخل لعبة: + +الفئة الرئيسية للتطبيق التي يتم تشغيل برنامجنا منها. + + +```java +public class App { + public static void main(String[] args) { + Entity enemy = new Enemy("Enemy"); + checkExtensionsForEntity(enemy); + } + + private static void checkExtensionsForEntity(Entity entity) { + Logger logger = Logger.getLogger(App.class.getName()); + String name = entity.getName(); + Function func = (e) -> () -> logger.info(name + " without " + e); + + String extension = "EnemyExtension"; + Optional.ofNullable(entity.getEntityExtension(extension)) + .map(e -> (EnemyExtension) e) + .ifPresentOrElse(EnemyExtension::extendedAction, func.apply(extension)); + } +} +``` +فئة العدو مع الإجراءات الأولية والتوسعات. + + +```java +class Enemy extends Entity { + public Enemy(String name) { + super(name); + } + + @Override + protected void performInitialAction() { + super.performInitialAction(); + System.out.println("Enemy wants to attack you."); + } + + @Override + public EntityExtension getEntityExtension(String extensionName) { + if (extensionName.equals("EnemyExtension")) { + return Optional.ofNullable(entityExtension).orElseGet(EnemyExtension::new); + } + return super.getEntityExtension(extensionName); + } +} +``` + +فئة EnemyExtension مع إعادة كتابة طريقة extendAction(). + + +```java +class EnemyExtension implements EntityExtension { + @Override + public void extendedAction() { + System.out.println("Enemy has advanced towards you!"); + } +} +``` + +فئة الكائن التي سيتم توسيعها بواسطة العدو. + + +```java +class Entity { + private String name; + protected EntityExtension entityExtension; + + public Entity(String name) { + this.name = name; + performInitialAction(); + } + + protected void performInitialAction() { + System.out.println(name + " performs the initial action."); + } + + public EntityExtension getEntityExtension(String extensionName) { + return null; + } + + public String getName() { + return name; + } +} +``` +واجهة `EntityExtension` التي ستستخدم `EnemyExtension`. + + +```java +interface EntityExtension { + void extendedAction(); +} +``` +إخراج البرنامج: + + +```markdown +Enemy performs the initial action. +Enemy wants to attack you. +Enemy has advanced towards you! +``` +في هذا المثال، يسمح نمط "كائنات التمديد" (Extension Objects) لكي يقوم الكائن العدو بتنفيذ إجراءات مبدئية فريدة وإجراءات متقدمة عند تطبيق التمديدات الخاصة. يوفر هذا النمط مرونة وقابلية تمديد لقاعدة الشيفرة مع تقليل الحاجة إلى إجراء تغييرات كبيرة في الشيفرة. + +## مخطط الفئات +![Extension_objects](./etc/extension_obj.png "Extension objects") + +## قابلية التطبيق +استخدم نمط "كائنات التمديد" (Extension objects) عندما: + +* تحتاج إلى دعم إضافة واجهات جديدة أو غير متوقعة إلى فئات موجودة ولا تريد التأثير على العملاء الذين لا يحتاجون إلى هذه الواجهة الجديدة. تتيح لك كائنات التمديد الاحتفاظ بالعمليات ذات الصلة معًا عن طريق تعريفها في فئة منفصلة. +* فئة تمثل تجريدًا رئيسيًا تؤدي وظائف مختلفة لعملاء مختلفين. يجب أن يكون عدد الوظائف التي يمكن أن تؤديها الفئة غير محدود. من الضروري الحفاظ على التجريد الرئيسي نفسه. على سبيل المثال، يبقى كائن العميل كائن عميل رغم أن الأنظمة الفرعية المختلفة قد تراها بطريقة مختلفة. +* يجب أن تكون الفئة قابلة للتمديد بسلوكيات جديدة دون الحاجة إلى تصنيفها منها. + +## أمثلة من العالم الحقيقي + +* [OpenDoc](https://en.wikipedia.org/wiki/OpenDoc) +* [ربط الكائنات وإدماجها](https://en.wikipedia.org/wiki/Object_Linking_and_Embedding) diff --git a/localization/ar/extension-objects/etc/extension_obj.png b/localization/ar/extension-objects/etc/extension_obj.png new file mode 100644 index 000000000000..a2b750e9dedd Binary files /dev/null and b/localization/ar/extension-objects/etc/extension_obj.png differ diff --git a/localization/ar/facade/README.md b/localization/ar/facade/README.md new file mode 100644 index 000000000000..99fa3bd04e9f --- /dev/null +++ b/localization/ar/facade/README.md @@ -0,0 +1,216 @@ +--- +title: Facade +shortTitle: Facade +category: Structural +language: ar +tag: + - Gang Of Four + - Decoupling +--- + +## الهدف + +توفير واجهة موحدة لمجموعة من واجهات النظام الفرعي. تقوم الواجهة البسيطة بتحديد واجهة تسهل استخدام النظام الفرعي. + +## الشرح + +مثال واقعي + +> كيف يعمل منجم الذهب؟ "حسنًا، ينزل العمال لاستخراج الذهب!" تقول. هذا ما تعتقده لأنك تستخدم واجهة بسيطة يوفرها منجم الذهب، ولكن من الداخل يجب أن يقوم بالكثير من الأشياء لتحقيق ذلك. هذه الواجهة البسيطة للنظام الفرعي المعقد هي الواجهة الأمامية. + +بإيجاز + +> يوفر نمط الواجهة الأمامية واجهة مبسطة لنظام فرعي معقد. + +تقول ويكيبيديا + +> الواجهة الأمامية هي كائن يوفر واجهة مبسطة لجسم من الكود الأكبر، مثل مكتبة الفصول. + +**مثال برمجي** + +لنأخذ مثال منجم الذهب. هنا لدينا تسلسل عمال الأقزام في المنجم. أولاً، لدينا فئة أساسية `DwarvenMineWorker`: + + +```java + +@Slf4j +public abstract class DwarvenMineWorker { + + public void goToSleep() { + LOGGER.info("{} goes to sleep.", name()); + } + + public void wakeUp() { + LOGGER.info("{} wakes up.", name()); + } + + public void goHome() { + LOGGER.info("{} goes home.", name()); + } + + public void goToMine() { + LOGGER.info("{} goes to the mine.", name()); + } + + private void action(Action action) { + switch (action) { + case GO_TO_SLEEP -> goToSleep(); + case WAKE_UP -> wakeUp(); + case GO_HOME -> goHome(); + case GO_TO_MINE -> goToMine(); + case WORK -> work(); + default -> LOGGER.info("Undefined action"); + } + } + + public void action(Action... actions) { + Arrays.stream(actions).forEach(this::action); + } + + public abstract void work(); + + public abstract String name(); + + enum Action { + GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK + } +} +``` + +ثم لدينا الفئات المحددة للأقزام `DwarvenTunnelDigger`، `DwarvenGoldDigger` و `DwarvenCartOperator`: + + +```java +@Slf4j +public class DwarvenTunnelDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} creates another promising tunnel.", name()); + } + + @Override + public String name() { + return "Dwarven tunnel digger"; + } +} + +@Slf4j +public class DwarvenGoldDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} digs for gold.", name()); + } + + @Override + public String name() { + return "Dwarf gold digger"; + } +} + +@Slf4j +public class DwarvenCartOperator extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} moves gold chunks out of the mine.", name()); + } + + @Override + public String name() { + return "Dwarf cart operator"; + } +} + +``` + +لإدارة جميع هؤلاء العمال في منجم الذهب، لدينا `FachadaDwarvenGoldmine`: + + +```java +public class DwarvenGoldmineFacade { + + private final List workers; + + public DwarvenGoldmineFacade() { + workers = List.of( + new DwarvenGoldDigger(), + new DwarvenCartOperator(), + new DwarvenTunnelDigger()); + } + + public void startNewDay() { + makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); + } + + public void digOutGold() { + makeActions(workers, DwarvenMineWorker.Action.WORK); + } + + public void endDay() { + makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); + } + + private static void makeActions(Collection workers, + DwarvenMineWorker.Action... actions) { + workers.forEach(worker -> worker.action(actions)); + } +} +``` + +الآن سنستخدم الواجهة: + + +```java +var facade = new DwarvenGoldmineFacade(); +facade.startNewDay(); +facade.digOutGold(); +facade.endDay(); +``` + +إخراج البرنامج: + + +```java +// Dwarf gold digger wakes up. +// Dwarf gold digger goes to the mine. +// Dwarf cart operator wakes up. +// Dwarf cart operator goes to the mine. +// Dwarven tunnel digger wakes up. +// Dwarven tunnel digger goes to the mine. +// Dwarf gold digger digs for gold. +// Dwarf cart operator moves gold chunks out of the mine. +// Dwarven tunnel digger creates another promising tunnel. +// Dwarf gold digger goes home. +// Dwarf gold digger goes to sleep. +// Dwarf cart operator goes home. +// Dwarf cart operator goes to sleep. +// Dwarven tunnel digger goes home. +// Dwarven tunnel digger goes to sleep. +``` + +## مخطط الفئات + +![alt text](./etc/facade.urm.png "مخطط فئة نمط الواجهة") + +## قابلية التطبيق + +استخدم نمط الواجهة عندما: + +* ترغب في توفير واجهة بسيطة إلى نظام فرعي معقد. غالبًا ما تصبح الأنظمة الفرعية أكثر تعقيدًا مع تطورها. معظم الأنماط، عند تطبيقها، تؤدي إلى المزيد من الفئات الأصغر. هذا يجعل النظام الفرعي أكثر قابلية لإعادة الاستخدام وأسهل في التخصيص، ولكن أيضًا يصبح أكثر صعوبة في الاستخدام للعملاء الذين لا يحتاجون إلى تخصيصه. يمكن أن توفر الواجهة عرضًا بسيطًا افتراضيًا للنظام الفرعي الذي يكفي لمعظم العملاء. فقط العملاء الذين يحتاجون إلى مزيد من التخصيص سيضطرون للنظر إلى ما وراء الواجهة. +* هناك العديد من الاعتمادات بين العملاء وفئات تنفيذ التجريد. إدخال واجهة لفصل النظام الفرعي عن العملاء والأنظمة الفرعية الأخرى، مما يعزز الاستقلالية وقابلية النقل للنظام الفرعي. +* ترغب في تقسيم أنظمتك الفرعية. استخدم واجهة لتعريف نقطة دخول إلى كل مستوى من النظام الفرعي. إذا كانت الأنظمة الفرعية تعتمد على بعضها البعض، يمكنك تبسيط الاعتمادات بينها من خلال جعلها تتواصل مع بعضها البعض فقط من خلال واجهاتها. + +## الدروس التعليمية + +* [DigitalOcean](https://www.digitalocean.com/community/tutorials/facade-design-pattern-in-java) + +* [Refactoring Guru](https://refactoring.guru/design-patterns/facade) +* [GeekforGeeks](https://www.geeksforgeeks.org/facade-design-pattern-introduction/) +* [Tutorialspoint](https://www.tutorialspoint.com/design_pattern/facade_pattern.htm) + +## الاعتمادات + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/ar/facade/etc/facade.urm.png b/localization/ar/facade/etc/facade.urm.png new file mode 100644 index 000000000000..8e3ec7aca45e Binary files /dev/null and b/localization/ar/facade/etc/facade.urm.png differ diff --git a/localization/ar/factory/README.md b/localization/ar/factory/README.md new file mode 100644 index 000000000000..5241065e3590 --- /dev/null +++ b/localization/ar/factory/README.md @@ -0,0 +1,140 @@ +--- +title: Factory +shortTitle: Factory +category: Creational +language: ar +tag: + - Gang of Four +--- + +## أيضًا معروف بـ + +* المصنع البسيط +* طريقة المصنع الثابتة + +## الهدف + +توفير طريقة ثابتة محاطة في فئة تسمى المصنع (Factory)، لإخفاء منطق التنفيذ وجعل شفرة العميل تركز على الاستخدام بدلاً من تهيئة الكائنات الجديدة. + +## الشرح + +مثال من الحياة الواقعية + +> تخيل كيميائيًا على وشك تصنيع العملات. يجب أن يكون الكيميائي قادرًا على إنشاء عملات ذهبية وكذلك عملات نحاسية، ويجب أن يكون من الممكن التبديل بينهما دون تعديل الكود المصدري الحالي. يجعل نمط المصنع هذا ممكنًا من خلال توفير طريقة بناء ثابتة يمكن استدعاؤها مع المعلمات ذات الصلة. + +تقول ويكيبيديا + +> المصنع (Factory) هو كائن لإنشاء كائنات أخرى: بشكل رسمي، المصنع هو دالة أو طريقة تُرجع كائنات من نموذج أو فئة متغيرة. + +**مثال برمجي** + +لدينا واجهة عملة `Coin` واثنان من تطبيقات العملة: عملة ذهبية `GoldCoin` وعملة نحاسية `CopperCoin`. + + +```java +public interface Coin { + String getDescription(); +} + +public class GoldCoin implements Coin { + + static final String DESCRIPTION = "This is a gold coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class CopperCoin implements Coin { + + static final String DESCRIPTION = "This is a copper coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +تُمثل التعداد التالي أنواع العملات التي نقبلها (`GoldCoin` و `CopperCoin`). + + +```java +@RequiredArgsConstructor +@Getter +public enum CoinType { + + COPPER(CopperCoin::new), + GOLD(GoldCoin::new); + + private final Supplier constructor; +} +``` + +ثم لدينا الطريقة الثابتة للحصول على العملة `getCoin` لإنشاء كائنات العملة مغلفة داخل فئة المصنع `CoinFactory`. + + +```java +public class CoinFactory { + + public static Coin getCoin(CoinType type) { + return type.getConstructor().get(); + } +} +``` + +الآن في كود العميل يمكننا إنشاء أنواع مختلفة من العملات باستخدام فئة المصنع. + + +```java +LOGGER.info("The alchemist begins his work."); +var coin1 = CoinFactory.getCoin(CoinType.COPPER); +var coin2 = CoinFactory.getCoin(CoinType.GOLD); +LOGGER.info(coin1.getDescription()); +LOGGER.info(coin2.getDescription()); +``` + +### مخرجات البرنامج: + + +```java +The alchemist begins his work. +This is a copper coin. +This is a gold coin. +``` + +## المخطط البياني للفئات + +![alt text](./etc/factory.urm.png "Factory pattern diagrama de clases") + +## قابلية الاستخدام + +استخدم نمط المصنع (Factory) عندما يكون تركيزك على إنشاء الكائنات فقط دون القلق حول كيفية إنشائها وإدارتها. + +### المزايا + +* يسمح بجمع كل عمليات إنشاء الكائنات في مكان واحد وتجنب نشر الكلمة الأساسية 'new' عبر قاعدة الشيفرة. +* يُمكنك من كتابة شيفرة منخفضة الارتباط. من بين مزاياه الرئيسية: قابلية أفضل للاختبار، شيفرة سهلة الفهم، مكونات قابلة للاستبدال، قابلية التوسع، وميزات معزولة. + +### العيوب + +* قد يصبح الشيفرة أكثر تعقيدًا مما ينبغي. + +## أمثلة استخدام معروفة + +* [java.util.Calendar#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +* [java.util.ResourceBundle#getBundle()](https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +* [java.text.NumberFormat#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +* [java.nio.charset.Charset#forName()](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +* [java.net.URLStreamHandlerFactory#createURLStreamHandler(String)](https://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html) + (يعيد كائنات Singleton مختلفة استنادًا إلى بروتوكول معين) +* [java.util.EnumSet#of()](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of(E)) +* [javax.xml.bind.JAXBContext#createMarshaller()](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) + وأيضًا طرق مشابهة أخرى. + +## الأنماط المرتبطة + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/) diff --git a/localization/ar/factory/etc/factory.urm.png b/localization/ar/factory/etc/factory.urm.png new file mode 100644 index 000000000000..4b3420792e06 Binary files /dev/null and b/localization/ar/factory/etc/factory.urm.png differ diff --git a/localization/bn/README.md b/localization/bn/README.md new file mode 100644 index 000000000000..8c79f04f7582 --- /dev/null +++ b/localization/bn/README.md @@ -0,0 +1,92 @@ + + +# জাভাতে প্রয়োগ করা ডিজাইনের প্যাটার্ন + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) + +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) + +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) + +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) + +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + + + +[![All Contributors](https://img.shields.io/badge/all_contributors-213-orange.svg?style=flat-square)](#contributors-) + + + +
    + +বিভিন্ন ভাষায় পড়ুন : [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md), [**vi**](localization/vi/README.md), [**bn**](localization/bn/README.md) + +
    + +# ভূমিকা + +ডিজাইন প্যাটার্ন হল সেরা, আনুষ্ঠানিক অনুশীলন যা একজন প্রোগ্রামার ব্যবহার করতে পারে + +একটি অ্যাপ্লিকেশন বা সিস্টেম ডিজাইন করার সময় সাধারণ সমস্যাগুলি সমাধান করুন। + +ডিজাইনের প্যাটার্নগুলি পরীক্ষিত, প্রমাণিত প্রদান করে উন্নয়ন প্রক্রিয়াকে ত্বরান্বিত করতে পারে + +উন্নয়ন দৃষ্টান্ত + +ডিজাইন প্যাটার্নগুলি পুনঃব্যবহার করা সূক্ষ্ম সমস্যাগুলি প্রতিরোধ করতে সাহায্য করে যা প্রধান সমস্যাগুলির কারণ হয় + +সমস্যা, এবং এটি কোডার এবং স্থপতিদের জন্য কোড পাঠযোগ্যতাও উন্নত করে যারা + +নিদর্শনগুলির সাথে পরিচিত। + +# শুরু হচ্ছে + +এই সাইটটি জাভা ডিজাইন প্যাটার্ন প্রদর্শন করে। সমাধান উন্নত করা হয়েছে + +ওপেন সোর্স সম্প্রদায়ের অভিজ্ঞ প্রোগ্রামার এবং স্থপতি দ্বারা। প্যাটার্নগুলি তাদের উচ্চ-স্তরের বর্ণনা দ্বারা বা তাদের দেখে ব্রাউজ করা যেতে পারে + +সোর্স কোড। কোড উদাহরণ ভাল মন্তব্য করা হয় এবং হিসাবে চিন্তা করা যেতে পারে + +প্রোগ্রামিং টিউটোরিয়াল কিভাবে একটি নির্দিষ্ট প্যাটার্ন বাস্তবায়ন করতে হয়। আমরা সবচেয়ে বেশি ব্যবহার করি + +জনপ্রিয় ওপেন সোর্স জাভা প্রযুক্তি। + +আপনি উপাদান সম্পর্কে জানার আগে, আপনি বিভিন্ন সঙ্গে পরিচিত হতে হবে + +[Software Design Principles](https://java-design-patterns.com/principles/). + +সমস্ত ডিজাইন যতটা সম্ভব সহজ হওয়া উচিত। আপনার চুম্বন, যগ্নি দিয়ে শুরু করা উচিত, + +এবং সবচেয়ে সহজ জিনিসটি করুন যা সম্ভবত নীতিগুলি কাজ করতে পারে। জটিলতা এবং + +নিদর্শনগুলি কেবল তখনই চালু করা উচিত যখন সেগুলি ব্যবহারিক জন্য প্রয়োজন + +এক্সটেনসিবিলিটি + +একবার আপনি এই ধারণাগুলির সাথে পরিচিত হয়ে গেলে আপনি ড্রিল করা শুরু করতে পারেন + +[available design patterns](https://java-design-patterns.com/patterns/) নিম্নলিখিত পন্থাগুলির যেকোনো একটি দ্বারা + + - নাম দ্বারা একটি নির্দিষ্ট প্যাটার্ন জন্য অনুসন্ধান করুন। একটি খুঁজে পাচ্ছেন না? একটি নতুন প্যাটার্ন রিপোর্ট করুন [here](https://github.com/iluwatar/java-design-patterns/issues). + + - ট্যাগ ব্যবহার করা যেমন `পারফরম্যান্স`, `গ্যাং অফ ফোর` বা `ডেটা অ্যাক্সেস`। + + - প্যাটার্ন বিভাগ, `সৃজনশীল`, `আচরণমূলক` এবং অন্যান্য ব্যবহার করে। + +আশা করি, আপনি এই সাইটে উপস্থাপিত অবজেক্ট-ওরিয়েন্টেড সমাধানগুলিকে আপনার আর্কিটেকচারে উপযোগী খুঁজে পাবেন এবং সেগুলিকে বিকাশ করার সময় আমরা সেগুলি শিখতে যতটা মজা পেয়েছি। + +# কিভাবে অবদান রাখতে হয় + +আপনি যদি প্রকল্পে অবদান রাখতে ইচ্ছুক হন তবে আপনি আমাদের প্রাসঙ্গিক তথ্য পাবেন [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). + +আমরা আপনাকে সাহায্য করব এবং আপনার প্রশ্নের উত্তর দেব [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns). + +# লাইসেন্স + +এই প্রকল্পটি MIT লাইসেন্সের শর্তাবলীর অধীনে লাইসেন্সপ্রাপ্ত। + diff --git a/localization/da/README.md b/localization/da/README.md new file mode 100644 index 000000000000..893851ebafe8 --- /dev/null +++ b/localization/da/README.md @@ -0,0 +1,54 @@ + + +# Designmønstre implementeret i Java + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-267-orange.svg?style=flat-square)](#contributors-) + + +
    + +Læs på andre sprog : [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md), [**vi**](localization/vi/README.md), [**bn**](localization/bn/README.md), [**np**](localization/ne/README.md), [**it**](localization/it/README.md) +
    + +# Introduktion + +Designmønstre er de bedste formaliserede praksisser, som en programmør kan anvende for at løse typiske problemer i forbindelse med design af en applikation eller et system. + +Designmønstre kan øge udviklingsprocessen ved at give testede, dokumenterede udviklingsparadigmer. + +Genanvendelse af designmønstre hjælper med at forhindre diskrete problemer, som kan føre til større problemer, og det forbedrer også kodelæsbarheden for programmører og arkitekter, der er bekendte med mønstrene. + +# Kom godt i gang + +Denne side viser Designmønstre I Java. Løsningerne er udviklet af erfarne programmører og arkitekter fra open-source fællesskabet. Mønstrene kan blive udforsket efter deres beskrivelser eller ved at se på deres kildekode. Kildekodeeksemplerne er velkommenterede og kan blive betragtet som programmerings-vejledninger om, hvordan man implementerer et specifikt mønster. Vi bruger de mest populære, afprøvede open-source Java-teknologier. + +Før du dykker ned i materialet, burde du være bekendt med forskellige +[Software Design Principper](https://java-design-patterns.com/principles/). + +Alle designs bør være så simple som muligt. Du bør starte med KISS, YAGNI, og Do The Simplest Thing That Could Possibly Work principperne. Kompleksitet og mønstre bør kun introduceres, når de er nødvendige for praktisk udvidelse. + +Når du først er bekendt med disse begreber, kan du begynde at bore ned i +[tilgængelige designmønstre](https://java-design-patterns.com/patterns/) ved at anvende en af disse tilgange: + + - Søg efter et specifikt mønster ved navn. Kan du ikke finde et? Rapportér venligst et nyt mønster [her](https://github.com/iluwatar/java-design-patterns/issues). + - Brug tags såsom `Performance`, `Gang of Four` eller `Data access`. + - Brug mønsterkategorier, såsom `Creational`, `Behavioral`, og andre. + +Forhåbentlig finder du de objektorienterede løsninger, der præsenteres på denne side, nyttige i dine arkitekturer og har lige så meget sjov med at lære dem, som vi havde, mens vi udviklede dem. + +# Hvordan man bidrager + +Hvis du er villig til at bidrage til projektet, finder du relevante oplysninger i +vores [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). Vi vil hjælpe dig og besvare dine spørgsmål i [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns). + +# Licens + +Dette projekt er licenseret under vilkårene for MIT-licensen. diff --git a/localization/de/README.md b/localization/de/README.md new file mode 100644 index 000000000000..b727e6ba47e1 --- /dev/null +++ b/localization/de/README.md @@ -0,0 +1,48 @@ +# In Java implementierte Entwurfsmuster + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![Lizenz MIT](https://img.shields.io/badge/lizenz-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Codezeilen](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Abdeckung](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Chat beitreten unter https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-208-orange.svg?style=flat-square)](#contributors-) + + +
    + +In anderen Sprachen lesen: [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md) + +
    + +# Einführung + +Entwurfsmuster sind bewährte Lösungen, die Entwickler nutzen können, um häufige Probleme beim Entwurf von Anwendungen oder Systemen zu lösen. + +Sie helfen dabei, den Entwicklungsprozess zu beschleunigen, indem sie erprobte und zuverlässige Ansätze bereitstellen. + +Die Wiederverwendung von Entwurfsmustern verhindert subtile Fehler, die zu größeren Problemen führen können, und verbessert die Lesbarkeit des Codes – besonders für Entwickler und Architekten, die mit diesen Mustern vertraut sind. + +# Erste Schritte + +Diese Seite stellt Java-Entwurfsmuster vor. Die Lösungen wurden von erfahrenen Entwicklern und Architekten aus der Open-Source-Community erstellt. Die Muster können entweder durch ihre Beschreibungen oder durch den Quellcode erkundet werden. Die Codebeispiele sind gut kommentiert und eignen sich als Tutorials, um die Muster zu verstehen und umzusetzen. Wir verwenden dabei bekannte und bewährte Open-Source-Java-Technologien. + +Bevor Sie sich mit den Entwurfsmustern beschäftigen, sollten Sie sich mit den grundlegenden [Software-Entwurfsprinzipien](https://java-design-patterns.com/principles/) vertraut machen. + +Entwürfe sollten immer so einfach wie möglich gehalten werden. Beginnen Sie mit den Prinzipien KISS (Keep It Simple, Stupid), YAGNI (You Aren’t Gonna Need It) und "Do The Simplest Thing That Could Possibly Work". Komplexe Muster sollten nur dann verwendet werden, wenn sie wirklich notwendig sind. + +Sobald Sie mit diesen Konzepten vertraut sind, können Sie sich die [verfügbaren Entwurfsmuster](https://java-design-patterns.com/patterns/) ansehen. Dafür gibt es verschiedene Ansätze: + +- Suchen Sie nach einem bestimmten Muster anhand des Namens. Fehlt ein Muster? Melden Sie es gerne [hier](https://github.com/iluwatar/java-design-patterns/issues). +- Nutzen Sie Tags wie `Performance`, `Gang of Four` oder `Data access`. +- Durchsuchen Sie die Muster nach Kategorien wie `Creational`, `Behavioral` und anderen. + +Wir hoffen, dass Sie die hier vorgestellten Lösungen für Ihre Projekte nützlich finden und genauso viel Spaß beim Lernen haben, wie wir bei der Entwicklung hatten. + +# Mitwirken + +Wenn Sie zum Projekt beitragen möchten, finden Sie alle notwendigen Informationen in unserem [Entwickler-Wiki](https://github.com/iluwatar/java-design-patterns/wiki). Bei Fragen helfen wir Ihnen gerne im [Gitter-Chatraum](https://gitter.im/iluwatar/java-design-patterns) weiter. + +# Lizenz + +Dieses Projekt steht unter der MIT-Lizenz. \ No newline at end of file diff --git a/localization/de/abstract-document/README.md b/localization/de/abstract-document/README.md new file mode 100644 index 000000000000..13f8d26fbbbf --- /dev/null +++ b/localization/de/abstract-document/README.md @@ -0,0 +1,226 @@ +--- +title: "Abstract Document Pattern in Java: Vereinfachung der Datenverwaltung mit Flexibilität" +shortTitle: Abstract Document +description: "Erkunden Sie das Abstract Document Design Pattern in Java. Lernen Sie seine Absicht, Erklärung, Anwendbarkeit, Vorteile kennen und sehen Sie reale Beispiele zur Implementierung flexibler und dynamischer Datenstrukturen." +category: Strukturell +language: de +tag: + - Abstraktion + - Entkopplung + - Dynamische Typisierung + - Kapselung + - Erweiterbarkeit + - Polymorphismus +--- + +## Absicht des Abstract Document Design Patterns + +Das Abstract Document Design Pattern in Java ist ein wichtiges strukturelles Design Pattern, das eine konsistente Möglichkeit bietet, hierarchische und baumartige Datenstrukturen zu handhaben, indem es eine gemeinsame Schnittstelle für verschiedene Dokumenttypen definiert. Es trennt die Kernstruktur des Dokuments von spezifischen Datenformaten und ermöglicht dynamische Aktualisierungen und vereinfachte Wartung. + +## Detaillierte Erklärung des Abstract Document Patterns mit realen Beispielen + +Das Abstract Document Design Pattern in Java ermöglicht die dynamische Handhabung nicht-statischer Eigenschaften. Dieses Pattern verwendet das Konzept der Traits, um Typsicherheit zu gewährleisten und Eigenschaften verschiedener Klassen in eine Menge von Schnittstellen zu trennen. + +Reales Beispiel + +> Betrachten Sie ein Bibliothekssystem, das das Abstract Document Design Pattern in Java implementiert, wo Bücher verschiedene Formate und Attribute haben können: physische Bücher, eBooks und Hörbücher. Jedes Format hat einzigartige Eigenschaften, wie Seitenzahl für physische Bücher, Dateigröße für eBooks und Dauer für Hörbücher. Das Abstract Document Design Pattern ermöglicht es dem Bibliothekssystem, diese verschiedenen Formate flexibel zu verwalten. Durch die Verwendung dieses Patterns kann das System Eigenschaften dynamisch speichern und abrufen, ohne dass eine starre Struktur für jeden Buchtyp erforderlich ist, was es einfacher macht, neue Formate oder Attribute in der Zukunft hinzuzufügen, ohne dass wesentliche Änderungen am Codebase erforderlich sind. + +In einfachen Worten + +> Das Abstract Document Pattern ermöglicht das Anhängen von Eigenschaften an Objekte, ohne dass diese davon wissen. + +Wikipedia sagt + +> Ein objektorientiertes strukturelles Design Pattern zur Organisation von Objekten in schwach typisierten Schlüssel-Wert-Speichern und zur Bereitstellung der Daten über typisierte Ansichten. Der Zweck des Patterns besteht darin, einen hohen Grad an Flexibilität zwischen Komponenten in einer stark typisierten Sprache zu erreichen, in der neue Eigenschaften zur Objektstruktur dynamisch hinzugefügt werden können, ohne die Unterstützung der Typsicherheit zu verlieren. Das Pattern verwendet Traits, um verschiedene Eigenschaften einer Klasse in verschiedene Schnittstellen zu trennen. + +## Programmatisches Beispiel des Abstract Document Patterns in Java + +Betrachten Sie ein Auto, das aus mehreren Teilen besteht. Wir wissen jedoch nicht, ob das spezifische Auto wirklich alle Teile hat oder nur einige davon. Unsere Autos sind dynamisch und extrem flexibel. + +Lassen Sie uns zunächst die Basisklassen `Document` und `AbstractDocument` definieren. Sie sorgen im Wesentlichen dafür, dass das Objekt eine Eigenschaftsmap und eine beliebige Anzahl von Kindobjekten enthält. + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + + // Andere Eigenschaften und Methoden... +} +``` +Als nächstes definieren wir ein Enum Property und eine Menge von Schnittstellen für Typ, Preis, Modell und Teile. Dies ermöglicht es uns, eine statisch aussehende Schnittstelle für unsere Car-Klasse zu erstellen. + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} + +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} +``` + +Jetzt sind wir bereit, das `Car` einzuführen. + +```java + public static void main(String[] args) { + LOGGER.info("Konstruktion von Teilen und Auto"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Hier ist unser Auto:"); + LOGGER.info("-> Modell: {}", car.getModel().orElseThrow()); + LOGGER.info("-> Preis: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> Teile: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); +} +``` +Die Programmausgabe: + +``` +07:21:57.391 [main] INFO com.iluwatar.abstractdocument.App -- Konstruktion von Teilen und Auto +07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- Hier ist unser Auto: +07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- -> Modell: 300SL +07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> Preis: 10000 +07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> Teile: +07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- Rad/15C/100 +07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- Tür/Lambo/300 +``` +## Abstract Document Pattern Klassendiagramm + +![Abstract Document](./etc/abstract-document.png "Abstract Document Traits und Domain") + +## Wann sollte das Abstract Document Pattern in Java verwendet werden? + +Das Abstract Document Design Pattern ist besonders vorteilhaft in Szenarien, die eine Verwaltung unterschiedlicher Dokumenttypen in Java erfordern, die einige gemeinsame Attribute oder Verhaltensweisen teilen, aber auch einzigartige Attribute oder Verhaltensweisen haben, die spezifisch für ihren Typ sind. Hier sind einige Szenarien, in denen das Abstract Document Design Pattern anwendbar ist: + +* **Content-Management-Systeme (CMS)**: In einem CMS könnten verschiedene Arten von Inhalten wie Artikel, Bilder, Videos usw. vorkommen. Jede Inhaltsart könnte gemeinsame Attribute wie Erstellungsdatum, Autor und Tags haben, aber auch spezifische Attribute wie Bildabmessungen für Bilder oder Videodauer für Videos. + +* **Dateisysteme**: Wenn Sie ein Dateisystem entwerfen, in dem unterschiedliche Dateitypen verwaltet werden müssen, wie Dokumente, Bilder, Audiodateien und Verzeichnisse, kann das Abstract Document Pattern helfen, eine konsistente Möglichkeit zum Zugriff auf Attribute wie Dateigröße, Erstellungsdatum usw. zu bieten, während spezifische Attribute wie Bildauflösung oder Audiodauer berücksichtigt werden. + +* **E-Commerce-Systeme**: Eine E-Commerce-Plattform könnte verschiedene Produkttypen haben, wie physische Produkte, digitale Downloads und Abonnements. Jeder Typ könnte gemeinsame Attribute wie Name, Preis und Beschreibung haben, aber auch einzigartige Attribute wie Versandgewicht für physische Produkte oder Download-Link für digitale Produkte. + +* **Medizinische Aufzeichnungssysteme**: Im Gesundheitswesen könnten Patientenakten verschiedene Datentypen enthalten, wie demografische Daten, medizinische Vorgeschichte, Testergebnisse und Rezepte. Das Abstract Document Pattern kann helfen, gemeinsame Attribute wie Patienten-ID und Geburtsdatum zu verwalten, während spezialisierte Attribute wie Testergebnisse oder verschriebene Medikamente berücksichtigt werden. + +* **Konfigurationsmanagement**: Bei der Verwaltung von Konfigurationseinstellungen für Softwareanwendungen gibt es möglicherweise verschiedene Arten von Konfigurationselementen, jedes mit einer eigenen Reihe von Attributen. Das Abstract Document Pattern kann verwendet werden, um diese Konfigurationselemente zu verwalten, während eine konsistente Möglichkeit zum Zugriff auf und Bearbeiten der Attribute sichergestellt wird. + +* **Bildungsplattformen**: Bildungssysteme könnten verschiedene Arten von Lernmaterialien wie textbasierte Inhalte, Videos, Quizze und Aufgaben haben. Gemeinsame Attribute wie Titel, Autor und Veröffentlichungsdatum können geteilt werden, während spezifische Attribute wie Videodauer oder Aufgabenfälligkeit für jeden Typ einzigartig sind. + +* **Projektmanagement-Tools**: In Projektmanagement-Anwendungen könnten unterschiedliche Aufgabenarten wie To-Do-Items, Meilensteine und Probleme vorliegen. Das Abstract Document Pattern könnte verwendet werden, um allgemeine Attribute wie Aufgabenname und Zuweisung zu handhaben, während spezifische Attribute wie Meilensteindaten oder Problemprioritäten zugelassen werden. + +* **Dokumente haben vielfältige und sich entwickelnde Attributstrukturen.** + +* **Dynamisches Hinzufügen neuer Eigenschaften ist eine häufige Anforderung.** + +* **Entkopplung des Datenzugriffs von spezifischen Formaten ist entscheidend.** + +* **Wartbarkeit und Flexibilität sind entscheidend für die Codebasis.** + +Die Hauptidee hinter dem Abstract Document Design Pattern ist es, eine flexible und erweiterbare Möglichkeit zur Verwaltung unterschiedlicher Dokumenttypen oder Entitäten mit gemeinsamen und spezifischen Attributen bereitzustellen. Durch die Definition einer gemeinsamen Schnittstelle und deren Implementierung über verschiedene Dokumenttypen hinweg können Sie einen besser organisierten und konsistenteren Ansatz zur Handhabung komplexer Datenstrukturen erreichen. + +## Vorteile und Abwägungen des Abstract Document Patterns + +**Vorteile:** + +* **Flexibilität**: Ermöglicht die Handhabung unterschiedlicher Dokumentstrukturen und -eigenschaften. +* **Erweiterbarkeit**: Neue Attribute können dynamisch hinzugefügt werden, ohne bestehenden Code zu brechen. +* **Wartbarkeit**: Fördert sauberen und anpassungsfähigen Code durch Trennung der Verantwortlichkeiten. +* **Wiederverwendbarkeit**: Typspezifische Ansichten ermöglichen eine Wiederverwendung des Codes zum Zugriff auf bestimmte Attributtypen. + +**Abwägungen:** + +* **Komplexität**: Erfordert die Definition von Schnittstellen und Ansichten, was zu zusätzlichem Implementierungsaufwand führt. +* **Leistung**: Kann im Vergleich zum direkten Datenzugriff zu leichtem Leistungsaufwand führen. + +## Quellen und Danksagungen + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://amzn.to/49zRP4R) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) +* [Abstract Document Pattern (Wikipedia)](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Dealing with Properties (Martin Fowler)](http://martinfowler.com/apsupp/properties.pdf) + + + + + diff --git a/localization/de/abstract-document/etc/abstract-document.png b/localization/de/abstract-document/etc/abstract-document.png new file mode 100644 index 000000000000..6bc0b29a4e77 Binary files /dev/null and b/localization/de/abstract-document/etc/abstract-document.png differ diff --git a/localization/el/README.md b/localization/el/README.md new file mode 100644 index 000000000000..50ddd4f508b2 --- /dev/null +++ b/localization/el/README.md @@ -0,0 +1,54 @@ + + +# Σχεδιαστικά μοτίβα για την Java + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-208-orange.svg?style=flat-square)](#contributors-) + + +
    + +# Εισαγωγή + +Τα σχεδιαστικά μοτίβα είναι οι καλύτερες, επίσημες πρακτικές που μπορεί να χρησιμοποιήσει ένας προγραμματιστής την λύση κοινών προβλημάτων κατά το σχεδιασμό μιας εφαρμογής ή συστήματος. + +Τα σχεδιαστικά μοτίβα μπορούν να επιταχύνουν τη διαδικασία ανάπτυξης παρέχοντας δοκιμασμένα, αποδεδειγμένα παραδείγματα. + +Η επαναχρησιμοποίηση σχεδιαστικών μοτίβων βοηθά στην αποφυγή λεπτών ζητημάτων που προκαλούν μεγάλα προβλήματα και βελτιώνει επίσης την αναγνωσιμότητα κώδικα για άτομα που είναι εξοικειωμένοι με τα μοτίβα αυτά. + +# Κάνοντας την αρχή + +Αυτός ο ιστότοπος παρουσιάζει σχεδιαστικά μοτίβα στην Java. Οι λύσεις έχουν αναπτυχθεί από έμπειρους προγραμματιστές και αρχιτέκτονες από την κοινότητα ανοιχτού κώδικα. Τα μοτίβα μπορούν να ελεγχθούν από τις περιγραφές υψηλού επιπέδου ή κοιτάζοντας τον πηγαίο κώδικα τους. Τα παραδείγματα του πηγαίου κώδικα είναι καλά σχολιασμένα και μπορούν να θεωρηθούν ως εκπαιδευτικά προγράμματα προγραμματισμού για τον τρόπο εφαρμογής ενός συγκεκριμένου μοτίβου. Χρησιμοποιούμε τις πιο δημοφιλείς τεχνολογίες Java ανοιχτού κώδικα, αποδεδειγμένα στη μάχη. + +Πριν ξεκινήσετε, θα πρέπει να είστε εξοικειωμένοι με διάφορες +[Αρχές Σχεδιασμού Λογισμικού](https://java-design-patterns.com/principles/). + +Όλα τα σχέδια πρέπει να είναι όσο το δυνατόν πιο απλά. Θα πρέπει να ξεκινήσετε με τις αρχές KISS, YAGNI και Do The Simplet Thing That Could Possibly Work. Πολυπλοκότητα και μοτίβα θα πρέπει να εισάγονται μόνο όταν χρειάζονται για πρακτική επεκτασιμότητα. + +Μόλις εξοικειωθείτε με αυτές τις έννοιες, μπορείτε να αρχίσετε να εξετάζετε τα +[τα διαθέσιμα σχεδιαστικά μοτίβα](https://java-design-patterns.com/patterns/) με οποιονδήποτε +απο τους παρακάτω τρόπους + + - Αναζητήστε ένα συγκεκριμένο μοτίβο με το όνομα του. Δεν μπορείτε να το βρείτε; Αναφέρετε ένα νέο μοτίβο [εδώ](https://github.com/iluwatar/java-design-patterns/issues). + - Χρησιμοποιώντας ετικέτες όπως `Performance`, `Gang of Four` or `Data access`. + - Χρησιμοποιώντας κατηγορίες μοτίβων, `Creational`, `Behavioral`, and others. + +Ας ελπίσουμε ότι θα βρείτε τις αντικειμενοστρεφείς λύσεις που παρουσιάζονται σε αυτόν τον ιστότοπο χρήσιμες στις αρχιτεκτονικές σας και θα διασκεδάσετε μαθαίνοντας τες όσο και εμείς κατά την ανάπτυξή τους. + +# Πως να συνεισφέρεις + +Εάν είστε πρόθυμοι να συνεισφέρετε στο έργο, θα βρείτε τις σχετικές πληροφορίες στο δικό μας [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). Θα σας βοηθήσουμε και θα απαντήσουμε στις ερωτήσεις σας στο [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns). + +# Άδεια + +Αυτό το έργο αδειοδοτείται σύμφωνα με τους όρους της άδειας MIT. + +# Συνεισφέροντες + diff --git a/localization/es/README.md b/localization/es/README.md new file mode 100644 index 000000000000..5540c3f0678c --- /dev/null +++ b/localization/es/README.md @@ -0,0 +1,50 @@ + + +# Patrones de diseño implementados en Java + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-167-orange.svg?style=flat-square)](#contributors-) + + +# Introducción + +Los patrones de diseño son las mejores prácticas formalizadas que un programador puede utilizar para resolver problemas comunes al diseñar una aplicación o sistema. + +Los patrones de diseño pueden acelerar el proceso de desarrollo al proporcionar paradigmas de desarrollo probados y comprobados. + +La reutilización de patrones de diseño ayuda a prevenir problemas sutiles que causan errores importantes, y también mejora la legibilidad del código para desarrolladores y arquitectos que están familiarizados con los patrones. + +# Comenzar + +Este sitio presenta los patrones de diseño en Java. Las soluciones han sido desarrolladas por +programadores y arquitectos experimentados de la comunidad de código abierto. Los patrones se pueden buscar por sus descripciones de alto nivel o mirando su código fuente. Los ejemplos de código fuente están bien comentados y pueden pensarse como tutoriales de programación sobre cómo implementar un patrón específico. Usamos las tecnologías Java de código abierto más populares. + +Antes de sumergirte en el material deberías estar familiarizado con varios +[Principios de diseño de software](https://java-design-patterns.com/principles/). + +Todos los diseños deben ser lo más simples posible. Deberías comenzar con los principios KISS, YAGNI y hacer lo más simple que funcione. La complejidad y los patrones solo deben introducirse cuando sean necesarios para una extensibilidad práctica. + +Una vez que esté familiarizado con estos conceptos, puedes comenzar a profundizar con los +[patrones de diseño disponibles](https://java-design-patterns.com/patterns/) por cualquiera de los siguientes enfoques + + - Buscar un patrón específico por su nombre. ¿No puedes encontrar uno? Informa de un nuevo patrón [aquí](https://github.com/iluwatar/java-design-patterns/issues). + - Usando etiquetas como `Performance`, `Gang of Four` ó `Data access`. + - Usando categorías de patrones, `Creational`, `Behavioral` y otras. + +Esperamos que las soluciones orientadas a objetos presentadas en este sitio te resulten útiles en sus arquitecturas y se divierta aprendiéndolas tanto como nosotros desarrollándolas. + +# Cómo contribuir + +Si estás dispuesto a contribuir al proyecto encontrarás la información relevante en nuestra [wiki del desarrollador](https://github.com/iluwatar/java-design-patterns/wiki). Te ayudaremos y responderemos tus preguntas en la [sala de chat de Gitter](https://gitter.im/iluwatar/java-design-patterns). + +# Licencia + +Este proyecto está licenciado de acuerdo con los términos de la licencia del MIT. + diff --git a/localization/es/abstract-document/README.md b/localization/es/abstract-document/README.md new file mode 100644 index 000000000000..ad07e56a292a --- /dev/null +++ b/localization/es/abstract-document/README.md @@ -0,0 +1,190 @@ +--- +title: Abstract Document +shortTitle: Abstract Document +category: Structural +language: es +tag: + - Extensibility +--- + +## Propósito + +Usar propiedades dinámicas y conseguir la flexibilidad de los lenguajes no tipados manteniendo la seguridad de tipos. + +## Explicación + +El uso del patrón Abstract Document permite gestionar propiedades no estáticas adicionales. Este patrón usa el concepto +de atributos para permitir seguridad de tipos y propiedades separadas de diferentes clases en un grupo de interfaces. + +Ejemplo del mundo real + +> Toma como ejemplo un coche que está formado por muchas partes. Sin embargo, no sabemos si el coche tiene todas las +> partes o solo una parte de ellas. Nuestros coches son dinámicos y extremadamente flexibles. + +Dicho de otra forma + +> El patrón Abstract Document permite añadir propiedades a objetos sin que estos sean conscientes de ello. + +Según Wikipedia + +> Un patrón de diseño estructural orientado a objetos para organizar objetos en contenedores clave-valor vagamente +> tipados y exponiendo los datos usando vistas tipadas. El propósito del patrón es conseguir un alto grado de flexibilidad +> entre componentes en un lenguaje de tipado fuerte donde nuevas propiedades pueden añadirse al árbol de objetos sobre la +> marcha sin perder el soporte de la seguridad de tipos. El patrón hace uso de atributos para separar diferentes +> propiedades de una clase en distintas interfaces. + +**Ejemplo Programático** + +Primero definamos las clases base `Document` y `AbstractDocument`. Básicamente, hacen que el objeto contenga un mapa de +propiedades y cualquier número de objetos hijo. + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + ... +} +``` + +A continuación definimos un enum `Property` y un grupo de interfaces para tipo, precio, modelo y partes. Esto nos +permite crear interfaces de apariencia estática para nuestra clase `Car`. + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} +``` + +Ahora estamos listos para introducir el Coche `Car`. + +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` + +Y finalmente asi es como construimos y usamos el Coche `Car` en un ejemplo completo. + +```java + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); + + // Constructing parts and car + // Here is our car: + // model: 300SL + // price: 10000 + // parts: + // wheel/15C/100 + // door/Lambo/300 +``` + +## Diagrama de clases + +![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain") + +## Aplicación + +Usar el patrón Abstract Document cuando + +* Existe la necesidad de añadir propiedades sobre la marcha. +* Quieres una manera flexible de organizar el dominio en una estructura similar a un árbol. +* Quieres un sistema menos acoplado. + +## Créditos + +* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492) diff --git a/localization/es/abstract-document/etc/abstract-document.png b/localization/es/abstract-document/etc/abstract-document.png new file mode 100644 index 000000000000..6bc0b29a4e77 Binary files /dev/null and b/localization/es/abstract-document/etc/abstract-document.png differ diff --git a/localization/es/abstract-factory/README.md b/localization/es/abstract-factory/README.md new file mode 100644 index 000000000000..84d63f941f9a --- /dev/null +++ b/localization/es/abstract-factory/README.md @@ -0,0 +1,229 @@ +--- +title: Abstract Factory +shortTitle: Abstract Factory +category: Creational +language: es +tag: + - Gang of Four +--- + +## También conocido como + +Kit + +## Propósito + +Proveer de una interfaz para crear familias de objetos relacionados dependientes sin especificar su clase concreta. + +## Explicación + +Ejemplo del mundo real + +> Para crear un reino necesitamos objetos con una temática común. El reino élfico necesita un rey elfo, un castillo élfico y un ejército élfico mientras que el reino orco necesita un rey orco, un castillo orco y un ejército orco. Hay una dependencia entre los objetos del reino. + +Dicho de otra forma + +> Una factoría de factorías; una factoría que agrupa otras factorías individuales pero relacionadas/dependientes sin especificar su clase concreta. + +Según Wikipedia + +> El patrón abstract factory provee una forma de encapsular un grupo de factorías individuales que tienen una temática común sin especificar sus clases concretas. + +**Ejemplo Programático** + +Traduciendo el ejemplo anterior sobre los reinos. Primero tenemos algunas interfaces e implementaciones de los objetos del `Castle`. + +```java +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 -> ... + +``` + +Luego tenemos la abstracción e implementación de la factoría del reino `KingdomFactory`. + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +Ahora tenemos la factoría abstracta que nos permite hacer familias de objetos relacionados por ejemplo la factoría del reino élfico `ElfKingdomFactory` crea el castillo `castle`, rey `king` y ejército `army` etc. + + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +Salida del programa: + +```java +This is the elven castle! +This is the elven king! +This is the elven Army! +``` + +Ahora podemos diseñar una factoría para nuestras factorías de reinos. En este ejemplo creamos `FactoryMaker`, responsable de devolver una instancia de `ElfKingdomFactory` o `OrcKingdomFactory`. +El cliente puede usar `FactoryMaker` para crear una factoría concreta, que a su vez, producirá diferentes objetos concretos (derivados de `Army`, `King`, `Castle`). +En este ejemplo también usamos un enum para parametrizar el tipo de factoría de reinos pedirá el cliente. + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + default -> throw new IllegalArgumentException("KingdomType not supported."); + }; + } +} + + public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + --similar use of the orc factory + } +``` + +## Diagrama de clases + +![alt text](./etc/abstract-factory.urm.png "Diagrama de Clases de Abstract Factory") + + +## Aplicación + +Usar el patrón Abstract Factory cuando + +* El sistema debe ser agnóstico a como se crean, componen y representan sus objetos. +* El sistema debe ser configurado con una de las múltiples familias de productos. +* La familia de objetos relacionados está diseñada para ser usada en conjunto y necesitas forzar esta premisa. +* Quieres proveer de una librería de productos y solo quieres revelar sus interfaces, no su implementación. +* El tiempo de vida de la dependencia es conceptualmente más corto que el del cliente. +* Necesitas un valor en tiempo de ejecución para construir una dependencia. +* Quieres decidir que producto de una familia llamar en tiempo de ejecución. +* Necesitas proveer de uno o más parámetros solo conocidos en tiempo de ejecución antes de poder resolver la dependencia. +* Necesitas consistencia entre productos. +* No quieres cambiar el código existente al añadir nuevos productos o familias de productos al programa. + +Ejemplos de casos de uso + +* Elegir llamar a la implementación correcta de FileSystemAcmeService o DatabaseAcmeService o NetworkAcmeService en tiempo de ejecución. +* Escribir test unitarios se hace mucho más sencillo. +* Herramientas UI (User Interface) para diferentes SO (Sistemas Operativos). + +## Consecuencias + +* La inyección de dependencias en java esconde las dependencias de la clase servicio lo que puede llevar a errores de ejecución que se podrían haber evitado al compilar. +* Mientras que el patrón es muy bueno creando objetos predefinidos, añadir nuevos puede ser complicado. +* El código es más complicado de lo que debería porque se añaden muchas interfaces y clases nuevas junto con el patrón. + +## Tutoriales + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## Usos conocidos + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## Patrones relacionados + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/es/abstract-factory/etc/abstract-factory.urm.png b/localization/es/abstract-factory/etc/abstract-factory.urm.png new file mode 100644 index 000000000000..836858a2c652 Binary files /dev/null and b/localization/es/abstract-factory/etc/abstract-factory.urm.png differ diff --git a/localization/es/active-object/README.md b/localization/es/active-object/README.md new file mode 100644 index 000000000000..37f4ac911835 --- /dev/null +++ b/localization/es/active-object/README.md @@ -0,0 +1,128 @@ +--- +title: Active Object +shortTitle: Active Object +category: Concurrency +language: es +tag: + - Performance +--- + + +## Propósito +El patrón de diseño de objeto activo desacopla la ejecución del método de la invocación del método para los objetos que residen en su propio hilo de control. El objetivo es introducir la concurrencia mediante el uso de la invocación de métodos asíncronos y un planificador para manejar solicitudes. + +## Explicación + +La clase que implementa el patrón de diseño de objeto activo contendrá un mecanismo de autosincronización sin utilizar métodos sincronizados (synchronized). + +Ejemplo del mundo real + +> Los orcos son conocidos por su salvajismo y filosofía de no hacer equipo. Basándonos en este comportamiento se podría decir que tienen su propio hilo de control. + +Podemos usar el patrón Active Object para implementar una criatura que tiene su propio hilo de control y exponer su API pero no la ejecución como tal. + + +**Ejemplo Programático** + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +Podemos ver que cualquier clase que extienda de ActiveCreature tendrá su propio hilo de control para invocar y ejecutar métodos. + +Por ejemplo, la clase Orc: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` + +Ahora podemos crear múltiples criaturas como los Orcos, diles que coman y deambulen y lo harán en su propio hilo de control: + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## Diagrama de clases + +![alt text](./etc/active-object.urm.png "Active Object class diagram") + +## Tutoriales + +* [Android and Java Concurrency: The Active Object Pattern](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) \ No newline at end of file diff --git a/localization/es/active-object/etc/active-object.urm.png b/localization/es/active-object/etc/active-object.urm.png new file mode 100644 index 000000000000..c14f66144ee2 Binary files /dev/null and b/localization/es/active-object/etc/active-object.urm.png differ diff --git a/localization/es/acyclic-visitor/README.md b/localization/es/acyclic-visitor/README.md new file mode 100644 index 000000000000..a4fe5e8e60d1 --- /dev/null +++ b/localization/es/acyclic-visitor/README.md @@ -0,0 +1,160 @@ +--- +title: Acyclic Visitor +shortTitle: Acyclic Visitor +category: Behavioral +language: es +tag: + - Extensibility +--- + +## Propósito + +Permitir añadir nuevas funciones a jerarquías de clases existentes sin que estas se vean afectadas, y sin crear los problemáticos círculos de dependencias que son inherentes al patrón GoF (Gang of Four) Visitor. + +## Explicación + +Ejemplo del mundo real + +> Tenemos una jerarquía de clases módem. Los modems de esta jerarquía deben ser visitados por un algoritmo externo basándose en unos filtros (el módem es compatible con Unix o DOS). + +En otras palabras + +> Acyclic Visitor permite añadir funciones a jerarquías de clases existentes sin modificarlas. + +[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) dice + +> El patrón Acyclic Visitor permite que nuevas funciones sean añadidas a jerarquías de clases existentes sin afectar a las mismas, y sin crear los círculos de dependencias que son inherentes al patrón de visitante (Visitor Pattern) de GangOfFour. + +**Ejemplo Programático** + +Aquí tenemos la jerarquía `Modem`. + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + +Después tenemos la jerarquía `ModemVisitor`. + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + ... + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + ... + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +Finalmente, aquí están los "visitors" en acción. + +```java + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + var zoom = new Zoom(); + var hayes = new Hayes(); + hayes.accept(conDos); + zoom.accept(conDos); + hayes.accept(conUnix); + zoom.accept(conUnix); +``` + +Output del programa: + +``` + // Hayes modem used with Dos configurator. + // Zoom modem used with Dos configurator. + // Only HayesVisitor is allowed to visit Hayes modem + // Zoom modem used with Unix configurator. +``` + +## Diagrama de clases + +![alt text](./etc/acyclic-visitor.png "Acyclic Visitor") + +## Aplicación + +Este patrón puede ser usado: + +* Cuando necesitas añadir una nueva función a una jerarquía de clases sin que esta se vea afectada o alterada. +* Cuando hay funciones que operan sobre la jerarquía, pero no pertenecen a la jerarquía como tal. Las clases ConfigureForDOS / ConfigureForUnix / ConfigureForX por ejemplo. +* Cuando necesitas ejecutar operaciones muy diferentes en un objeto dependiendo de su tipo. +* Cuando la jerarquía visitada va a ser frecuentemente extendida con derivados de la clase elemento. +* Cuando el proceso de volver a compilar, enlazar, probar o distribuir los derivados de la clase elemento es muy pesado. + +## Tutoriales + +* [Acyclic Visitor Pattern Example](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) + +## Consecuencias + +Buenas: + +* No hay círculos de dependencias entre las jerarquías. +* No es necesario compilar todos los visitantes si se añade uno nuevo. +* No provoca errores de compilación en visitantes existentes si la jerarquía tiene un nuevo miembro. + +Malas: + +* Viola el [Principio de sustitución de Liskov](https://java-design-patterns.com/principles/#liskov-substitution-principle) al mostrar que puede aceptar todos los visitantes solamente estando interesado en uno en particular. +* Hay que crear una jerarquía de visitantes paralela para todos los miembros de una jerarquía visitable. + +## Patrones relacionados + +* [Visitor Pattern](https://java-design-patterns.com/patterns/visitor/) + +## Créditos + +* [Acyclic Visitor by Robert C. Martin](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor in WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) diff --git a/localization/es/acyclic-visitor/etc/acyclic-visitor.png b/localization/es/acyclic-visitor/etc/acyclic-visitor.png new file mode 100644 index 000000000000..7b4df13d80f8 Binary files /dev/null and b/localization/es/acyclic-visitor/etc/acyclic-visitor.png differ diff --git a/localization/es/adapter/README.md b/localization/es/adapter/README.md new file mode 100644 index 000000000000..3f8d9eb3c5dd --- /dev/null +++ b/localization/es/adapter/README.md @@ -0,0 +1,137 @@ +--- +title: Adapter +shortTitle: Adapter +category: Structural +language: es +tag: + - Gang of Four +--- + +## También conocido como +Wrapper + +## Propósito +Convertir la interfaz de una clase en otra que espera el cliente. El patrón Adapter permite a clases funcionar en conjunto con otras clases con las que no podrían de otra forma por problemas de compatibilidad. + +## Explicación + +Ejemplo del mundo real + +> Imagina que tienes unas imágenes en una tarjeta de memoria y quieres transferirlas a tu ordenador. Para transferirlas necesitas algún tipo de adaptador compatible con los puertos de tu ordenador que te permita introducir tu tarjeta. En este caso el lector de tarjetas es un adaptador (adapter). +> Otro ejemplo podría ser el famoso adaptador de corriente; un enchufe con tres patas no se puede conectar a una toma de corriente con dos agujeros, necesita un adaptador para hacerlo compatible con la toma de corriente. +> Otro ejemplo más sería un traductor traduciendo palabras de una persona para otra. + +En otras palabras + +> El patrón Adapter permite envolver un objeto en un adaptador para hacerlo compatible con una clase con la que sería incompatible de otra manera. + +Según Wikipedia + +> En ingeniería de software el patrón Adapter es un patrón de diseño de software que permite usar la interfaz de una clase existente como otra interfaz diferente. A menudo es utilizado para hacer que clases existentes trabajen con otras clases sin necesidad de modificar su código fuente. + +**Ejemplo Programático** + +Toma como ejemplo un capitán que solo puede usar botes de remo y no puede navegar en absoluto. + +Primero tenemos las interfaces `RowingBoat` (bote de remo) y `FishingBoat` (bote de pesca). + +```java +public interface RowingBoat { + void row(); +} + +@Slf4j +public class FishingBoat { + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } +} +``` + +Y el capitán espera una implementación de la interfaz `RowingBoat` (bote de remo) para poder moverse. + +```java +public class Captain { + + private final RowingBoat rowingBoat; + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +Ahora supongamos que viene un grupo de piratas y nuestro capitán tiene que escapar, pero solo hay un bote de pesca. Necesitamos crear un adaptador que permita al capitán usar el bote de pesca con sus habilidades para usar botes de remo. + +```java +@Slf4j +public class FishingBoatAdapter implements RowingBoat { + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} +``` + +Y ahora el `Captain` (capitán) puede usar el `FishingBoat` (bote de pesca) para escapar de los piratas. + +```java +var captain = new Captain(new FishingBoatAdapter()); +captain.row(); +``` + +## Diagrama de clases +![alt text](./etc/adapter.urm.png "Adapter class diagram") + +## Aplicación +Usa el patrón Adapter cuando + +* Quieres usar una clase existente y su interfaz no coincide con la que necesitas. +* Quieres crear una clase reutilizable que coopere con clases que no están relacionadas o con las que su cooperación no estaba planeada, esto es, clases que no necesariamente tienen interfaces compatibles. +* Necesitas usar varias subclases existentes, pero no es práctico adaptar su interfaz creando subclases para todas. Un adaptador puede adaptar la interfaz de la clase padre. +* Muchas aplicaciones que usan librerías de terceros usan adaptadores como capas intermedias entre la aplicación y la librería para desacoplar la aplicación de la librería. Si es necesario usar otra librería solo hace falta crear un adaptador para la nueva librería sin necesidad de modificar el código de la aplicación. + +## Tutoriales + +* [Dzone](https://dzone.com/articles/adapter-design-pattern-in-java) +* [Refactoring Guru](https://refactoring.guru/design-patterns/adapter/java/example) +* [Baeldung](https://www.baeldung.com/java-adapter-pattern) + +## Consecuencias +Los adaptadores de clases y objetos tienen distintas cualidades. Un adaptador de clases + +* Hace la adaptación quedando enlazado a una clase adaptada concreta. Como consecuencia un adaptador de clases no funcionará cuando queramos adaptar una clase y sus subclases. +* Permite al adaptador modificar el comportamiento de la clase adaptada porque el adaptador es una subclase de la clase adaptada. +* Usa un solo objeto y no es necesario usar punteros adicionales para referenciar la clase adaptada. + +Un adaptador de objetos + +* Permite a un solo adaptador trabajar con varias clases, esto es, con la clase adaptada y todas sus subclases (si tiene alguna). El adaptador también puede añadir funcionalidad a todas las clases adaptadas a la vez. +* Hace más complicado modificar el comportamiento de la clase adaptada. Sería necesario hacer una subclase de la clase a adaptar y hacer que el adaptador referencie la subclase en lugar de la clase a adaptar. + + +## Ejemplos del mundo real + +* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +* [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +* [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/adapter/etc/adapter.urm.png b/localization/es/adapter/etc/adapter.urm.png new file mode 100644 index 000000000000..341ad67699d9 Binary files /dev/null and b/localization/es/adapter/etc/adapter.urm.png differ diff --git a/localization/es/aggregator-microservices/README.md b/localization/es/aggregator-microservices/README.md new file mode 100644 index 000000000000..71d869697825 --- /dev/null +++ b/localization/es/aggregator-microservices/README.md @@ -0,0 +1,108 @@ +--- +title: Aggregator Microservices +shortTitle: Aggregator Microservices +category: Architectural +language: es +tag: +- Cloud distributed +- Decoupling +- Microservices +--- + +## Propósito + +El usuario realiza una sola llamada al servicio del agregador y, a continuación, el agregador llama a cada microservicio relevante. + +## Explicación + +Ejemplo del mundo real + +> Nuestro mercado web necesita información sobre los productos y su inventario actual. Hace una llamada a un agregador +> servicio que a su vez llama al microservicio de información del producto y al microservicio de inventario del producto que devuelve la +> información combinada. + +En palabras sencillas + +> Aggregator Microservice recopila datos de varios microservicios y devuelve un agregado para su procesamiento. + +StackOverflow dice + +> Aggregator Microservice invoca múltiples servicios para lograr la funcionalidad requerida por la aplicación. + +**Ejemplo programático** + +Empecemos por el modelo de datos. Aquí está nuestro `Product`. + +```java +public class Product { + private String title; + private int productInventories; + // getters and setters -> + ... +} +``` + +A continuación, podemos presentar nuestro microservicio `Aggregator` (Agregador de microservicios). Contiene él `ProductInformationClient` (Información del producto del cliente) y él +`ProductInventoryClient` (Inventario del producto del cliente) de los clientes para llamar a los respectivos microservicios. + +```java +@RestController +public class Aggregator { + + @Resource + private ProductInformationClient informationClient; + + @Resource + private ProductInventoryClient inventoryClient; + + @RequestMapping(path = "/product", method = RequestMethod.GET) + public Product getProduct() { + + var product = new Product(); + var productTitle = informationClient.getProductTitle(); + var productInventory = inventoryClient.getProductInventories(); + + //Fallback to error message + product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed")); + + //Fallback to default error inventory + product.setProductInventories(requireNonNullElse(productInventory, -1)); + + return product; + } +} +``` + +Esta es la esencia de la implementación de microservicios de información. El microservicio de inventario es similar, simplemente regresa +recuentos de inventario. + +```java +@RestController +public class InformationController { + @RequestMapping(value = "/information", method = RequestMethod.GET) + public String getProductTitle() { + return "The Product Title."; + } +} +``` + +Ahora llamando a nuestra REST API `Aggregator` devuelve la información del producto. + +```bash +curl http://localhost:50004/product +{"title":"The Product Title.","productInventories":5} +``` + +## Diagrama de clase + +![alt text](./aggregator-service/etc/aggregator-service.png "Aggregator Microservice") + +## Aplicabilidad + +Utilice el patrón Agregador de microservicios (Aggregator Microservices) cuando necesite una API unificada para varios microservicios, independientemente del dispositivo cliente. + +## Créditos + +* [Patrones de diseño de microservicios] (http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/) +* [Patrones de microservicios: Con ejemplos en Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=8b4e570267bc5fb8b8189917b461dc60) +* [Patrones de arquitectura: Descubra patrones esenciales en el ámbito más indispensable de la arquitectura empresarial](https://www.amazon.com/gp/product/B077T7V8RC/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B077T7V8RC&linkId=c34d204bfe1b277914b420189f09c1a4) diff --git a/localization/es/aggregator-microservices/aggregator-service/etc/aggregator-service.png b/localization/es/aggregator-microservices/aggregator-service/etc/aggregator-service.png new file mode 100644 index 000000000000..75ee82328bbe Binary files /dev/null and b/localization/es/aggregator-microservices/aggregator-service/etc/aggregator-service.png differ diff --git a/localization/es/ambassador/README.md b/localization/es/ambassador/README.md new file mode 100644 index 000000000000..e9510ffb0869 --- /dev/null +++ b/localization/es/ambassador/README.md @@ -0,0 +1,209 @@ +--- +title: Ambassador +shortTitle: Ambassador +category: Structural +language: es +tag: + - Decoupling + - Cloud distributed +--- + +## Propósito + +Proporcionar una instancia de servicio auxiliar a un cliente y delegar en ella las funcionalidades comunes de un recurso compartido. + +## Explicación + +Ejemplo real + +> Un servicio remoto tiene muchos clientes accediendo a una función que este servicio proporciona. El servicio es una aplicación heredada y +> es imposible actualizarla. Un gran número de solicitudes por parte de los usuarios están causando problemas de conectividad. Nuevas reglas +> respecto a la frecuencia de solicitudes deberían implementarse junto con comprobaciones de latencia y registros del lado del cliente. + +En otras palabras + +> Con el patrón Ambassador, podemos implementar una menor frecuencia en solicitudes de clientes junto con comprobaciones de latencia y +> registros. + +Según la Documentación de Microsoft + +> Un servicio de Ambassador puede considerarse como un proxy fuera de proceso que coexiste con el cliente. +> +> Este patrón puede ser útil para la descarga de tareas comunes de conectividad de cliente, como la supervisión, el registro, el enrutamiento, +> la seguridad (por ejemplo, TLS) y los patrones de resistencia(*) de una manera independiente del lenguaje. A menudo se utiliza con aplicaciones heredadas, +> u otras aplicaciones que son difíciles de modificar, con el fin de ampliar sus capacidades de red. También puede +> habilitar un equipo especializado para implementar esas características. + +**Código de ejemplo** + +Con la introducción anterior en mente vamos a imitar su funcionalidad en el siguiente ejemplo. Tenemos una interface implementada +por el servicio remoto así como el servicio ambassador: + +```java +interface RemoteServiceInterface { + long doRemoteFunction(int value) throws Exception; +} +``` + +Un servicio remoto representado como un singleton (Instancia única). + +```java +@Slf4j +public class RemoteService implements RemoteServiceInterface { + private static RemoteService service = null; + + static synchronized RemoteService getRemoteService() { + if (service == null) { + service = new RemoteService(); + } + return service; + } + + private RemoteService() {} + + @Override + public long doRemoteFunction(int value) { + long waitTime = (long) Math.floor(Math.random() * 1000); + + try { + sleep(waitTime); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep interrupted", e); + } + + return waitTime >= 200 ? value * 10 : -1; + } +} +``` + +Un servicio ambassador añadiendo funcionalidades adicionales como registros, comprobación de latencia + +```java +@Slf4j +public class ServiceAmbassador implements RemoteServiceInterface { + private static final int RETRIES = 3; + private static final int DELAY_MS = 3000; + + ServiceAmbassador() { + } + + @Override + public long doRemoteFunction(int value) { + return safeCall(value); + } + + private long checkLatency(int value) { + var startTime = System.currentTimeMillis(); + var result = RemoteService.getRemoteService().doRemoteFunction(value); + var timeTaken = System.currentTimeMillis() - startTime; + + LOGGER.info("Time taken (ms): " + timeTaken); + return result; + } + + private long safeCall(int value) { + var retries = 0; + var result = (long) FAILURE; + + for (int i = 0; i < RETRIES; i++) { + if (retries >= RETRIES) { + return FAILURE; + } + + if ((result = checkLatency(value)) == FAILURE) { + LOGGER.info("Failed to reach remote: (" + (i + 1) + ")"); + retries++; + try { + sleep(DELAY_MS); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep state interrupted", e); + } + } else { + break; + } + } + return result; + } +} +``` + +Un cliente tiene un servicio ambassador local usado para interactuar con el servicio remoto: + +```java +@Slf4j +public class Client { + private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador(); + + long useService(int value) { + var result = serviceAmbassador.doRemoteFunction(value); + LOGGER.info("Service result: " + result); + return result; + } +} +``` + +A continuación dos clientes usando el servicio. + +```java +public class App { + public static void main(String[] args) { + var host1 = new Client(); + var host2 = new Client(); + host1.useService(12); + host2.useService(73); + } +} +``` + +Esta es la salida que obtendremos tras ejecutar el ejemplo: + +```java +Time taken (ms): 111 +Service result: 120 +Time taken (ms): 931 +Failed to reach remote: (1) +Time taken (ms): 665 +Failed to reach remote: (2) +Time taken (ms): 538 +Failed to reach remote: (3) +Service result: -1 +``` + +## Diagrama de clase + +![alt text](./etc/ambassador.urm.png "Ambassador class diagram") + +## Aplicaciones + +Ambassador es aplicable cuando trabajamos con un servicio remoto heredado que no puede ser modificado o que sería extremamente +difícil de modificar. Las características de conectividad pueden implementarse en el cliente sin necesidad de realizar cambios en el servicio +remoto. + +* Ambassador proporciona una interface local para un servicio remoto. +* Ambassador proporciona registros, interrupción de circuitos, reintentos y seguridad en el cliente. + +## Casos de uso típicos + +* Control de acceso a otro objeto +* Implementación de registros o logs +* Implementación de interrupciones de circuito +* Delegar tareas de servicios remotos +* Facilitar la conexión a la red + +## Usos conocidos + +* [Pasarela API Kubernetes-native para microservicios](https://github.com/datawire/ambassador) + +## Patrones relacionados + +* [Proxy](https://java-design-patterns.com/patterns/proxy/) + +## Créditos + +* [Ambassador Pattern (Documentación de Microsoft en inglés)](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador) +* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://www.amazon.com/s?k=designing+distributed+systems&sprefix=designing+distri%2Caps%2C156&linkCode=ll2&tag=javadesignpat-20&linkId=a12581e625462f9038557b01794e5341&language=en_US&ref_=as_li_ss_tl) + +## Notas del traductor +(*) La versión original en inglés de la documentación de Microsoft hace referencia al término resiliencia y +en su traducción al español lo traduce como resistencia, aunque enlaza al apartado patrones de confiabilidad. Véase: +* [Versión de la Documentación para el Patrón Ambassador de Microsoft en español.](https://learn.microsoft.com/es-es/azure/architecture/patterns/ambassador) diff --git a/localization/es/ambassador/etc/ambassador.urm.png b/localization/es/ambassador/etc/ambassador.urm.png new file mode 100644 index 000000000000..9b50a02ad356 Binary files /dev/null and b/localization/es/ambassador/etc/ambassador.urm.png differ diff --git a/localization/es/api-gateway/README.md b/localization/es/api-gateway/README.md new file mode 100644 index 000000000000..e2a7a00241fb --- /dev/null +++ b/localization/es/api-gateway/README.md @@ -0,0 +1,169 @@ +--- +title: API Gateway +shortTitle: API Gateway +category: Architectural +language: es +tag: + - Cloud distributed + - Decoupling + - Microservices +--- + +## Propósito + +Agregar llamadas a los microservicios en un mismo lugar, la puerta de enlace API (API Gateway). El usuario +hace una llamada simple a la API Gateway, y la API Gateway hace la llamada a cada microservicio relevante. + +## Explicación + +Con el patrón de microservicios, el cliente puede necesitar datos de múltiples microservicios. Si el +cliente llamara a cada microservicio de forma directe, podría ocasionar tiempos de carga largos, ya que +el cliente tendría que hacer una solicitud de red para cada microservicio llamado. Además, tener +la llamada del cliente a cada microservicio vincula directamente al cliente con ese microservicio - si la +implementacion interna del cambio de microservicios (por ejemplo, si dos microservicios se combinan en +algún momento en el futuro) o si la ubicación (host y puerto) de un microservicio cambia, entonces cada +cliente que hace uso de esos microservicios debe ser actualizado. + +La intención del patrón API Gateway es aliviar algunos de estos problemas. En el patrón API Gateway, +se coloca una entidad adicional (la API Gateway) entre el cliente y los microservicios. +El trabajo de API Gateway es agregar las llamadas a los microservicios. En lugar de que el cliente +llame a cada microservicio individualmente, el cliente llama a la API Gateway una sola vez. La API +Gateway luego llama a cada uno de los microservicios que necesita el cliente. + +Ejemplo real + +> Estamos implementando un sistema de microservicios y API Gateway para un sitio e-commerce. En este +> sistema API Gateway realiza llamadas a los microservicios Image y Price. (Imagen y Precio) + +En otras palabras + +> Para un sistema implementado utilizando una arquitectura de microservicios, API Gateway es el único +> punto de entrada que agrega las llamadas a los microservicios individuales. + +Wikipedia dice + +> API Gateway es un servidor que actúa como un front-end de API, recibe solicitudes de API, aplica la +> limitación y políticas de seguridad, pasa las solicitudes al servicio back-end y luego devuelve la +> respuesta al solicitante. Una puerta de enlace a menudo incluye un motor de transformación para +> orquestar y modificar las solicitudes y respuestas sobre la marcha. Una puerta de enlace también +> puede proporcionar funciones como recopilar análisis de datos y almacenamiento en caché. La puerta +> de enlace puede proporcionar funcionalidad para soportar autenticación, autorización, seguridad, +> auditoría y cumplimiento normativo. + +**Código de ejemplo** + +Esta implementación muestra cómo podría verse el patrón API Gateway para un sitio de e-commerce. El +`ApiGateway` hace llamadas a los microservicios Image y Price usando `ImageClientImpl` y`PriceClientImpl` +respectivamente. Los clientes que ven el sitio en un dispositivo de escritorio pueden ver la información +de precio y una imagen de un producto, entonces `ApiGateway` llama a los microservicios y +agrega los datos en el modelo `DesktopProduct`. Sin embargo, los usuarios de dispositivos móviles solo +ven información de precios, no ven una imagen del producto. Para usuarios móviles, `ApiGateway` solo +recupera el precio información, que utiliza para completar el `MobileProduct`. + +Aquí está la implementación del microservicio de imagen (Image). + +```java +public interface ImageClient { + String getImagePath(); +} + +public class ImageClientImpl implements ImageClient { + @Override + public String getImagePath() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50005/image-path")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +Aquí está la implementación del microservicio de precio (Price). + +```java +public interface PriceClient { + String getPrice(); +} + +public class PriceClientImpl implements PriceClient { + + @Override + public String getPrice() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50006/price")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +Aquí podemos ver cómo API Gateway asigna las solicitudes a los microservicios. + +```java +public class ApiGateway { + + @Resource + private ImageClient imageClient; + + @Resource + private PriceClient priceClient; + + @RequestMapping(path = "/desktop", method = RequestMethod.GET) + public DesktopProduct getProductDesktop() { + var desktopProduct = new DesktopProduct(); + desktopProduct.setImagePath(imageClient.getImagePath()); + desktopProduct.setPrice(priceClient.getPrice()); + return desktopProduct; + } + + @RequestMapping(path = "/mobile", method = RequestMethod.GET) + public MobileProduct getProductMobile() { + var mobileProduct = new MobileProduct(); + mobileProduct.setPrice(priceClient.getPrice()); + return mobileProduct; + } +} +``` + +## Diagrama de clase + +![alt text](./etc/api-gateway.png "API Gateway") + +## Aplicaciones + +Usa el patrón de API Gateway cuando + +* Estás usando una arquitectura de microservicios y necesites un único punto de agregación para las llamadas de microservicios. + +## Tutoriales + +* [Exploring the New Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway) +* [Spring Cloud - Gateway](https://www.tutorialspoint.com/spring_cloud/spring_cloud_gateway.htm) +* [Getting Started With Spring Cloud Gateway](https://dzone.com/articles/getting-started-with-spring-cloud-gateway) + +## Créditos + +* [microservices.io - API Gateway](http://microservices.io/patterns/apigateway.html) +* [NGINX - Building Microservices: Using an API Gateway](https://www.nginx.com/blog/building-microservices-using-an-api-gateway/) +* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=ac7b6a57f866ac006a309d9086e8cfbd) +* [Building Microservices: Designing Fine-Grained Systems](https://www.amazon.com/gp/product/1491950358/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1491950358&linkId=4c95ca9831e05e3f0dadb08841d77bf1) diff --git a/localization/es/api-gateway/etc/api-gateway.png b/localization/es/api-gateway/etc/api-gateway.png new file mode 100644 index 000000000000..bb3ec2e2e1a8 Binary files /dev/null and b/localization/es/api-gateway/etc/api-gateway.png differ diff --git a/localization/es/arrange-act-assert/README.md b/localization/es/arrange-act-assert/README.md new file mode 100644 index 000000000000..64e75c4cbdaf --- /dev/null +++ b/localization/es/arrange-act-assert/README.md @@ -0,0 +1,141 @@ +--- +title: Arrange/Act/Assert +shortTitle: Arrange/Act/Assert +category: Idiom +language: es +tag: + - Testing +--- + +## También conocido como + +Dado/Cuando/Entonces + +## Propósito + +Arrange/Act/Assert (AAA) es un patrón para organizar UnitTests. +Divide las UnitTests en tres pasos claros y diferenciados: + +1. Arrange(Organizar): Realiza la configuración y la inicialización necesarias para el test. +2. Act(Actuar): Toma las medidas necesarias para el test. +3. Assert(Afirmar): Verifica los resultados del test. + +## Explicación + +Este patrón tiene varios beneficios significativos. Crea una clara separación entre la configuración, operaciones y resultados de un test. Esta estructura hace que el código sea más fácil de leer y comprender. Si +colocas los pasos en orden y formateas su código para separarlos, puedes escanear un test y +comprender rápidamente lo que hace. + +También impone un cierto grado de disciplina cuando escribes tus UnitTests. Tienes que visualizar +claramente los tres pasos que tu test realizará. Esto hace que los tests sean más intuitivos de escribir a la vez que tienes presente un esquema. + +Ejemplo cotidiano + +> Necesitamos escribir un conjunto de UnitTests completo y claro para una clase. + +En otras palabras + +> Arrange/Act/Assert es un patrón de testeo que organiza las pruebas en tres pasos claros para facilitar su +> mantenimiento. + +WikiWikiWeb dice + +> Arrange/Act/Assert es un patrón para organizar y dar formato al código en los métodos UnitTest. + +**Código de ejemplo** + +Veamos primero nuestra clase `Cash` para que sea testeada. + +```java +public class Cash { + + private int amount; + + Cash(int amount) { + this.amount = amount; + } + + void plus(int addend) { + amount += addend; + } + + boolean minus(int subtrahend) { + if (amount >= subtrahend) { + amount -= subtrahend; + return true; + } else { + return false; + } + } + + int count() { + return amount; + } +} +``` + +Luego escribimos nuestras UnitTests en función del patrón Arrange/Act/Assert. Note claramente la separación de los pasos para cada UnitTest. + +```java +class CashAAATest { + + @Test + void testPlus() { + //Arrange + var cash = new Cash(3); + //Act + cash.plus(4); + //Assert + assertEquals(7, cash.count()); + } + + @Test + void testMinus() { + //Arrange + var cash = new Cash(8); + //Act + var result = cash.minus(5); + //Assert + assertTrue(result); + assertEquals(3, cash.count()); + } + + @Test + void testInsufficientMinus() { + //Arrange + var cash = new Cash(1); + //Act + var result = cash.minus(6); + //Assert + assertFalse(result); + assertEquals(1, cash.count()); + } + + @Test + void testUpdate() { + //Arrange + var cash = new Cash(5); + //Act + cash.plus(6); + var result = cash.minus(3); + //Assert + assertTrue(result); + assertEquals(8, cash.count()); + } +} +``` + +## Aplicabilidad + +Utilice el patrón Arrange/Act/Assert cuando + +* Necesitas estructurar tus UnitTests para que sean más fáciles de leer, mantener y mejorar. + +## Créditos + +* [Arrange, Act, Assert: ¿Qué son las pruebas AAA?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx) +* [Bill Wake: 3A – Arrange, Act, Assert](https://xp123.com/articles/3a-arrange-act-assert/) +* [Martin Fowler: DadoCuandoEntonces](https://martinfowler.com/bliki/GivenWhenThen.html) +* [Patrones de prueba xUnit: Refactorizando Código de prueba](https://www.amazon.com/gp/product/0131495054/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0131495054&linkId=99701e8f4af2f63d0bcf50) +* [Principios, prácticas y patrones UnitTesting](https://www.amazon.com/gp/product/1617296279/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617296279&linkId=74c75cfae3a5aaccae3a5a) +* [Desarrollo basado en pruebas: Ejemplo](https://www.amazon.com/gp/product/0321146530/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321146530&linkId=5c63a93d8c1175b47caef50875) diff --git a/localization/es/async-method-invocation/README.md b/localization/es/async-method-invocation/README.md new file mode 100644 index 000000000000..6de9b93be43f --- /dev/null +++ b/localization/es/async-method-invocation/README.md @@ -0,0 +1,169 @@ +--- +title: Async Method Invocation +shortTitle: Async Method Invocation +category: Concurrency +language: es +tag: + - Reactive +--- + +## Propósito + +Asynchronous method invocation (invocación de método asincrónico) es un patrón con el que el hilo o subproceso de llamada +no se bloquea mientras espera resultados. El patrón proporciona procesamiento en paralelo de múltiples tareas independientes y recupera los resultados a través de +devoluciones de llamada (callbacks) o esperando hasta que termine el procedimiento. + +## Explicación + +Ejemplo cotidiano + +> Lanzar cohetes espaciales es un negocio apasionante. El comandante de la misión da la orden de lanzamiento y +> después de un tiempo indeterminado, el cohete se lanza con éxito o falla miserablemente. + +En otras palabras + +> La invocación del método asíncrono inicia el procedimiento y vuelve inmediatamente antes de que la tarea termine +> Los resultados del procedimiento se devuelven a la llamada posteriormente (callback). + +Según Wikipedia + +> En la programación multiproceso, la invocación de método asíncrono (AMI), también conocida como +> llamadas de método asíncrono o el patrón asíncrono es un patrón de diseño en el que el lugar de la llamada +> no se bloquea mientras espera que termine el código llamado. En cambio, el hilo de llamada es +> notificado cuando llega la respuesta. Sondear para obtener una respuesta es una opción no deseada. + +**Ejemplo programático** + +En este ejemplo, estamos lanzando cohetes espaciales y desplegando vehículos lunares. + +La aplicación demuestra lo que hace el patrón de invocación del método asíncrono. Las partes clave del patrón son +`AsyncResult` que es un contenedor intermedio para un valor evaluado de forma asíncrona, +`AsyncCallback` que se puede proporcionar para que se ejecute al finalizar la tarea y `AsyncExecutor` que +gestiona la ejecución de las tareas asíncronas. + +```java +public interface AsyncResult { + boolean isCompleted(); + T getValue() throws ExecutionException; + void await() throws InterruptedException; +} +``` + +```java +public interface AsyncCallback { + void onComplete(T value, Optional ex); +} +``` + +```java +public interface AsyncExecutor { + AsyncResult startProcess(Callable task); + AsyncResult startProcess(Callable task, AsyncCallback callback); + T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException; +} +``` + +`ThreadAsyncExecutor` es una implementación de `AsyncExecutor`. Se destacan algunas de sus partes clave a continuación. + +```java +public class ThreadAsyncExecutor implements AsyncExecutor { + + @Override + public AsyncResult startProcess(Callable task) { + return startProcess(task, null); + } + + @Override + public AsyncResult startProcess(Callable task, AsyncCallback callback) { + var result = new CompletableResult<>(callback); + new Thread( + () -> { + try { + result.setValue(task.call()); + } catch (Exception ex) { + result.setException(ex); + } + }, + "executor-" + idx.incrementAndGet()) + .start(); + return result; + } + + @Override + public T endProcess(AsyncResult asyncResult) + throws ExecutionException, InterruptedException { + if (!asyncResult.isCompleted()) { + asyncResult.await(); + } + return asyncResult.getValue(); + } +} +``` + +Ahora está todo preparado para lanzar algunos cohetes y así poder ver cómo funciona todo. + +```java +public static void main(String[] args) throws Exception { + // construye un nuevo objeto executor que ejecutará tareas asíncronas + var executor = new ThreadAsyncExecutor(); + + // inicia algunas tareas asíncronas con diferentes tiempos de procesamiento, las dos últimas con controladores de devolución de llamada + final var asyncResult1 = executor.startProcess(lazyval(10, 500)); + final var asyncResult2 = executor.startProcess(lazyval("test", 300)); + final var asyncResult3 = executor.startProcess(lazyval(50L, 700)); + final var asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Desplegando el rover lunar")); + final var asyncResult5 = + executor.startProcess(lazyval("devolución de llamada callback", 600), callback("Desplegando el rover lunar")); + + // emula el procesamiento en el hilo o subproceso actual mientras las tareas asíncronas se ejecutan en sus propios hilos o subprocesos + Subproceso.dormir(350); // Oye, estamos trabajando duro aquí + log("El comandante de la misión está bebiendo café"); + + // espera a que se completen las tareas + final var result1 = executor.endProcess(asyncResult1); + final var result2 = executor.endProcess(asyncResult2); + final var result3 = executor.endProcess(asyncResult3); + asyncResult4.await(); + asyncResult5.await(); + + // registra los resultados de las tareas, las devoluciones de las llamadas se registran inmediatamente cuando se completan + log("Cohete espacial <" + resultado1 + "> ha completado su lanzamiento"); + log("Cohete espacial <" + resultado2 + "> ha completado su lanzamiento"); + log("Cohete espacial <" + result3 + "> ha completado su lanzamiento"); +} +``` + +Aquí está la salida de la consola del programa. + +```java +21:47:08.227 [executor-2] INFO com.iluwatar.async.method.invocation.App - Cohete espacial lanzado con éxito +21:47:08.269 [main] INFO com.iluwatar.async.method.invocation.App - El comandante de la misión está bebiendo café +21:47:08.318 [executor-4] INFO com.iluwatar.async.method.invocation.App - Cohete espacial <20> lanzado con éxito +21:47:08.335 [executor-4] INFO com.iluwatar.async.method.invocation.App Desplegando el rover lunar <20> +21:47:08.414 [executor-1] INFO com.iluwatar.async.method.invocation.App - Cohete espacial <10> lanzado con éxito +21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - Cohete espacial lanzado con éxito +21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - Implementando el vehículo lunar +21:47:08.616 [executor-3] INFO com.iluwatar.async.method.invocation.App - Cohete espacial <50> lanzado con éxito +21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - Lanzamiento del cohete espacial <10> completado +21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - Lanzamiento de cohete espacial completado +21:47:08.618 [main] INFO com.iluwatar.async.method.invocation.App - Lanzamiento del cohete espacial <50> completado +``` + +# Diagrama de clase + +![texto alternativo](./etc/async-method-invocation.png "Invocación de método asíncrono") + +## Aplicabilidad + +Utiliza el patrón de invocación del método asíncrono cuando + +* Tienes múltiples tareas independientes que pueden ejecutarse en paralelo +* Necesitas mejorar el desempeño de un grupo de tareas secuenciales +* Tienes una cantidad limitada de capacidad de procesamiento o tareas de ejecución prolongada y la llamada no debe esperar a que las tareas estén listas + +## Ejemplos cotidianos + +* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html) +* [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) +* [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) +* [Patrón asíncrono basado en tareas](https://msdn.microsoft.com/en-us/library/hh873175.aspx) \ No newline at end of file diff --git a/localization/es/async-method-invocation/etc/async-method-invocation.png b/localization/es/async-method-invocation/etc/async-method-invocation.png new file mode 100644 index 000000000000..764895d7a217 Binary files /dev/null and b/localization/es/async-method-invocation/etc/async-method-invocation.png differ diff --git a/localization/es/balking/README.md b/localization/es/balking/README.md new file mode 100644 index 000000000000..2bf1433eab37 --- /dev/null +++ b/localization/es/balking/README.md @@ -0,0 +1,138 @@ +--- +title: Balking +shortTitle: Balking +category: Concurrency +language: es +tag: + - Decoupling +--- + +## Propósito + +El patrón _Balking_ se utiliza para prevenir que un objeto ejecute un código determinado si +este se encuentra en un estado incompleto o inapropiado. + +## Explicación + +Ejemplo del mundo real + +> En una lavadora hay un botón de arranque para iniciar el lavado de ropa. Cuando la lavadora +> está inactiva el botón funciona como se espera, pero si ya está lavando entonces el botón no hace +> nada. + +En otras palabras + +> Usando el patrón _Balking_, un código determinado se ejecuta solo si el objeto está en un estado concreto. + +Wikipedia dice + +> El patrón _Balking_ es un patrón de diseño de software que ejecuta una acción en un objeto solamente cuando +> el objeto está en un estado concreto. Por ejemplo, si un objeto lee archivos ZIP y un método de llamada +> invoca un método _get_ en el objeto cuando el archivo ZIP no está abierto, el objeto "rechazaría" (_balk_) +> la petición. + +**Ejemplo Programático** + +En este ejemplo de implementación, `WashingMachine` es un objeto que tiene dos estados los cuales pueden +ser: _ENABLED_ y _WASHING_ (ACTIVADA y LAVANDO respectivamente). Si la máquina está _ENABLED_, el estado +cambia a _WASHING_ usando un método thread-safe a prueba de hilos. Por otra parte, si ya está lavando y +cualquier otro hilo ejecuta `wash()` entonces no hará ningún cambio de estado y finalizará la ejecución del +método sin hacer nada. + +Aquí están las partes relevantes de la clase `WashingMachine`. + +```java +@Slf4j +public class WashingMachine { + + private final DelayProvider delayProvider; + private WashingMachineState washingMachineState; + + public WashingMachine(DelayProvider delayProvider) { + this.delayProvider = delayProvider; + this.washingMachineState = WashingMachineState.ENABLED; + } + + public WashingMachineState getWashingMachineState() { + return washingMachineState; + } + + public void wash() { + synchronized (this) { + var machineState = getWashingMachineState(); + LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState); + if (this.washingMachineState == WashingMachineState.WASHING) { + LOGGER.error("Cannot wash if the machine has been already washing!"); + return; + } + this.washingMachineState = WashingMachineState.WASHING; + } + LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); + this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing); + } + + public synchronized void endOfWashing() { + washingMachineState = WashingMachineState.ENABLED; + LOGGER.info("{}: Washing completed.", Thread.currentThread().getId()); + } +} +``` + +Aquí la sencilla interfaz `DelayProvider` utilizada por `WashingMachine`. + +```java +public interface DelayProvider { + void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task); +} +``` + +Ahora introducimos la aplicación utilizando `WashingMachine`. + +```java +public static void main(String... args) { + final var washingMachine = new WashingMachine(); + var executorService = Executors.newFixedThreadPool(3); + for (int i = 0; i < 3; i++) { + executorService.execute(washingMachine::wash); + } + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + LOGGER.error("ERROR: Waiting on executor service shutdown!"); + Thread.currentThread().interrupt(); + } +} +``` + +Aquí está la salida en consola de la aplicación. + +``` +14:02:52.268 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Actual machine state: ENABLED +14:02:52.272 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Doing the washing +14:02:52.272 [pool-1-thread-3] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-3: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-3] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.273 [pool-1-thread-1] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-1: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-1] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.324 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - 14: Washing completed. +``` + +## Diagrama de clases + +![alt text](./etc/balking.png "Balking") + +## Aplicabilidad + +Usa el patrón _Balking_ cuando + +* Un objeto debe ejecutar un código determinado sólo cuando se encuentra en un estado concreto. +* Los objetos están en un estado que es propenso a bloquearse temporalmente, pero durante una cantidad de tiempo indeterminada. + +## Patrones relacionados + +* [Guarded Suspension Pattern](https://java-design-patterns.com/patterns/guarded-suspension/) +* [Double Checked Locking Pattern](https://java-design-patterns.com/patterns/double-checked-locking/) + +## Referencias + +* [Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML, 2nd Edition, Volume 1](https://www.amazon.com/gp/product/0471227293/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0471227293&linkId=0e39a59ffaab93fb476036fecb637b99) diff --git a/localization/es/balking/etc/balking.png b/localization/es/balking/etc/balking.png new file mode 100644 index 000000000000..f409eaacbb95 Binary files /dev/null and b/localization/es/balking/etc/balking.png differ diff --git a/localization/es/bridge/README.md b/localization/es/bridge/README.md new file mode 100644 index 000000000000..e04d94225f8e --- /dev/null +++ b/localization/es/bridge/README.md @@ -0,0 +1,224 @@ +--- +title: Bridge +shortTitle: Bridge +category: Structural +language: es +tag: + - Gang of Four +--- + +## También conocido como + +Handle/Body + +## Intención + +Desacoplar una abstracción de su implementación para que ambas puedan variar de forma independiente. + +## Explicación + +Real-world example + +> Imagina que tienes un arma con diferentes encantamientos, y se supone que debes permitir la mezcla de diferentes armas +> con diferentes encantamientos. ¿Qué harías? ¿Crearías múltiples copias de cada una de las armas para cada uno de los +> encantamientos o simplemente crearías un encantamiento separado y lo establecerías para el arma según sea necesario? +> El +> patrón Bridge te permite hacer lo segundo. + +En palabras sencillas + +> El patrón Bridge se trata de preferir la composición sobre la herencia. Los detalles de implementación se empujan de +> una jerarquía a otro objeto con una jerarquía separada. + +Wikipedia dice + +> El patrón bridge es un patrón de diseño utilizado en ingeniería de software que tiene como objetivo "desacoplar una +> abstracción de su implementación para que las dos puedan variar independientemente" + +**Ejemplo programático** + +Transladando nuestro ejemplo de arma de arriba. Aquí tenemos la interfaz arma `Weapon`: + +```java +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; + } +} +``` + +Aquí está la interfaz de encantamientos `Enchantment` separada: + +```java +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."); + } +} +``` + +Aquí están ambas interfaces en acción: + +```java +LOGGER.info("The knight receives an enchanted sword."); +var enchantedSword = new Sword(new SoulEatingEnchantment()); +enchantedSword.wield(); +enchantedSword.swing(); +enchantedSword.unwield(); + +LOGGER.info("The valkyrie receives an enchanted hammer."); +var hammer = new Hammer(new FlyingEnchantment()); +hammer.wield(); +hammer.swing(); +hammer.unwield(); +``` + +Aquí está la salida en consola. + +``` +The knight receives an enchanted sword. +The sword is wielded. +The item spreads bloodlust. +The sword is swung. +The item eats the soul of enemies. +The sword is unwielded. +Bloodlust slowly disappears. +The valkyrie receives an enchanted hammer. +The hammer is wielded. +The item begins to glow faintly. +The hammer is swung. +The item flies and strikes the enemies finally returning to owner's hand. +The hammer is unwielded. +The item's glow fades. +``` + +## Diagrama de Clases + +![alt text](./etc/bridge.urm.png "Bridge diagrama de clases") + +## Aplicabilidad + +Usa el patrón Bridge cuando + +* Quieres evitar una vinculación permanente entre una abstracción y su implementación. Este podría ser el caso, por + ejemplo, cuando la implementación debe ser seleccionada o cambiada en tiempo de ejecución. +* Tanto las abstracciones como sus implementaciones deberían ser extensibles mediante la herencia. En este caso, el + patrón Bridge te permite combinar las diferentes abstracciones e implementaciones y extenderlas de forma + independiente. +* Los cambios en la implementación de una abstracción no deberían tener impacto en los clientes; es decir, su código no + debería tener que ser recompilado. +* Tienes una proliferación de clases. Tal jerarquía de clases indica la necesidad de dividir un objeto en dos partes. + Rumbaugh usa el término "generalizaciones anidadas" para referirse a tales jerarquías de clases. +* Quieres compartir una implementación entre varios objetos (quizás usando conteo de referencias), y este hecho debería + ser ocultado al cliente. Un ejemplo simple es la clase String de Coplien, en la que varios objetos pueden compartir la + misma representación de cadena. + +## Tutoriales + +* [Bridge Pattern Tutorial](https://www.journaldev.com/1491/bridge-design-pattern-java) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) \ No newline at end of file diff --git a/localization/es/bridge/etc/bridge.urm.png b/localization/es/bridge/etc/bridge.urm.png new file mode 100644 index 000000000000..785585bf8163 Binary files /dev/null and b/localization/es/bridge/etc/bridge.urm.png differ diff --git a/localization/es/builder/README.md b/localization/es/builder/README.md new file mode 100644 index 000000000000..955b8e55d700 --- /dev/null +++ b/localization/es/builder/README.md @@ -0,0 +1,159 @@ +--- +title: Builder +shortTitle: Builder +category: Creational +language: es +tag: + - Gang of Four +--- + +## Propósito + +Separar la construcción de un objeto complejo de su representación para que el mismo proceso de +construcción pueda crear diferentes representaciones. + +## Explicación + +Ejemplo real + +> Imagina un generador de personajes para un juego de rol. La opción más fácil es dejar que el ordenador +> cree el personaje por ti. Si quieres seleccionar manualmente los detalles del personaje como +> profesión, sexo, color de pelo, etc. la generación del personaje se convierte en un proceso paso a paso que +> se completa cuando todas las selecciones están listas. + +En pocas palabras + +> Permite crear diferentes sabores de un objeto evitando la contaminación del constructor. Útil +> cuando puede haber varios sabores de un objeto. O cuando hay muchos pasos involucrados en la creación de un objeto. +> creación de un objeto. + +Wikipedia dice + +> El patrón constructor es un patrón de diseño de software de creación de objetos con la intención de encontrar +> una solución al anti-patrón del constructor telescópico. + + +Dicho esto, permíteme agregar un poco sobre qué es el anti-patrón del constructor telescópico. En algún momento +u otro, todos hemos visto un constructor como el siguiente: + +```java +public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) { +} +``` + +Como puedes ver, el número de parámetros del constructor puede salirse rápidamente de control, y puede volverse difícil +entender la disposición de los parámetros. Además, esta lista de parámetros podría seguir creciendo si quisieras agregar +más opciones en el futuro. A esto se le llama anti-patrón del constructor telescópico. + +**Ejemplo programático** + +La alternativa sensata es utilizar el patrón Builder. En primer lugar, tenemos a nuestro héroe `Hero` que queremos +crear: + +```java +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; + } +} +``` + +Luego tenemos al constructor: + +```java + 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); + } + } +``` + +Entonces se puede utilizar como: + +```java +var mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build(); +``` + +## Diagrama de clases + +![alt text](./etc/builder.urm.png "Builder diagrama de clases") + +## Aplicabilidad + +Utiliza el patrón Builder cuando + +* El algoritmo para crear un objeto complejo debe ser independiente de las partes que componen el objeto y cómo se + ensamblan. +* El proceso de construcción debe permitir diferentes representaciones para el objeto que se construye. + +## Tutoriales + +* [Refactoring Guru](https://refactoring.guru/design-patterns/builder) +* [Oracle Blog](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) +* [Journal Dev](https://www.journaldev.com/1425/builder-design-pattern-in-java) + +## Usos en el mundo real + +* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) +* [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) así como otros + buffers + como FloatBuffer, IntBuffer, etc. +* [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) +* Todas las implementaciones + de [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) +* [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/builder/etc/builder.urm.png b/localization/es/builder/etc/builder.urm.png new file mode 100644 index 000000000000..d77808d36097 Binary files /dev/null and b/localization/es/builder/etc/builder.urm.png differ diff --git a/localization/es/business-delegate/README.md b/localization/es/business-delegate/README.md new file mode 100644 index 000000000000..8f606c1bbd7f --- /dev/null +++ b/localization/es/business-delegate/README.md @@ -0,0 +1,203 @@ +--- +title: Business Delegate +shortTitle: Business Delegate +category: Structural +language: es +tag: + - Decoupling +--- + +## Propósito + +El patrón Business Delegate añade una capa de abstracción entre los niveles de presentación y de negocio. Al utilizar +este patrón, conseguimos un acoplamiento flexible entre los niveles y encapsulamos el conocimiento sobre cómo localizar, +conectar e interactuar con los objetos de negocio que componen la aplicación. + +## También conocido como + +Service Representative + +## Explicación + +Ejemplo del mundo real + +> Una aplicación para teléfonos móviles promete transmitir a tu dispositivo cualquier película existente. Captura la +> cadena de búsqueda del usuario y se la pasa al Delegado de Negocio. El Delegado de Negocio selecciona el +> servicio de streaming de vídeo más adecuado y reproduce el vídeo. + +En pocas palabras + +> Business Delegate añade una capa de abstracción entre los niveles de presentación y de negocio. + +Wikipedia dice + +> Business Delegate es un patrón de diseño de Java EE. Este patrón está dirigido a reducir el acoplamiento entre los +> servicios de negocio y el nivel de presentación conectado, y para ocultar los detalles de implementación de los +> servicios (incluyendo la búsqueda y la accesibilidad de la arquitectura EJB). Los delegados de negocio actúan como un +> adaptador para invocar objetos de negocio desde la capa de presentación. + +**Ejemplo programático** + +En primer lugar, tenemos una abstracción para los servicios de streaming de vídeo `VideoStreamingService` y un par de +implementaciones `NetflixService` y `YouTubeService`. + +```java +public interface VideoStreamingService { + void doProcessing(); +} + +@Slf4j +public class NetflixService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("NetflixService is now processing"); + } +} + +@Slf4j +public class YouTubeService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("YouTubeService is now processing"); + } +} +``` + +A continuación, tenemos un servicio de búsqueda `BusinessLookup` que decide qué servicio de transmisión de vídeo +utilizar. + +```java + +@Setter +public class BusinessLookup { + + private NetflixService netflixService; + private YouTubeService youTubeService; + + public VideoStreamingService getBusinessService(String movie) { + if (movie.toLowerCase(Locale.ROOT).contains("die hard")) { + return netflixService; + } else { + return youTubeService; + } + } +} +``` + +El Delegado de Negocio `BusinessDelegate` utiliza una búsqueda de negocio para dirigir las solicitudes de reproducción +de películas a un servicio de streaming de vídeo adecuado. + +```java + +@Setter +public class BusinessDelegate { + + private BusinessLookup lookupService; + + public void playbackMovie(String movie) { + VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie); + videoStreamingService.doProcessing(); + } +} +``` + +El cliente móvil `MobileClient` utiliza Business Delegate para llamar al nivel de negocio. + +```java +public class MobileClient { + + private final BusinessDelegate businessDelegate; + + public MobileClient(BusinessDelegate businessDelegate) { + this.businessDelegate = businessDelegate; + } + + public void playbackMovie(String movie) { + businessDelegate.playbackMovie(movie); + } +} +``` + +Por último, podemos demostrar el ejemplo completo en acción. + +```java + public static void main(String[]args){ + + // preparar los objetos + var businessDelegate=new BusinessDelegate(); + var businessLookup=new BusinessLookup(); + businessLookup.setNetflixService(new NetflixService()); + businessLookup.setYouTubeService(new YouTubeService()); + businessDelegate.setLookupService(businessLookup); + + // crear el cliente y utilizar el Business Delegate + var client=new MobileClient(businessDelegate); + client.playbackMovie("Die Hard 2"); + client.playbackMovie("Maradona: The Greatest Ever"); + } +``` + +Aquí está la salida de la consola. + +``` +21:15:33.790 [main] INFO com.iluwatar.business.delegate.NetflixService - NetflixService is now processing +21:15:33.794 [main] INFO com.iluwatar.business.delegate.YouTubeService - YouTubeService is now processing +``` + +## Diagrama de clases + +![Diagrama de clases](./etc/business-delegate.urm.png "Business Delegate") + +## Patrones relacionados + +* [Patrón de localización de servicios](https://java-design-patterns.com/patterns/service-locator/) + +## Aplicabilidad + +Utilice el patrón Business Delegate cuando + +* Desea un acoplamiento flexible entre los niveles de presentación y de negocio. +* Quieres orquestar llamadas a múltiples servicios de negocio +* Se desea encapsular las búsquedas y llamadas a servicios. +* Es necesario abstraer y encapsular la comunicación entre la capa cliente y los servicios de negocio. + +## Tutoriales + +* [Patrón Delegado de Negocio en TutorialsPoint](https://www.tutorialspoint.com/design_pattern/business_delegate_pattern.htm) + +## Usos conocidos + +* Aplicaciones empresariales que utilicen Java EE (Java Platform, Enterprise Edition) +* Aplicaciones que requieren acceso remoto a servicios empresariales + +## Consecuencias + +Ventajas: + +* Desacoplamiento de los niveles de presentación y de negocio: Permite que el nivel de cliente y los servicios + empresariales evolucionen de forma independiente. +* Transparencia de ubicación: Los clientes no se ven afectados por cambios en la ubicación o la instanciación de los + servicios de negocio. +* Reutilización y escalabilidad: Los objetos Business Delegate pueden ser reutilizados por múltiples clientes, y el + patrón soporta el equilibrio de carga y la escalabilidad. + carga y escalabilidad. + +Contrapartidas: + +* Complejidad: Introduce capas y abstracciones adicionales que pueden aumentar la complejidad. +* Sobrecarga de rendimiento: La indirección adicional puede suponer una ligera penalización en el rendimiento. + +## Patrones relacionados + +* [Localizador de servicios](https://java-design-patterns.com/patterns/service-locator/): El Delegado de Negocio ( + Business Delegate) utiliza el Localizador de Servicios (Service Locator) para localizar servicios de negocio. +* [Fachada de Sesión](https://java-design-patterns.com/patterns/session-facade/): El Delegado de Negocio (Business + Delegate) puede utilizar la Fachada de Sesión (Session Facade) para proporcionar una interfaz unificada a un conjunto + de servicios de negocio. +* [Entidad Compuesta](https://java-design-patterns.com/patterns/composite-entity/): El Delegado (Business Delegate) de + Negocio puede utilizar Entidad Compuesta (Composite Entity) para gestionar el estado de los servicios de negocio. + +## Créditos + +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Core J2EE Patterns: Best Practices and Design Strategies](https://www.amazon.com/gp/product/0130648841/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0130648841&linkId=a0100de2b28c71ede8db1757fb2b5947) diff --git a/localization/es/business-delegate/etc/business-delegate.urm.png b/localization/es/business-delegate/etc/business-delegate.urm.png new file mode 100644 index 000000000000..4dca6c263b99 Binary files /dev/null and b/localization/es/business-delegate/etc/business-delegate.urm.png differ diff --git a/localization/es/bytecode/README.md b/localization/es/bytecode/README.md new file mode 100644 index 000000000000..35cf357f429e --- /dev/null +++ b/localization/es/bytecode/README.md @@ -0,0 +1,256 @@ +--- +title: Bytecode +shortTitle: Bytecode +category: Behavioral +language: es +tag: + - Game programming +--- + +## Propósito + +Permite codificar el comportamiento como instrucciones para una máquina virtual. + +## Explicación + +Ejemplo del mundo real + +> Un equipo está trabajando en un nuevo juego en el que los magos luchan entre sí. El comportamiento de los magos necesita ser cuidadosamente ajustado e iterado cientos de veces a través de pruebas de juego. No es óptimo pedir al programador que haga cambios cada vez que el diseñador del juego quiere variar el comportamiento, así que el comportamiento del mago se implementa como una máquina virtual basada en datos. + +En palabras sencillas + +> El patrón Bytecode permite un comportamiento dirigido por datos en lugar de por código. + +[Gameprogrammingpatterns.com](https://gameprogrammingpatterns.com/bytecode.html) indica la documentación: + +> Un conjunto de instrucciones define las operaciones de bajo nivel que pueden realizarse. Una serie de instrucciones se codifica como una secuencia de bytes. Una máquina virtual ejecuta estas instrucciones de una en una, utilizando una pila para los valores intermedios. La combinación de instrucciones permite definir comportamientos complejos de alto nivel. + +**Ejemplo programático** + +Uno de los objetos más importantes del juego es la clase Mago `Wizard`. + +```java + +@AllArgsConstructor +@Setter +@Getter +@Slf4j +public class Wizard { + + private int health; + private int agility; + private int wisdom; + private int numberOfPlayedSounds; + private int numberOfSpawnedParticles; + + public void playSound() { + LOGGER.info("Playing sound"); + numberOfPlayedSounds++; + } + + public void spawnParticles() { + LOGGER.info("Spawning particles"); + numberOfSpawnedParticles++; + } +} +``` + +A continuación, mostramos las instrucciones disponibles para nuestra máquina virtual. Cada una de las instrucciones tiene su propia semántica sobre cómo opera con los datos de la pila. Por ejemplo, la instrucción ADD toma los dos elementos superiores de la pila, los suma y coloca el resultado en la pila. + +```java + +@AllArgsConstructor +@Getter +public enum Instruction { + + LITERAL(1), // e.g. "LITERAL 0", push 0 to stack + SET_HEALTH(2), // e.g. "SET_HEALTH", pop health and wizard number, call set health + SET_WISDOM(3), // e.g. "SET_WISDOM", pop wisdom and wizard number, call set wisdom + SET_AGILITY(4), // e.g. "SET_AGILITY", pop agility and wizard number, call set agility + PLAY_SOUND(5), // e.g. "PLAY_SOUND", pop value as wizard number, call play sound + SPAWN_PARTICLES(6), // e.g. "SPAWN_PARTICLES", pop value as wizard number, call spawn particles + GET_HEALTH(7), // e.g. "GET_HEALTH", pop value as wizard number, push wizard's health + GET_AGILITY(8), // e.g. "GET_AGILITY", pop value as wizard number, push wizard's agility + GET_WISDOM(9), // e.g. "GET_WISDOM", pop value as wizard number, push wizard's wisdom + ADD(10), // e.g. "ADD", pop 2 values, push their sum + DIVIDE(11); // e.g. "DIVIDE", pop 2 values, push their division + // ... +} +``` + +En el corazón de nuestro ejemplo está la clase `VirtualMachine`. Toma instrucciones como entrada y las ejecuta para proporcionar el comportamiento del objeto de juego. + +```java + +@Getter +@Slf4j +public class VirtualMachine { + + private final Stack stack = new Stack<>(); + + private final Wizard[] wizards = new Wizard[2]; + + public VirtualMachine() { + wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), + 0, 0); + wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), + 0, 0); + } + + public VirtualMachine(Wizard wizard1, Wizard wizard2) { + wizards[0] = wizard1; + wizards[1] = wizard2; + } + + public void execute(int[] bytecode) { + for (var i = 0; i < bytecode.length; i++) { + Instruction instruction = Instruction.getInstruction(bytecode[i]); + switch (instruction) { + case LITERAL: + // Read the next byte from the bytecode. + int value = bytecode[++i]; + // Push the next value to stack + stack.push(value); + break; + case SET_AGILITY: + var amount = stack.pop(); + var wizard = stack.pop(); + setAgility(wizard, amount); + break; + case SET_WISDOM: + amount = stack.pop(); + wizard = stack.pop(); + setWisdom(wizard, amount); + break; + case SET_HEALTH: + amount = stack.pop(); + wizard = stack.pop(); + setHealth(wizard, amount); + break; + case GET_HEALTH: + wizard = stack.pop(); + stack.push(getHealth(wizard)); + break; + case GET_AGILITY: + wizard = stack.pop(); + stack.push(getAgility(wizard)); + break; + case GET_WISDOM: + wizard = stack.pop(); + stack.push(getWisdom(wizard)); + break; + case ADD: + var a = stack.pop(); + var b = stack.pop(); + stack.push(a + b); + break; + case DIVIDE: + a = stack.pop(); + b = stack.pop(); + stack.push(b / a); + break; + case PLAY_SOUND: + wizard = stack.pop(); + getWizards()[wizard].playSound(); + break; + case SPAWN_PARTICLES: + wizard = stack.pop(); + getWizards()[wizard].spawnParticles(); + break; + default: + throw new IllegalArgumentException("Invalid instruction value"); + } + LOGGER.info("Executed " + instruction.name() + ", Stack contains " + getStack()); + } + } + + public void setHealth(int wizard, int amount) { + wizards[wizard].setHealth(amount); + } + // other setters -> + // ... +} +``` + +Ahora podemos mostrar el ejemplo completo utilizando la máquina virtual. + +```java + public static void main(String[]args){ + + var vm=new VirtualMachine( + new Wizard(45,7,11,0,0), + new Wizard(36,18,8,0,0)); + + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_HEALTH")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_AGILITY")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_WISDOM")); + vm.execute(InstructionConverterUtil.convertToByteCode("ADD")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 2")); + vm.execute(InstructionConverterUtil.convertToByteCode("DIVIDE")); + vm.execute(InstructionConverterUtil.convertToByteCode("ADD")); + vm.execute(InstructionConverterUtil.convertToByteCode("SET_HEALTH")); + } +``` + +Aquí está la salida de la consola. + +``` +16:20:10.193 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0] +16:20:10.196 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_HEALTH, Stack contains [0, 45] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_AGILITY, Stack contains [0, 45, 7] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 7, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_WISDOM, Stack contains [0, 45, 7, 11] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 45, 18] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 18, 2] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed DIVIDE, Stack contains [0, 45, 9] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 54] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed SET_HEALTH, Stack contains [] +``` + +## Diagrama de clases + +![alt text](./etc/bytecode.urm.png "Bytecode class diagram") + +## Aplicabilidad + +Utiliza el patrón Bytecode cuando tengas que definir muchos comportamientos y el lenguaje de implementación de tu juego no sea el adecuado porque: + +* Es demasiado de bajo nivel, por lo que es tedioso o propenso a errores para programar. +* Iterar en él lleva demasiado tiempo debido a tiempos de compilación lentos u otros problemas de herramientas. +* Tiene demasiada confianza. Si quieres asegurarte de que el comportamiento definido no puede romper el juego, necesitas separarlo del resto del código base. + +## Usos Conocidos + +* Java Virtual Machine (JVM) utiliza bytecode para permitir que los programas Java se ejecuten en cualquier dispositivo que tenga JVM instalado. +* Python compila sus scripts a bytecode que luego es interpretado por la Máquina Virtual Python. +* NET Framework utiliza una forma de bytecode llamada Microsoft Intermediate Language (MSIL). + +## Consecuencias + +Ventajas: + +* Portabilidad: Los programas pueden ejecutarse en cualquier plataforma que disponga de una máquina virtual compatible. +* Seguridad: La máquina virtual puede aplicar controles de seguridad al código de bytes. +* Rendimiento: Los compiladores JIT pueden optimizar el código de bytes en tiempo de ejecución, mejorando potencialmente el rendimiento respecto al código interpretado. + +Desventajas: + +* Sobrecarga: Ejecutar bytecode normalmente implica más sobrecarga que ejecutar código nativo, lo que puede afectar al rendimiento. +* Complejidad: Implementar y mantener una máquina virtual añade complejidad al sistema. + +## Patrones relacionados + +* [Intérprete](https://java-design-patterns.com/patterns/interpreter/) se utiliza a menudo dentro de la implementación de VMs para interpretar instrucciones bytecode. +* [Comando](https://java-design-patterns.com/patterns/command/): Las instrucciones bytecode pueden ser vistas como comandos ejecutados por la VM. +* [Método de fábrica](https://java-design-patterns.com/patterns/factory-method/): Las VMs pueden utilizar métodos de fábrica para instanciar operaciones o instrucciones definidas en el bytecode. + +## Créditos + +* [Game programming patterns](http://gameprogrammingpatterns.com/bytecode.html) +* [Programming Language Pragmatics](https://amzn.to/49Tusnn) diff --git a/localization/es/bytecode/etc/bytecode.urm.png b/localization/es/bytecode/etc/bytecode.urm.png new file mode 100644 index 000000000000..51335fa0a4b4 Binary files /dev/null and b/localization/es/bytecode/etc/bytecode.urm.png differ diff --git a/localization/es/chain-of-responsibility/README.md b/localization/es/chain-of-responsibility/README.md new file mode 100644 index 000000000000..1c36af8e75cf --- /dev/null +++ b/localization/es/chain-of-responsibility/README.md @@ -0,0 +1,201 @@ +--- +title: Chain of responsibility +shortTitle: Chain of responsibility +category: Behavioral +language: es +tag: + - Gang of Four + - Decoupling +--- + +## También conocido como + +* Chain of Command +* Chain of Objects +* Responsibility Chain + +## Propósito + +Evita acoplar el emisor de una petición a su receptor dando a más de un objeto la oportunidad de gestionar la petición. Encadena los objetos receptores y pasa la solicitud a lo largo de la cadena hasta que un objeto la gestione. + +## Explicación + +Ejemplo real + +> El Rey Orco da órdenes en voz alta a su ejército. El más cercano a reaccionar es el comandante, luego un oficial y después un soldado. El comandante, el oficial y el soldado forman una cadena de responsabilidad. + +En palabras sencillas + +> Ayuda a construir una cadena de objetos. Una solicitud entra por un extremo y sigue pasando de un objeto a otro hasta que encuentra un gestor adecuado. + +Wikipedia dice + +> En diseño orientado a objetos, el patrón de cadena de responsabilidad es un patrón de diseño que consiste en una fuente de objetos de comando y una serie de objetos de procesamiento. Cada objeto de procesamiento contiene lógica que define los tipos de objetos de comando que puede manejar; el resto se pasa al siguiente objeto de procesamiento de la cadena. + +**Ejemplo programático** + +Traduciendo nuestro ejemplo con los orcos de arriba. Primero, tenemos la clase `Request`: + +```java +import lombok.Getter; + +@Getter +public class Request { + + private final RequestType requestType; + private final String requestDescription; + private boolean handled; + + public Request(final RequestType requestType, final String requestDescription) { + this.requestType = Objects.requireNonNull(requestType); + this.requestDescription = Objects.requireNonNull(requestDescription); + } + + public void markHandled() { + this.handled = true; + } + + @Override + public String toString() { + return getRequestDescription(); + } +} + +public enum RequestType { + DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX +} +``` + +A continuación, mostramos la jerarquía del gestor de peticiones. + +```java +public interface RequestHandler { + + boolean canHandleRequest(Request req); + + int getPriority(); + + void handle(Request req); + + String name(); +} + +@Slf4j +public class OrcCommander implements RequestHandler { + @Override + public boolean canHandleRequest(Request req) { + return req.getRequestType() == RequestType.DEFEND_CASTLE; + } + + @Override + public int getPriority() { + return 2; + } + + @Override + public void handle(Request req) { + req.markHandled(); + LOGGER.info("{} handling request \"{}\"", name(), req); + } + + @Override + public String name() { + return "Orc commander"; + } +} + +// OrcOfficer and OrcSoldier are defined similarly as OrcCommander + +``` + +El Rey Orco da las órdenes y forma la cadena. + +```java +public class OrcKing { + + private List handlers; + + public OrcKing() { + buildChain(); + } + + private void buildChain() { + handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier()); + } + + public void makeRequest(Request req) { + handlers + .stream() + .sorted(Comparator.comparing(RequestHandler::getPriority)) + .filter(handler -> handler.canHandleRequest(req)) + .findFirst() + .ifPresent(handler -> handler.handle(req)); + } +} +``` + +La cadena de responsabilidad en acción. + +```java +var king=new OrcKing(); + king.makeRequest(new Request(RequestType.DEFEND_CASTLE,"defend castle")); + king.makeRequest(new Request(RequestType.TORTURE_PRISONER,"torture prisoner")); + king.makeRequest(new Request(RequestType.COLLECT_TAX,"collect tax")); +``` + +La salida de la consola. + +``` +Orc commander handling request "defend castle" +Orc officer handling request "torture prisoner" +Orc soldier handling request "collect tax" +``` + +## Diagrama de clases + +![alt text](./etc/chain-of-responsibility.urm.png "Diagrama de clases de la cadena de responsabilidad") + +## Aplicabilidad + +Utilice Cadena de Responsabilidad cuando + +* Más de un objeto puede gestionar una petición, y el gestor no se conoce a priori. El gestor debe determinarse automáticamente. +* Se desea enviar una petición a uno de varios objetos sin especificar explícitamente el receptor. +* El conjunto de objetos que pueden gestionar una solicitud debe especificarse dinámicamente. + +## Usos conocidos + +* Burbujeo de eventos en frameworks GUI donde un evento puede ser manejado en múltiples niveles de la jerarquía de un componente UI. +* Frameworks de middleware en los que una petición pasa a través de una cadena de objetos de procesamiento. +* Marcos de trabajo de registro donde los mensajes pueden pasar a través de una serie de registradores, cada uno posiblemente manejándolos de manera diferente. +* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) +* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) +* [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-) + +## Consecuencias + +Ventajas: + +* Acoplamiento reducido. El emisor de una petición no necesita conocer el manejador concreto que procesará la petición. +* Mayor flexibilidad a la hora de asignar responsabilidades a los objetos. Se pueden añadir o cambiar responsabilidades para gestionar una petición cambiando los miembros y el orden de la cadena. +* Permite establecer un gestor por defecto si no hay ningún gestor concreto que pueda gestionar la solicitud. + +Desventajas: + +* Puede ser difícil depurar y entender el flujo, especialmente si la cadena es larga y compleja. +* La petición puede quedar sin gestionar si la cadena no incluye un gestor "catch-all". +* Pueden surgir problemas de rendimiento debido a la posibilidad de pasar por varios gestores antes de encontrar el correcto, o no encontrarlo en absoluto. + +## Patrones Relacionados + +* [Comando](https://java-design-patterns.com/patterns/command/): puede ser usado para encapsular una petición como un objeto, que puede ser pasado a lo largo de la cadena. +* [Composite](https://java-design-patterns.com/patterns/composite/): la Cadena de Responsabilidad se aplica a menudo junto con el patrón Composite. +* [Decorator](https://java-design-patterns.com/patterns/decorator/): los decoradores pueden encadenarse de forma similar a las responsabilidades en el patrón Cadena de responsabilidad. + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3PAJUg5) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) +* [Pattern languages of program design 3](https://amzn.to/4a4NxTH) diff --git a/localization/es/chain-of-responsibility/etc/chain-of-responsibility.urm.png b/localization/es/chain-of-responsibility/etc/chain-of-responsibility.urm.png new file mode 100644 index 000000000000..af1bd105455b Binary files /dev/null and b/localization/es/chain-of-responsibility/etc/chain-of-responsibility.urm.png differ diff --git a/localization/es/client-session/README.md b/localization/es/client-session/README.md new file mode 100644 index 000000000000..d032bd6db8d5 --- /dev/null +++ b/localization/es/client-session/README.md @@ -0,0 +1,117 @@ +--- +title: Client Session +shortTitle: Client Session +category: Behavioral +language: es +tags: + - Session management + - Web development +--- + +## También conocido como + +* User session + +## Propósito + +El patrón de diseño Client Session tiene como objetivo mantener el estado y los datos de un usuario a través de múltiples peticiones dentro de una aplicación web, asegurando una experiencia de usuario continua y personalizada. + +## Explicación + +Ejemplo real + +> Quieres crear una aplicación de gestión de datos que permita a los usuarios enviar peticiones al servidor para modificar y realizar cambios en los datos almacenados en sus dispositivos. Estas peticiones son pequeñas y los datos son individuales para cada usuario, negando la necesidad de una implementación de base de datos a gran escala. Utilizando el patrón de sesión de cliente, se pueden gestionar múltiples peticiones simultáneas, equilibrando la carga de clientes entre diferentes servidores con facilidad debido a que los servidores permanecen sin estado. También se elimina la necesidad de almacenar identificadores de sesión en el lado del servidor debido a que los clientes proporcionan toda la información que un servidor necesita para realizar su proceso. + +En pocas palabras + +> En lugar de almacenar información sobre el cliente actual y la información a la que se está accediendo en el servidor, se mantiene sólo en el lado del cliente. El cliente tiene que enviar datos de sesión con cada solicitud al servidor y tiene que enviar un estado actualizado de vuelta al cliente, que se almacena en la máquina del cliente. El servidor no tiene que almacenar la información del cliente. ([ref](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client)) + +**Ejemplo programático** + +Aquí está el código de ejemplo para describir el patrón cliente-sesión. En el siguiente código estamos creando primero una instancia del Servidor. Esta instancia del servidor se utilizará entonces para obtener objetos Session para dos clientes. Como puedes ver en el siguiente código, el objeto Session puede ser utilizado para almacenar cualquier información relevante que sea requerida por el servidor para procesar la petición del cliente. Estos objetos Session serán pasados con cada Request al servidor. La solicitud tendrá el objeto Session que almacena los detalles relevantes del cliente junto con los datos requeridos para procesar la solicitud. La información de sesión en cada solicitud ayuda al servidor a identificar al cliente y procesar la solicitud en consecuencia. + +```java +public class App { + + public static void main(String[] args) { + var server = new Server("localhost", 8080); + var session1 = server.getSession("Session1"); + var session2 = server.getSession("Session2"); + var request1 = new Request("Data1", session1); + var request2 = new Request("Data2", session2); + server.process(request1); + server.process(request2); + } +} + +@Data +@AllArgsConstructor +public class Session { + + /** + * Session id. + */ + private String id; + + /** + * Client name. + */ + private String clientName; + +} + +@Data +@AllArgsConstructor +public class Request { + + private String data; + + private Session session; + +} +``` + +## Diagrama de arquitectura + +![alt text](./etc/session_state_pattern.png "Session State Pattern") + +## Aplicabilidad + +Utilice el patrón de estado del cliente cuando: + +* Aplicaciones web que requieran autenticación y autorización del usuario. +* Aplicaciones que necesiten realizar un seguimiento de las actividades y preferencias del usuario a lo largo de múltiples peticiones o visitas. +* Sistemas donde los recursos del servidor necesitan ser optimizados descargando la gestión del estado al lado del cliente. + +## Usos conocidos + +* Sitios web de comercio electrónico para rastrear el contenido de la cesta de la compra a lo largo de las sesiones. +* Plataformas en línea que ofrecen contenidos personalizados basados en las preferencias y el historial del usuario. +* Aplicaciones web que requieren el inicio de sesión del usuario para acceder a contenidos personalizados o seguros. + +## Consecuencias + +Beneficios: + +* Mejora del rendimiento del servidor al reducir la necesidad de almacenar el estado del usuario en el servidor. +* Mejora de la experiencia del usuario a través de contenidos personalizados y navegación fluida a través de las diferentes partes de la aplicación. +* Flexibilidad en la gestión de sesiones a través de varios mecanismos de almacenamiento del lado del cliente (por ejemplo, cookies, Web Storage API). + +Desventajas: + +* Riesgos potenciales de seguridad si se almacena información sensible en las sesiones del cliente sin el cifrado y la validación adecuados. +* Dependencia de las capacidades y ajustes del cliente, como las políticas de cookies, que pueden variar según el navegador y la configuración del usuario. +* Mayor complejidad en la lógica de gestión de sesiones, especialmente en la gestión de la caducidad, renovación y sincronización de sesiones en varios dispositivos o pestañas. + +## Patrones relacionados + +* Sesión Servidor: A menudo se utiliza junto con el patrón Client Session para proporcionar un equilibrio entre la eficiencia del lado del cliente y el control del lado del servidor. +* [Singleton](https://java-design-patterns.com/patterns/singleton/): Asegurar una única instancia de la sesión de un usuario en toda la aplicación. +* [Estado](https://java-design-patterns.com/patterns/state/): Gestionar las transiciones de estado en una sesión, como los estados autenticado, invitado o caducado. + +## Créditos + +* [DZone - Practical PHP patterns](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client) +* [Client Session State Design Pattern - Ram N Java](https://www.youtube.com/watch?v=ycOSj9g41pc) +* [Professional Java for Web Applications](https://amzn.to/4aazY59) +* [Securing Web Applications with Spring Security](https://amzn.to/3PCCEA1) diff --git a/localization/es/client-session/etc/session_state_pattern.png b/localization/es/client-session/etc/session_state_pattern.png new file mode 100644 index 000000000000..f1e23be95766 Binary files /dev/null and b/localization/es/client-session/etc/session_state_pattern.png differ diff --git a/localization/es/collecting-parameter/README.md b/localization/es/collecting-parameter/README.md new file mode 100644 index 000000000000..b54c4ba80d80 --- /dev/null +++ b/localization/es/collecting-parameter/README.md @@ -0,0 +1,220 @@ +--- +title: Collecting Parameter +shortTitle: Collecting Parameter +category: Behavioral +language: es +tag: + - Accumulation + - Generic +--- + +## También conocido como + +* Collector +* Accumulator + +## Propósito + +Su objetivo es simplificar los métodos que recopilan información pasando un único objeto de colección a través de varias llamadas a métodos, permitiéndoles añadir resultados a esta colección en lugar de que cada método cree su propia colección. + +## Explicación + +### Ejemplo del mundo real + +Dentro de un gran edificio corporativo, existe una cola de impresión global que es una colección de todos los trabajos de impresión que están actualmente pendientes. Las diferentes plantas contienen diferentes modelos de impresoras, cada una con una política de impresión diferente. Debemos construir un programa que pueda añadir continuamente trabajos de impresión apropiados a una colección, que se llama el *parámetro de recogida*. + +### En palabras sencillas + +En lugar de tener un método gigante que contenga numerosas políticas para recoger información en una variable, podemos crear numerosas funciones más pequeñas que tomen cada parámetro, y añadan nueva información. Podemos pasar el parámetro a todas estas funciones más pequeñas y al final, tendremos lo que queríamos originalmente. Esta vez, el código es más limpio y fácil de entender. Debido a que la función más grande se ha dividido, el código también es más fácil de modificar ya que los cambios se localizan en las funciones más pequeñas. + +### Wikipedia dice + +En el modismo de Parámetros de Recolección una colección (lista, mapa, etc.) se pasa repetidamente como parámetro a un método que añade elementos a la colección. + +### Ejemplo programático + +Codificando nuestro ejemplo anterior, podemos utilizar la colección `resultado` como parámetro recolector. Se implementan las siguientes restricciones: + +- Si un papel A4 es de color, también debe ser de una sola cara. Se aceptan todos los demás papeles no coloreados. +- El papel A3 no debe ser de color y debe ser de una sola cara. +- El papel A2 debe ser de una sola página, a una cara y sin colorear. + +```java +package com.iluwatar.collectingparameter; + +import java.util.LinkedList; +import java.util.Queue; + +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + /* + Initialising the printer queue with jobs + */ + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A2, 5, false, false)); + + /* + This variable is the collecting parameter. + */ + var result = new LinkedList(); + + /* + * Using numerous sub-methods to collaboratively add information to the result collecting parameter + */ + addA4Papers(result); + addA3Papers(result); + addA2Papers(result); + } +} +``` + +Utilizamos los métodos `addA4Paper`, `addA3Paper` y `addA2Paper` para rellenar el parámetro de recogida `result` con los trabajos de impresión adecuados según la política descrita anteriormente. Las tres políticas se codifican a continuación, + +```java +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + + /** + * Adds A4 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA4Papers(Queue printerItemsCollection) { + /* + Iterate through the printer queue, and add A4 papers according to the correct policy to the collecting parameter, + which is 'printerItemsCollection' in this case. + */ + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A4)) { + var isColouredAndSingleSided = + nextItem.isColour && !nextItem.isDoubleSided; + if (isColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } else if (!nextItem.isColour) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A3 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate + * the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA3Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A3)) { + + // Encoding the policy into a Boolean: the A3 paper cannot be coloured and double-sided at the same time + var isNotColouredAndSingleSided = + !nextItem.isColour && !nextItem.isDoubleSided; + if (isNotColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A2 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate + * the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA2Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A2)) { + + // Encoding the policy into a Boolean: the A2 paper must be single page, single-sided, and non-coloured. + var isNotColouredSingleSidedAndOnePage = + nextItem.pageCount == 1 && + !nextItem.isDoubleSided + && !nextItem.isColour; + if (isNotColouredSingleSidedAndOnePage) { + printerItemsCollection.add(nextItem); + } + } + } + } +} +``` + +Cada método toma como argumento un parámetro de recogida. A continuación, añade elementos, tomados de una variable global, a este parámetro de recogida si cada elemento satisface un criterio determinado. Estos métodos pueden tener la política que desee el cliente. + +En este ejemplo de programación, se añaden tres trabajos de impresión a la cola. Sólo los dos primeros trabajos de impresión deben añadirse al parámetro de recogida según la política. Los elementos de la variable `result` después de la ejecución son, + +| paperSize | pageCount | isDoubleSided | isColour | +|-----------|-----------|---------------|----------| +| A4 | 5 | false | false | +| A3 | 2 | false | false | + +que es lo que esperábamos. + +## Diagrama de clases + +![alt text](./etc/collecting-parameter.urm.png "Collecting Parameter") + +## Aplicabilidad + +Utilice el patrón de diseño Recopilación de parámetros cuando + +- Cuando múltiples métodos producen una colección de resultados y quieres agregar estos resultados de una manera unificada. +- En escenarios donde reducir el número de colecciones creadas por métodos puede mejorar la eficiencia de memoria y el rendimiento. +- Al refactorizar métodos grandes que realizan varias tareas, incluida la recopilación de resultados de varias operaciones. + +## Tutoriales + +Los tutoriales para este método se encuentran en: + +- [Refactoring To Patterns](http://www.tarrani.net/RefactoringToPatterns.pdf) por Joshua Kerivsky +- [Smalltalk Best Practice Patterns](https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf) por Kent Beck + +## Usos conocidos + +Joshua Kerivsky da un ejemplo real en su libro 'Refactoring to Patterns'. Da un ejemplo de uso del patrón de diseño "Collecting Parameter" para crear un método `toString()` para un árbol XML. Sin utilizar este patrón de diseño, esto requeriría una función voluminosa con condicionales y concatenación que empeoraría la legibilidad del código. Un método de este tipo puede dividirse en métodos más pequeños, cada uno de los cuales añade su propio conjunto de información al parámetro de recogida. Véase esto en [Refactoring To Patterns](http://www.tarrani.net/RefactoringToPatterns.pdf). + +Otros ejemplos son: + +- Agregar mensajes de error o fallos de validación en un proceso de validación complejo. +- Recopilar elementos o información mientras se recorre una estructura de datos compleja. +- Refactorización de funcionalidades de informes complejas en las que varias partes de un informe se generan mediante métodos diferentes. + +## Consecuencias + +Ventajas: + +- Reduce la duplicación de código centralizando el manejo de las colecciones en un único lugar. +- Mejora la claridad y la capacidad de mantenimiento al hacer explícito dónde y cómo se recogen los resultados. +- Mejora el rendimiento al minimizar la creación y gestión de múltiples objetos de recopilación. + +Desventajas: + +- Aumenta el acoplamiento entre el invocador y los métodos invocados, ya que deben ponerse de acuerdo sobre la colección a utilizar. +- Puede introducir efectos secundarios en los métodos si no se gestionan con cuidado, ya que los métodos ya no son autónomos en su gestión de resultados. + +## Patrones relacionados + +- [Composite](https://java-design-patterns.com/patterns/composite/): Puede utilizarse junto con Collecting Parameter cuando se trabaja con estructuras jerárquicas, permitiendo que los resultados se recojan a través de una estructura compuesta. +- [Visitante](https://java-design-patterns.com/patterns/visitor/): A menudo se utiliza conjuntamente, donde Visitor se encarga de recorrer y realizar operaciones en una estructura, y Collecting Parameter acumula los resultados. +- [Comando](https://java-design-patterns.com/patterns/command/): Los comandos pueden utilizar el parámetro de recopilación para agregar resultados de varias operaciones ejecutadas por los objetos de comando. + +## Créditos + +- [Refactoring To Patterns](http://www.tarrani.net/RefactoringToPatterns.pdf) by Joshua Kerivsky +- [Smalltalk Best Practice Patterns](https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf) by Kent Beck +- [Wiki](https://wiki.c2.com/?CollectingParameter) +- [Refactoring: Improving the Design of Existing Code](https://amzn.to/3TVEgaB) +- [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/4aApLP0) diff --git a/localization/es/collecting-parameter/etc/collecting-parameter.urm.png b/localization/es/collecting-parameter/etc/collecting-parameter.urm.png new file mode 100644 index 000000000000..785d6ecc2da1 Binary files /dev/null and b/localization/es/collecting-parameter/etc/collecting-parameter.urm.png differ diff --git a/localization/es/command/README.md b/localization/es/command/README.md new file mode 100644 index 000000000000..a67e974d0087 --- /dev/null +++ b/localization/es/command/README.md @@ -0,0 +1,244 @@ +--- +title: Command +shortTitle: Command +category: Behavioral +language: es +tag: + - Gang of Four +--- + +## También conocido como + +* Action +* Transaction + +## Propósito + +El patrón de diseño Command encapsula una petición como un objeto, permitiendo así la parametrización de clientes con colas, peticiones y operaciones. También permite soportar operaciones deshechas. + +## Explicación + +Ejemplo real + +> Hay un mago lanzando hechizos sobre un goblin. Los hechizos se ejecutan sobre el duende uno a uno. El primer hechizo encoge al duende y el segundo lo hace invisible. A continuación, el mago invierte los hechizos uno a uno. Cada hechizo es un objeto de comando que se puede deshacer. + +En palabras simples: + +> Almacenar peticiones como objetos de comando permite realizar una acción o deshacerla en un momento posterior. + +Wikipedia dice: + +> En programación orientada a objetos, el patrón de comandos es un patrón de diseño de comportamiento en el que un objeto se utiliza para encapsular toda la información necesaria para realizar una acción o desencadenar un evento en un momento posterior. + +**Ejemplo programático** + +Aquí está el código de ejemplo con mago `Wizard` y duende `Goblin`. Empecemos por la clase Mago `Wizard`. + +```java + +@Slf4j +public class Wizard { + + private final Deque undoStack = new LinkedList<>(); + private final Deque redoStack = new LinkedList<>(); + + public Wizard() { + } + + public void castSpell(Runnable runnable) { + runnable.run(); + undoStack.offerLast(runnable); + } + + public void undoLastSpell() { + if (!undoStack.isEmpty()) { + var previousSpell = undoStack.pollLast(); + redoStack.offerLast(previousSpell); + previousSpell.run(); + } + } + + public void redoLastSpell() { + if (!redoStack.isEmpty()) { + var previousSpell = redoStack.pollLast(); + undoStack.offerLast(previousSpell); + previousSpell.run(); + } + } + + @Override + public String toString() { + return "Wizard"; + } +} +``` + +A continuación, tenemos al duende `Goblin` que es el objetivo `Target` de los hechizos. + +```java + +@Slf4j +public abstract class Target { + + private Size size; + + private Visibility visibility; + + public Size getSize() { + return size; + } + + public void setSize(Size size) { + this.size = size; + } + + public Visibility getVisibility() { + return visibility; + } + + public void setVisibility(Visibility visibility) { + this.visibility = visibility; + } + + @Override + public abstract String toString(); + + public void printStatus() { + LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); + } +} + +public class Goblin extends Target { + + public Goblin() { + setSize(Size.NORMAL); + setVisibility(Visibility.VISIBLE); + } + + @Override + public String toString() { + return "Goblin"; + } + + public void changeSize() { + var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL; + setSize(oldSize); + } + + public void changeVisibility() { + var visible = getVisibility() == Visibility.INVISIBLE + ? Visibility.VISIBLE : Visibility.INVISIBLE; + setVisibility(visible); + } +} +``` + +Por último, tenemos al mago en la función principal lanzando hechizos. + +```java +public static void main(String[]args){ + var wizard=new Wizard(); + var goblin=new Goblin(); + + // casts shrink/unshrink spell + wizard.castSpell(goblin::changeSize); + + // casts visible/invisible spell + wizard.castSpell(goblin::changeVisibility); + + // undo and redo casts + wizard.undoLastSpell(); + wizard.redoLastSpell(); +``` + +Este es el ejemplo en acción. + +```java +var wizard=new Wizard(); + var goblin=new Goblin(); + + goblin.printStatus(); + wizard.castSpell(goblin::changeSize); + goblin.printStatus(); + + wizard.castSpell(goblin::changeVisibility); + goblin.printStatus(); + + wizard.undoLastSpell(); + goblin.printStatus(); + + wizard.undoLastSpell(); + goblin.printStatus(); + + wizard.redoLastSpell(); + goblin.printStatus(); + + wizard.redoLastSpell(); + goblin.printStatus(); +``` + +Aquí está la salida del programa: + +```java +Goblin,[size=normal][visibility=visible] + Goblin,[size=small][visibility=visible] + Goblin,[size=small][visibility=invisible] + Goblin,[size=small][visibility=visible] + Goblin,[size=normal][visibility=visible] + Goblin,[size=small][visibility=visible] + Goblin,[size=small][visibility=invisible] +``` + +## Diagrama de clases + +![alt text](./etc/command.png "Command") + +## Aplicabilidad + +Utilice el patrón Comando (Command) para: + +* Parametrizar objetos mediante una acción a realizar. Puedes expresar dicha parametrización en un lenguaje procedimental con una función callback, es decir, una función que se registra en algún lugar para ser llamada en un momento posterior. Los comandos son un sustituto orientado a objetos de las retrollamadas. +* Especifican, ponen en cola y ejecutan peticiones en diferentes momentos. Un objeto Command puede tener una vida independiente de la petición original. Si el receptor de una petición puede ser representado de una manera independiente del espacio de direcciones, entonces puedes transferir un objeto comando para la petición a un proceso diferente y cumplir la petición allí. +* Soporta deshacer. La operación de ejecución del comando puede almacenar el estado para revertir sus efectos en el propio comando. La interfaz del Comando debe tener una operación añadida de des-ejecutar que revierta los efectos de una llamada previa a ejecutar. Los comandos ejecutados se almacenan en una lista de historial. La funcionalidad de deshacer y rehacer a nivel ilimitado se consigue recorriendo esta lista hacia atrás y hacia delante llamando a un-ejecutar y ejecutar, respectivamente. +* Soporta el registro de cambios para que puedan volver a aplicarse en caso de caída del sistema. Al aumentar la interfaz de comandos con operaciones de carga y almacenamiento, puede mantener un registro persistente de los cambios. La recuperación de un fallo implica volver a cargar los comandos registrados desde el disco y volver a ejecutarlos con la operación de ejecución. +* Estructurar un sistema en torno a operaciones de alto nivel construidas sobre operaciones primitivas. Esta estructura es común en los sistemas de información que admiten transacciones. Una transacción encapsula un conjunto de cambios de datos. El patrón Command ofrece una forma de modelar las transacciones. Los comandos tienen una interfaz común que permite invocar todas las transacciones de la misma manera. El patrón también facilita la ampliación del sistema con nuevas transacciones. +* Mantener un historial de peticiones. +* Implementar la funcionalidad de callback. +* Implementar la funcionalidad de deshacer. + +## Usos conocidos + +* Botones GUI y elementos de menú en aplicaciones de escritorio. +* Operaciones en sistemas de bases de datos y sistemas transaccionales que soportan rollback. +* Grabación de macros en aplicaciones como editores de texto y hojas de cálculo. +* [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) +* [org.junit.runners.model.Statement](https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/model/Statement.java) +* [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki) +* [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html) + +## Consecuencias + +Ventajas: + +* Desacopla el objeto que invoca la operación del que sabe cómo realizarla. +* Es fácil añadir nuevos Comandos, porque no tienes que cambiar las clases existentes. +* Puedes ensamblar un conjunto de comandos en un comando compuesto. + +Desventajas: + +* Aumenta el número de clases para cada comando individual. +* Puede complicar el diseño al añadir múltiples capas entre emisores y receptores. + +## Patrones Relacionados + +* [Composite](https://java-design-patterns.com/patterns/composite/): Los comandos pueden ser compuestos usando el patrón Composite para crear macro comandos. +* [Memento](https://java-design-patterns.com/patterns/memento/): Puede usarse para implementar mecanismos de deshacer. +* [Observador](https://java-design-patterns.com/patterns/observer/): El patrón puede ser observado para cambios que activan comandos. + +## Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3PFUqSY) diff --git a/localization/es/command/etc/command.png b/localization/es/command/etc/command.png new file mode 100644 index 000000000000..0f026464ecc4 Binary files /dev/null and b/localization/es/command/etc/command.png differ diff --git a/localization/es/commander/README.md b/localization/es/commander/README.md new file mode 100644 index 000000000000..c46e8e5b3faa --- /dev/null +++ b/localization/es/commander/README.md @@ -0,0 +1,132 @@ +--- +title: Commander +shortTitle: Commander +category: Behavioral +language: es +tag: + - Cloud distributed + - Microservices + - Transactions +--- + +## También conocido como + +* Distributed Transaction Commander +* Transaction Coordinator + +## Propósito + +La intención del patrón Commander en el contexto de las transacciones distribuidas es gestionar y coordinar transacciones complejas a través de múltiples componentes o servicios distribuidos, asegurando la consistencia e integridad de la transacción global. Encapsula comandos de transacciones y lógica de coordinación, facilitando la implementación de protocolos de transacciones distribuidas como commit de dos fases o Saga. + +## Explicación + +Ejemplo real + +> Imagine que organiza un gran festival internacional de música en el que están programadas actuaciones de varios grupos de todo el mundo. La llegada, la prueba de sonido y la actuación de cada grupo son como transacciones individuales en un sistema distribuido. El organizador del festival actúa como el "Comandante", coordinando estas transacciones para garantizar que si el vuelo de una banda se retrasa (similar a un fallo de transacción), hay un plan de respaldo, como reprogramar o intercambiar franjas horarias con otra banda (acciones compensatorias), para mantener intacto el programa general. Esta configuración refleja el patrón del Comandante en las transacciones distribuidas, en las que varios componentes deben coordinarse para lograr un resultado satisfactorio a pesar de los fallos individuales. + +En palabras sencillas + +> El patrón Commander convierte una petición en un objeto independiente, permitiendo la parametrización de comandos, la puesta en cola de acciones y la implementación de operaciones de deshacer. + +**Ejemplo programático** + +La gestión de transacciones a través de diferentes servicios en un sistema distribuido, como una plataforma de comercio electrónico con microservicios separados de Pago y Envío, requiere una cuidadosa coordinación para evitar problemas. Cuando un usuario realiza un pedido pero un servicio (por ejemplo, Pago) no está disponible mientras que el otro (por ejemplo, Envío) está listo, necesitamos una solución robusta para manejar esta discrepancia. + +Una estrategia para resolver este problema consiste en utilizar un componente Commander que orqueste el proceso. Inicialmente, el pedido es procesado por el servicio disponible (Envío en este caso). A continuación, el comandante intenta sincronizar el pedido con el servicio no disponible en ese momento (Pago) almacenando los detalles del pedido en una base de datos o poniéndolo en cola para su procesamiento futuro. Este sistema de colas también debe tener en cuenta posibles fallos al añadir solicitudes a la cola. + +El comandante intenta repetidamente procesar los pedidos en cola para garantizar que ambos servicios reflejen finalmente los mismos datos de transacción. Este proceso implica garantizar la idempotencia, lo que significa que incluso si la misma solicitud de sincronización de pedidos se realiza varias veces, sólo se ejecutará una vez, evitando transacciones duplicadas. El objetivo es lograr una coherencia final entre los servicios, en la que todos los sistemas se sincronicen a lo largo del tiempo a pesar de los fallos o retrasos iniciales. + +En el código proporcionado, el patrón Commander se utiliza para manejar transacciones distribuidas a través de múltiples servicios (PaymentService, ShippingService, MessagingService, EmployeeHandle). Cada servicio tiene su propia base de datos y puede lanzar excepciones para simular fallos. + +La clase Commander es la parte central de este patrón. Toma instancias de todos los servicios y sus bases de datos, junto con algunos parámetros de configuración. El método placeOrder de la clase Commander se utiliza para realizar un pedido, lo que implica interactuar con todos los servicios. + +```java +public class Commander { + // ... constructor and other methods ... + + public void placeOrder(Order order) { + // ... implementation ... + } +} +``` + +Las clases Usuario y Pedido representan un usuario y un pedido respectivamente. Un pedido lo realiza un usuario. + +```java +public class User { + // ... constructor and other methods ... +} + +public class Order { + // ... constructor and other methods ... +} +``` + +Cada servicio (por ejemplo, PaymentService, ShippingService, MessagingService, EmployeeHandle) tiene su propia base de datos y puede lanzar excepciones para simular fallos. Por ejemplo, el PaymentService puede lanzar una DatabaseUnavailableException si su base de datos no está disponible. + +```java +public class PaymentService { + // ... constructor and other methods ... +} +``` + +Las clases DatabaseUnavailableException, ItemUnavailableException y ShippingNotPossibleException representan diferentes tipos de excepciones que pueden ocurrir. + +```java +public class DatabaseUnavailableException extends Exception { + // ... constructor and other methods ... +} + +public class ItemUnavailableException extends Exception { + // ... constructor and other methods ... +} + +public class ShippingNotPossibleException extends Exception { + // ... constructor and other methods ... +} +``` + +En el método principal de cada clase (AppQueueFailCases, AppShippingFailCases), se simulan diferentes escenarios creando instancias de la clase Commander con diferentes configuraciones y llamando al método placeOrder. + +## Diagrama de clases + +![alt text](./etc/commander.urm.png "Commander class diagram") + +## Aplicabilidad + +Utilice el patrón Commander para transacciones distribuidas cuando: + +* Necesites asegurar la consistencia de los datos entre servicios distribuidos en caso de fallos parciales del sistema. +* Las transacciones abarcan múltiples microservicios o componentes distribuidos que requieren un commit o rollback coordinado. +* Está implementando transacciones de larga duración que requieren acciones compensatorias para la reversión. + +## Usos conocidos + +* Protocolos Two-Phase Commit (2PC): Coordinación de commit o rollback a través de bases de datos o servicios distribuidos. +* Implementaciones del patrón Saga: Gestión de procesos de negocio de larga duración que abarcan múltiples microservicios, con cada paso teniendo una acción compensatoria para la reversión. +* Transacciones distribuidas en arquitectura de microservicios: Coordinación de operaciones complejas entre microservicios manteniendo la integridad y consistencia de los datos. + +## Consecuencias + +Beneficios: + +* Proporciona un mecanismo claro para gestionar transacciones distribuidas complejas, mejorando la fiabilidad del sistema. +* Permite la implementación de transacciones compensatorias, que son cruciales para mantener la coherencia en transacciones de larga duración. +* Facilita la integración de sistemas heterogéneos en un contexto transaccional. + +Contrapartidas: + +* Aumenta la complejidad, especialmente en situaciones de fallo, debido a la necesidad de mecanismos de reversión coordinados. +* Potencialmente afecta al rendimiento debido a la sobrecarga de la coordinación y las comprobaciones de coherencia. +* Las implementaciones basadas en Saga pueden llevar a una mayor complejidad en la comprensión del flujo global del proceso de negocio. + +## Patrones relacionados + +[Saga Pattern](https://java-design-patterns.com/patterns/saga/): A menudo se discute junto con el patrón Commander para transacciones distribuidas, centrándose en transacciones de larga duración con acciones compensatorias. + +## Créditos + +* [Distributed Transactions: The Icebergs of Microservices](https://www.grahamlea.com/2016/08/distributed-transactions-microservices-icebergs/) +* [Microservices Patterns: With examples in Java](https://amzn.to/4axjnYW) +* [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/4axHwOV) +* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/4aATcRe) diff --git a/localization/es/commander/etc/commander.urm.png b/localization/es/commander/etc/commander.urm.png new file mode 100644 index 000000000000..6b5ebba75bd6 Binary files /dev/null and b/localization/es/commander/etc/commander.urm.png differ diff --git a/localization/es/composite-entity/README.md b/localization/es/composite-entity/README.md new file mode 100644 index 000000000000..d3a908312e09 --- /dev/null +++ b/localization/es/composite-entity/README.md @@ -0,0 +1,173 @@ +--- +title: Composite Entity +shortTitle: Composite Entity +category: Structural +language: es +tag: + - Client-server + - Data access + - Enterprise patterns +--- + +## También conocido como + +* Coarse-Grained Entity + +## Propósito + +El patrón de diseño Entidad Compuesta tiene como objetivo gestionar un conjunto de objetos persistentes +interrelacionados como si fueran una única entidad. Se utiliza comúnmente en el contexto de Enterprise JavaBeans (EJB) y +marcos empresariales similares para representar estructuras de datos basadas en gráficos dentro de modelos de negocio, +permitiendo a los clientes tratarlos como una sola unidad. + +## Explicación + +Ejemplo real + +> En una consola, puede haber muchas interfaces que necesiten ser gestionadas y controladas. Usando el patrón de entidad +> compuesta, objetos dependientes como mensajes y señales pueden ser combinados y controlados usando un único objeto. + +En palabras sencillas + +> El patrón de entidad compuesta permite representar y gestionar un conjunto de objetos relacionados mediante un objeto +> unificado. + +**Ejemplo programático** + +Necesitamos una solución genérica para el problema. Para ello, vamos a introducir un patrón genérico de entidad +compuesta. + +```java +public abstract class DependentObject { + + T data; + + public void setData(T message) { + this.data = message; + } + + public T getData() { + return data; + } +} + +public abstract class CoarseGrainedObject { + + DependentObject[] dependentObjects; + + public void setData(T... data) { + IntStream.range(0, data.length).forEach(i -> dependentObjects[i].setData(data[i])); + } + + public T[] getData() { + return (T[]) Arrays.stream(dependentObjects).map(DependentObject::getData).toArray(); + } +} + +``` + +La entidad compuesta especializada `consola` hereda de esta clase base de la siguiente manera. + +```java +public class MessageDependentObject extends DependentObject { + +} + +public class SignalDependentObject extends DependentObject { + +} + +public class ConsoleCoarseGrainedObject extends CoarseGrainedObject { + + @Override + public String[] getData() { + super.getData(); + return new String[] { + dependentObjects[0].getData(), dependentObjects[1].getData() + }; + } + + public void init() { + dependentObjects = new DependentObject[] { + new MessageDependentObject(), new SignalDependentObject()}; + } +} + +public class CompositeEntity { + + private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); + + public void setData(String message, String signal) { + console.setData(message, signal); + } + + public String[] getData() { + return console.getData(); + } +} +``` + +Gestionando ahora la asignación de objetos mensaje y señal con la entidad compuesta `consola`. + +```java +var console=new CompositeEntity(); + console.init(); + console.setData("No Danger","Green Light"); + Arrays.stream(console.getData()).forEach(LOGGER::info); + console.setData("Danger","Red Light"); + Arrays.stream(console.getData()).forEach(LOGGER::info); +``` + +## Diagrama de clases + +![alt text](./etc/composite_entity.urm.png "Patrón de entidad compuesta") + +## Aplicabilidad + +* Útil en aplicaciones empresariales donde los objetos de negocio son complejos e involucran varios objetos + interdependientes. +* Ideal para escenarios donde los clientes necesitan trabajar con una interfaz unificada para un conjunto de objetos en + lugar de entidades individuales. +* Aplicable en sistemas que requieren una vista simplificada de un modelo de datos complejo para clientes o servicios + externos. + +## Usos conocidos + +* Aplicaciones empresariales con modelos de negocio complejos, particularmente aquellas que utilizan EJB o marcos + empresariales similares. +* Sistemas que requieren abstracción sobre esquemas de bases de datos complejos para simplificar las interacciones con + los clientes. +* Aplicaciones que necesitan reforzar la consistencia o las transacciones a través de múltiples objetos en una entidad + de negocio. + +## Consecuencias + +Ventajas: + +* Simplifica las interacciones del cliente con modelos de entidad complejos proporcionando una interfaz unificada. +* Mejora la reutilización y el mantenimiento de la capa de negocio al desacoplar el código del cliente de los complejos + componentes internos de las entidades de negocio. +* Facilita la gestión de transacciones y la aplicación de la coherencia en un conjunto de objetos relacionados. + +Contrapartidas: + +* Puede introducir un nivel de indirección que podría afectar al rendimiento. +* Puede dar lugar a interfaces de grano demasiado grueso que podrían no ser tan flexibles para todas las necesidades de + los clientes. +* Requiere un diseño cuidadoso para evitar entidades compuestas hinchadas que sean difíciles de gestionar. + +## Patrones relacionados + +* [Decorador](https://java-design-patterns.com/patterns/decorator/): Para añadir dinámicamente comportamiento a objetos + individuales dentro de la entidad compuesta sin afectar a la estructura. +* [Fachada](https://java-design-patterns.com/patterns/facade/): Proporciona una interfaz simplificada a un subsistema + complejo, de forma similar a como una entidad compuesta simplifica el acceso a un conjunto de objetos. +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Útil para gestionar objetos compartidos dentro de + una entidad compuesta para reducir la huella de memoria. + +## Créditos + +* [Composite Entity Pattern in wikipedia](https://en.wikipedia.org/wiki/Composite_entity_pattern) +* [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) +* [Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML](https://amzn.to/49mslqS) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3xjKdpe) diff --git a/localization/es/composite-entity/etc/composite_entity.urm.png b/localization/es/composite-entity/etc/composite_entity.urm.png new file mode 100644 index 000000000000..d6c29a718837 Binary files /dev/null and b/localization/es/composite-entity/etc/composite_entity.urm.png differ diff --git a/localization/es/composite-view/README.md b/localization/es/composite-view/README.md new file mode 100644 index 000000000000..9c178e81533b --- /dev/null +++ b/localization/es/composite-view/README.md @@ -0,0 +1,386 @@ +--- +title: Composite View +shortTitle: Composite View +category: Structural +language: es +tag: + - Enterprise patterns + - Presentation +--- + +## Propósito + +El objetivo principal del patrón de diseño Composite View es componer objetos en estructuras de árbol para representar +jerarquías parte-todo. Esto permite a los clientes tratar objetos individuales y composiciones de objetos de manera +uniforme, simplificando la gestión de estructuras complejas. + +## Explicación + +Ejemplo del mundo real + +> Un sitio de noticias quiere mostrar la fecha actual y las noticias a diferentes usuarios basándose en las preferencias +> de ese usuario. El sitio de noticias sustituirá en diferentes componentes de alimentación de noticias en función de +> los intereses del usuario, por defecto a las noticias locales. + +En pocas palabras + +> El patrón de vista compuesta consiste en tener una vista principal compuesta por subvistas más pequeñas. El diseño de +> esta vista compuesta se basa en una plantilla. Un View-manager decide entonces qué subvistas incluir en esta +> plantilla. + +Wikipedia dice + +> Vistas compuestas que están formadas por múltiples subvistas atómicas. Cada componente de la plantilla puede incluirse +> dinámicamente en el conjunto y el diseño de la página puede gestionarse independientemente del contenido. Esta +> solución permite crear una vista compuesta basada en la inclusión y sustitución de fragmentos modulares de plantillas +> dinámicas y estáticas. Promueve la reutilización de porciones atómicas de la vista fomentando el diseño modular. + +**Ejemplo programático** + +Dado que se trata de un patrón de desarrollo web, se requiere un servidor para demostrarlo. Este ejemplo utiliza Tomcat +10.0.13 para ejecutar el servlet, y este ejemplo programático sólo funcionará con Tomcat 10+. + +En primer lugar, existe `AppServlet` que es un `HttpServlet` que se ejecuta en Tomcat 10+. + +```java +public class AppServlet extends HttpServlet { + private String msgPartOne = "

    This Server Doesn't Support"; + private String msgPartTwo = "Requests

    \n" + + "

    Use a GET request with boolean values for the following parameters

    \n" + + "

    'name'

    \n

    'bus'

    \n

    'sports'

    \n

    'sci'

    \n

    'world'

    "; + + private String destination = "newsDisplay.jsp"; + + public AppServlet() { + + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination); + ClientPropertiesBean reqParams = new ClientPropertiesBean(req); + req.setAttribute("properties", reqParams); + requestDispatcher.forward(req, resp); + } + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Post " + msgPartTwo); + + } + + @Override + public void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Delete " + msgPartTwo); + + } + + @Override + public void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Put " + msgPartTwo); + + } +} + +``` + +Este servlet no forma parte del patrón, y simplemente reenvía las peticiones GET a la JSP correcta. Las peticiones PUT, +POST y DELETE no están soportadas y simplemente mostrarán un mensaje de error. + +La gestión de la vista en este ejemplo se realiza a través de una clase javabean: `ClientPropertiesBean`, que almacena +las preferencias del usuario. + +```java +public class ClientPropertiesBean implements Serializable { + + private static final String WORLD_PARAM = "world"; + private static final String SCIENCE_PARAM = "sci"; + private static final String SPORTS_PARAM = "sport"; + private static final String BUSINESS_PARAM = "bus"; + private static final String NAME_PARAM = "name"; + + private static final String DEFAULT_NAME = "DEFAULT_NAME"; + private boolean worldNewsInterest; + private boolean sportsInterest; + private boolean businessInterest; + private boolean scienceNewsInterest; + private String name; + + public ClientPropertiesBean() { + worldNewsInterest = true; + sportsInterest = true; + businessInterest = true; + scienceNewsInterest = true; + name = DEFAULT_NAME; + + } + + public ClientPropertiesBean(HttpServletRequest req) { + worldNewsInterest = Boolean.parseBoolean(req.getParameter(WORLD_PARAM)); + sportsInterest = Boolean.parseBoolean(req.getParameter(SPORTS_PARAM)); + businessInterest = Boolean.parseBoolean(req.getParameter(BUSINESS_PARAM)); + scienceNewsInterest = Boolean.parseBoolean(req.getParameter(SCIENCE_PARAM)); + String tempName = req.getParameter(NAME_PARAM); + if (tempName == null || tempName == "") { + tempName = DEFAULT_NAME; + } + name = tempName; + } + // getters and setters generated by Lombok +} +``` + +Este javabean tiene un constructor por defecto, y otro que toma un `HttpServletRequest`. + +Este segundo constructor toma el objeto de solicitud, analiza los parámetros de la solicitud que contienen las +preferencias del usuario para los diferentes tipos de noticias. + +La plantilla para la página de noticias está en `newsDisplay.jsp`. + +```html + + + + + + +<%ClientPropertiesBean propertiesBean = (ClientPropertiesBean) request.getAttribute("properties");%> +

    Welcome <%= propertiesBean.getName()%>

    + + + + + + <% if(propertiesBean.isWorldNewsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isBusinessInterest()) { %> + + <% } else { %> + + <% } %> + + <% if(propertiesBean.isSportsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isScienceNewsInterest()) { %> + + <% } else { %> + + <% } %> + + +
    <%@include file="worldNews.jsp"%><%@include file="localNews.jsp"%>
    <%@include file="businessNews.jsp"%><%@include file="localNews.jsp"%><%@include file="sportsNews.jsp"%><%@include file="localNews.jsp"%>
    <%@include file="scienceNews.jsp"%><%@include file="localNews.jsp"%>
    + + +``` + +Esta página JSP es la plantilla. Declara una tabla con tres filas, con un componente en la primera fila, dos componentes +en la segunda fila y un componente en la tercera fila. + +Los scriplets en el archivo son parte de la estrategia de gestión de vistas que incluyen diferentes subvistas atómicas +basadas en las preferencias del usuario en el Javabean. + +A continuación se muestran dos ejemplos de las subvistas atómicas simuladas utilizadas en el +compuesto: `businessNews.jsp` + +```html + + + + + + +

    + Generic Business News +

    + + + + + + + + + +
    Stock prices up across the worldNew tech companies to invest in
    Industry leaders unveil new projectPrice fluctuations and what they mean
    + + +``` + +`localNews.jsp` + +```html + + + +
    +

    + Generic Local News +

    +
      +
    • + Mayoral elections coming up in 2 weeks +
    • +
    • + New parking meter rates downtown coming tomorrow +
    • +
    • + Park renovations to finish by the next year +
    • +
    • + Annual marathon sign ups available online +
    • +
    +
    + + +``` + +Los resultados son los siguientes: + +1) El usuario ha puesto su nombre como `Tammy` en los parámetros de la petición y ninguna + preferencia: ![alt text](./etc/images/noparam.png) +2) El usuario ha puesto su nombre como `Johnny` en los parámetros de la petición y tiene preferencia por noticias del + mundo, negocios y ciencia: ![alt text](./etc/images/threeparams.png) + +Las distintas subvistas como `worldNews.jsp`, `businessNews.jsp`, etc. se incluyen condicionalmente en función de los +parámetros de la solicitud. + +**Cómo utilizarlo** + +Para probar este ejemplo, asegúrese de tener Tomcat 10+ instalado. Configure su IDE para construir un archivo WAR a +partir del módulo y despliegue ese archivo en el servidor + +IntelliJ: + +En `Run` y `edit configurations` Asegúrate de que el servidor Tomcat es una de las configuraciones de ejecución. Vaya a +la pestaña de despliegue y asegúrese de que se está construyendo un artefacto llamado `composite-view:war exploded`. Si +no está presente, añada uno. + +Asegúrate de que el artefacto se está construyendo a partir del contenido del directorio `web` y de los resultados de la +compilación del módulo. Apunta la salida del artefacto a un lugar conveniente. Ejecute la configuración y vea la página +de destino, siga las instrucciones de esa página para continuar. + +## Diagrama de clases + +![alt text](./etc/composite_view.png) + +El diagrama de clases aquí muestra el Javabean que es el gestor de vistas. Las vistas son JSP's dentro del directorio +web. + +## Aplicabilidad: + +Utiliza el patrón de diseño Composite View cuando: + +## Desea representar jerarquías parciales de objetos. + +* Esperas que las estructuras compuestas puedan incluir nuevos componentes en el futuro. +* Desea que los clientes puedan ignorar la diferencia entre composiciones de objetos y objetos individuales. Los + clientes tratarán todos los objetos de la estructura compuesta de manera uniforme. + +## Usos conocidos + +* Interfaces gráficas de usuario (GUI) en las que los widgets pueden contener otros widgets (por ejemplo, una ventana + con paneles, botones y campos de texto). +* Estructuras de documentos, como la representación de tablas que contienen filas, que a su vez contienen celdas, todas + las cuales pueden tratarse como elementos de una jerarquía unificada. + +## Consecuencias + +Ventajas: + +* Gran flexibilidad a la hora de añadir nuevos componentes: Como los compuestos y los nodos hoja se tratan de manera + uniforme, es más fácil añadir nuevos tipos de componentes. +* Código cliente simplificado: Los clientes pueden tratar las estructuras compuestas y los elementos individuales de + manera uniforme, lo que reduce la complejidad del código cliente. + +Contrapartidas: + +* Generalización excesiva: El diseño del sistema puede volverse más complejo si haces que todo sea compuesto, + especialmente si tu aplicación no lo requiere. +* Dificultad en la aplicación de restricciones: Puede ser más difícil restringir los componentes de un compuesto a sólo + ciertos tipos. + +## Patrones Relacionados + +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Mientras que Decorator se utiliza para añadir + responsabilidades a los objetos, Composite está pensado para construir estructuras de objetos. +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Composite puede combinarse a menudo con Flyweight + para implementar nodos hoja compartidos en una estructura compuesta, reduciendo la huella de memoria. +* [Cadena de responsabilidad](https://java-design-patterns.com/patterns/chain-of-responsibility/): Puede usarse con + Composite para permitir a los componentes pasar peticiones a través de la jerarquía. +* [Composite](https://java-design-patterns.com/patterns/composite/) +* [Ayudante de vista](https://www.oracle.com/java/technologies/viewhelper.html) + +## Créditos + +* [Core J2EE Patterns - Composite View](https://www.oracle.com/java/technologies/composite-view.html) +* [Composite View Design Pattern – Core J2EE Patterns](https://www.dineshonjava.com/composite-view-design-pattern/) +* [Patterns of Enterprise Application Architecture](https://amzn.to/49jpQG3) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3xfntGJ) diff --git a/localization/es/composite-view/etc/composite_view.png b/localization/es/composite-view/etc/composite_view.png new file mode 100644 index 000000000000..66215d9416b8 Binary files /dev/null and b/localization/es/composite-view/etc/composite_view.png differ diff --git a/localization/es/composite-view/etc/images/noparam.png b/localization/es/composite-view/etc/images/noparam.png new file mode 100644 index 000000000000..2979cf2bc657 Binary files /dev/null and b/localization/es/composite-view/etc/images/noparam.png differ diff --git a/localization/es/composite-view/etc/images/threeparams.png b/localization/es/composite-view/etc/images/threeparams.png new file mode 100644 index 000000000000..9338dedb8885 Binary files /dev/null and b/localization/es/composite-view/etc/images/threeparams.png differ diff --git a/localization/es/composite/README.md b/localization/es/composite/README.md new file mode 100644 index 000000000000..62c56e56cdd1 --- /dev/null +++ b/localization/es/composite/README.md @@ -0,0 +1,230 @@ +--- +title: Composite +shortTitle: Composite +category: Structural +language: es +tag: + - Gang of Four + - Object composition + - Recursion +--- + +## También conocido como + +* Object Tree +* Composite Structure + +## Propósito + +Componga objetos en estructuras de árbol para representar jerarquías parte-todo. Composite permite a los clientes tratar +objetos individuales y composiciones de objetos de manera uniforme. + +## Explanation + +Real-world example + +> Cada frase se compone de palabras que a su vez se componen de caracteres. Cada uno de estos objetos es imprimible y +> puede tener algo impreso antes o después de ellos, como la frase siempre termina con punto final y la palabra siempre +> tiene espacio antes de ella. + +En pocas palabras + +> El patrón compuesto permite a los clientes tratar uniformemente los objetos individuales. + +Wikipedia dice + +> En ingeniería de software, el patrón compuesto es un patrón de diseño de partición. El patrón compuesto describe que +> un grupo de objetos debe ser tratado de la misma manera que una única instancia de un objeto. La intención de un +> compuesto es "componer" objetos en estructuras de árbol para representar jerarquías parte-todo. La implementación del +> patrón de composición permite a los clientes tratar los objetos individuales y las composiciones de manera uniforme. + +**Ejemplo programático** + +Tomando nuestro ejemplo anterior. Aquí tenemos la clase base `LetterComposite` y los diferentes tipos +imprimibles `Letter`, `Word` y `Sentence`. + +```java +public abstract class LetterComposite { + + private final 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(); + children.forEach(LetterComposite::print); + printThisAfter(); + } +} + +public class Letter extends LetterComposite { + + private final char character; + + public Letter(char c) { + this.character = c; + } + + @Override + protected void printThisBefore() { + System.out.print(character); + } +} + +public class Word extends LetterComposite { + + public Word(List letters) { + letters.forEach(this::add); + } + + public Word(char... letters) { + for (char letter : letters) { + this.add(new Letter(letter)); + } + } + + @Override + protected void printThisBefore() { + System.out.print(" "); + } +} + +public class Sentence extends LetterComposite { + + public Sentence(List words) { + words.forEach(this::add); + } + + @Override + protected void printThisAfter() { + System.out.print("."); + } +} +``` + +Entonces tenemos un mensajero para llevar mensajes: + +```java +public class Messenger { + + LetterComposite messageFromOrcs() { + + var words = List.of( + new Word('W', 'h', 'e', 'r', 'e'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'h', 'i', 'p'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'a', 'y') + ); + + return new Sentence(words); + + } + + LetterComposite messageFromElves() { + + var words = List.of( + new Word('M', 'u', 'c', 'h'), + new Word('w', 'i', 'n', 'd'), + new Word('p', 'o', 'u', 'r', 's'), + new Word('f', 'r', 'o', 'm'), + new Word('y', 'o', 'u', 'r'), + new Word('m', 'o', 'u', 't', 'h') + ); + + return new Sentence(words); + + } + +} +``` + +Y entonces se puede utilizar como: + +```java +var messenger=new Messenger(); + + LOGGER.info("Message from the orcs: "); + messenger.messageFromOrcs().print(); + + LOGGER.info("Message from the elves: "); + messenger.messageFromElves().print(); +``` + +La salida de la consola: + +``` +Message from the orcs: + Where there is a whip there is a way. +Message from the elves: + Much wind pours from your mouth. +``` + +## Diagrama de clases + +![alt text](./etc/composite.urm.png "Diagrama de clases compuestas") + +## Aplicabilidad + +Utilice el patrón Composite cuando + +* Desea representar jerarquías parciales de objetos. +* Desea que los clientes puedan ignorar la diferencia entre composiciones de objetos y objetos individuales. Los + clientes tratarán todos los objetos de la estructura compuesta de manera uniforme. + +## Usos conocidos + +* Interfaces gráficas de usuario donde los componentes pueden contener otros componentes (por ejemplo, paneles que + contienen botones, etiquetas, otros paneles). +* Representaciones de sistemas de archivos donde los directorios pueden contener archivos y otros directorios. +* Estructuras organizativas en las que un departamento puede contener subdepartamentos y empleados. +* [java.awt.Container](http://docs.oracle.com/javase/8/docs/api/java/awt/Container.html) + y [java.awt.Component](http://docs.oracle.com/javase/8/docs/api/java/awt/Component.html) +* Árbol de componentes [Apache Wicket](https://github.com/apache/wicket), + ver [Component](https://github.com/apache/wicket/blob/91e154702ab1ff3481ef6cbb04c6044814b7e130/wicket-core/src/main/java/org/apache/wicket/Component.java) + y [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java) + +## Consecuencias + +Ventajas: + +* Simplifica el código cliente, ya que puede tratar estructuras compuestas y objetos individuales de manera uniforme. +* Facilita la adición de nuevos tipos de componentes, ya que no es necesario modificar el código existente. + +Contrapartidas: + +* Puede hacer que el diseño sea demasiado general. Puede ser difícil restringir los componentes de un compuesto. +* Puede dificultar la restricción de los tipos de componentes de un compuesto. + +## Patrones relacionados + +* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Composite puede usar Flyweight para compartir + instancias de componentes entre varios composites. +* [Iterador](https://java-design-patterns.com/patterns/iterator/): Puede ser utilizado para atravesar estructuras + Composite. +* [Visitante](https://java-design-patterns.com/patterns/visitor/): Puede aplicar una operación sobre una estructura + Composite. + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3xoLAmi) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3vBKXWb) diff --git a/localization/es/composite/etc/composite.urm.png b/localization/es/composite/etc/composite.urm.png new file mode 100644 index 000000000000..93c160f6450a Binary files /dev/null and b/localization/es/composite/etc/composite.urm.png differ diff --git a/localization/es/context-object/README.md b/localization/es/context-object/README.md new file mode 100644 index 000000000000..5cc16554508d --- /dev/null +++ b/localization/es/context-object/README.md @@ -0,0 +1,188 @@ +--- +title: Context object +shortTitle: Context object +category: Creational +language: es +tags: + - Data access +--- + +## Nombre / Clasificación + +Context Object + +## También conocido como + +Context, Encapsulate Context + +## Propósito + +Desacoplar los datos de las clases específicas del protocolo y almacenar los datos del ámbito en un objeto independiente +de la tecnología del protocolo subyacente. + +## Explicación + +Ejemplo del mundo real + +> Esta aplicación tiene diferentes capas etiquetadas como A, B y C, cada una extrayendo información específica de un +> contexto similar para su uso posterior en el software. Pasar cada pieza de información individualmente sería +> ineficiente, se necesita un método para almacenar y pasar información de manera eficiente. +> En palabras sencillas + +> Crea un objeto y almacena los datos allí y pasa este objeto a donde se necesita. + +[Core J2EE Patterns](http://corej2eepatterns.com/ContextObject.htm) dice + +> Utilice un objeto de contexto (Context Object) para encapsular el estado de una manera independiente del protocolo para ser compartido +> en toda tu aplicación. + +**Ejemplo programático** + +Definimos qué datos contiene un objeto de contexto (Context Object) de servicio `ServiceContext`. + +```Java +public class ServiceContext { + + String ACCOUNT_SERVICE, SESSION_SERVICE, SEARCH_SERVICE; + + public void setACCOUNT_SERVICE(String ACCOUNT_SERVICE) { + this.ACCOUNT_SERVICE = ACCOUNT_SERVICE; + } + + public void setSESSION_SERVICE(String SESSION_SERVICE) { + this.SESSION_SERVICE = SESSION_SERVICE; + } + + public void setSEARCH_SERVICE(String SEARCH_SERVICE) { + this.SEARCH_SERVICE = SEARCH_SERVICE; + } + + public String getACCOUNT_SERVICE() { + return ACCOUNT_SERVICE; + } + + public String getSESSION_SERVICE() { + return SESSION_SERVICE; + } + + public String getSEARCH_SERVICE() { + return SEARCH_SERVICE; + } + + public String toString() { return ACCOUNT_SERVICE + " " + SESSION_SERVICE + " " + SEARCH_SERVICE;} +} +``` + +Se crea una interfaz `ServiceContextFactory` utilizada en partes de la aplicación para crear objetos de contexto. + +```Java +public class ServiceContextFactory { + + public static ServiceContext createContext() { + return new ServiceContext(); + } +} +``` + +Instanciar el objeto de contexto en la primera capa `LayerA` y la capa contigua `LayerB` hasta llamar al contexto en la capa actual `LayerC`, +que estructura el objeto. + +```Java +public class LayerA { + + private static ServiceContext context; + + public LayerA() { + context = ServiceContextFactory.createContext(); + } + + public static ServiceContext getContext() { + return context; + } + + public void addAccountInfo(String accountService) { + context.setACCOUNT_SERVICE(accountService); + } +} + +public class LayerB { + + private static ServiceContext context; + + public LayerB(LayerA layerA) { + this.context = layerA.getContext(); + } + + public static ServiceContext getContext() { + return context; + } + + public void addSessionInfo(String sessionService) { + context.setSESSION_SERVICE(sessionService); + } +} + +public class LayerC { + + public static ServiceContext context; + + public LayerC(LayerB layerB) { + this.context = layerB.getContext(); + } + + public static ServiceContext getContext() { + return context; + } + + public void addSearchInfo(String searchService) { + context.setSEARCH_SERVICE(searchService); + } +} +``` + +He aquí el objeto de contexto y las capas en acción. + +```Java +var layerA = new LayerA(); +layerA.addAccountInfo(SERVICE); +LOGGER.info("Context = {}",layerA.getContext()); +var layerB = new LayerB(layerA); +layerB.addSessionInfo(SERVICE); +LOGGER.info("Context = {}",layerB.getContext()); +var layerC = new LayerC(layerB); +layerC.addSearchInfo(SERVICE); +LOGGER.info("Context = {}",layerC.getContext()); +``` + +Salida del programa: + +```Java +Context = SERVICE null null +Context = SERVICE SERVICE null +Context = SERVICE SERVICE SERVICE +``` + +## Diagrama de clases + +![alt text](./etc/context-object.png "Context object") + +## Aplicabilidad + +Utilizar el patrón Objeto Contexto (Context Object) para: + +* Compartir información entre diferentes capas del sistema. +* Desacoplar datos de software de contextos específicos de protocolo. +* Exponer solo las API relevantes dentro del contexto. + +## Usos conocidos + +* [Spring: ApplicationContext](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html) +* [Oracle: SecurityContext](https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/SecurityContext.html) +* [Oracle: ServletContext](https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html) + +## Créditos + +* [Core J2EE Design Patterns](https://amzn.to/3IhcY9w) +* [Core J2EE Design Patterns website - Context Object](http://corej2eepatterns.com/ContextObject.htm) +* [Allan Kelly - The Encapsulate Context Pattern](https://accu.org/journals/overload/12/63/kelly_246/) +* [Arvid S. Krishna et al. - Context Object](https://www.dre.vanderbilt.edu/~schmidt/PDF/Context-Object-Pattern.pdf) diff --git a/localization/es/context-object/etc/context-object.png b/localization/es/context-object/etc/context-object.png new file mode 100644 index 000000000000..a1f670812f7b Binary files /dev/null and b/localization/es/context-object/etc/context-object.png differ diff --git a/localization/es/converter/README.md b/localization/es/converter/README.md new file mode 100644 index 000000000000..199cd79715db --- /dev/null +++ b/localization/es/converter/README.md @@ -0,0 +1,106 @@ +--- +title: Converter +shortTitle: Converter +category: Creational +language: es +tag: + - Decoupling +--- + +## Propósito + +El propósito del patrón Conversor (Converter) es proporcionar una forma genérica y común de conversión bidireccional +entre tipos correspondientes, permitiendo una implementación limpia en la que los tipos no +tienen que conocerse entre sí. Además, el patrón Converter introduce la asignación bidireccional de colecciones +bidireccional, reduciendo al mínimo el código repetitivo. + +## Explicación + +Ejemplo del mundo real + +> En las aplicaciones del mundo real, a menudo se da el caso de que la capa de base de datos consta de entidades que +> necesitan ser mapeadas en DTO para su uso en la capa de lógica de negocio. Un mapeo similar se realiza para +> potencialmente enorme cantidad de clases y necesitamos una forma genérica de lograrlo. + +En palabras sencillas + +> El patrón de conversión (Converter) facilita la asignación de instancias de una clase a instancias de otra clase. + +**Ejemplo programático** + +Necesitamos una solución genérica para el problema del mapeo. Para ello, introduzcamos un convertidor genérico. + +```java +public class Converter { + + private final Function fromDto; + private final Function fromEntity; + + public Converter(final Function fromDto, final Function fromEntity) { + this.fromDto = fromDto; + this.fromEntity = fromEntity; + } + + public final U convertFromDto(final T dto) { + return fromDto.apply(dto); + } + + public final T convertFromEntity(final U entity) { + return fromEntity.apply(entity); + } + + public final List createFromDtos(final Collection dtos) { + return dtos.stream().map(this::convertFromDto).collect(Collectors.toList()); + } + + public final List createFromEntities(final Collection entities) { + return entities.stream().map(this::convertFromEntity).collect(Collectors.toList()); + } +} +``` + +Los convertidores especializados heredan de esta clase base de la siguiente manera. + +```java +public class UserConverter extends Converter { + + public UserConverter() { + super(UserConverter::convertToEntity, UserConverter::convertToDto); + } + + private static UserDto convertToDto(User user) { + return new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), user.getUserId()); + } + + private static User convertToEntity(UserDto dto) { + return new User(dto.getFirstName(), dto.getLastName(), dto.isActive(), dto.getEmail()); + } + +} +``` + +Ahora el mapeo entre `User` y `UserDto` se vuelve trivial. + +```java +var userConverter = new UserConverter(); +var dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); +var user = userConverter.convertFromDto(dtoUser); +``` + +## Diagrama de Clases + +![alt text](./etc/converter.png "Converter Pattern") + +## Aplicabilidad + +Utilice el patrón de conversión en las siguientes situaciones: + +* Cuando tiene tipos que lógicamente se corresponden entre sí y necesita convertir entidades + entre ellos. +* Cuando quieras proporcionar diferentes formas de conversión de tipos dependiendo del contexto. +* Siempre que introduzca un DTO (Data transfer object), probablemente necesitará convertirlo en la + equivalencia de dominio. + +## Créditos + +* [Converter Pattern in Java 8](http://www.xsolve.pl/blog/converter-pattern-in-java-8/) diff --git a/localization/es/converter/etc/converter.png b/localization/es/converter/etc/converter.png new file mode 100644 index 000000000000..01435ef5ae29 Binary files /dev/null and b/localization/es/converter/etc/converter.png differ diff --git a/localization/es/crtp/README.md b/localization/es/crtp/README.md new file mode 100644 index 000000000000..a8160e1ac8bc --- /dev/null +++ b/localization/es/crtp/README.md @@ -0,0 +1,135 @@ +--- +title: Curiously Recurring Template Pattern +language: es +category: Structural +tag: +- Extensibility +- Instantiation +--- + +## Nombre / clasificación + +Curiously Recurring Template Pattern + +## También conocido como + +Recursive Type Bound, Recursive Generic + +## Propósito + +Permitir que los componentes derivados hereden ciertas funcionalidades de un componente base que sean compatibles con el tipo derivado. + +## Explicación + +Un ejemplo real + +> Para una promoción de artes marciales mixtas que esté planificando un evento, es crucial asegurarse de que los combates se organicen entre atletas de la misma categoría de peso. Así se evitan los enfrentamientos entre luchadores de tallas muy diferentes, como un peso pesado contra un peso gallo. + +En pocas palabras + +> Hacer que ciertos métodos dentro de un tipo acepten argumentos específicos de sus subtipos. + +Wikipedia dice + +> El patrón de plantilla curiosamente recurrente (CRTP) es un modismo, originalmente en C++, en el que una clase X deriva de una instanciación de plantilla de clase usando la propia X como argumento de plantilla. + +**Ejemplo programático** + +Definamos la interfaz genérica Fighter + +```java +public interface Fighter { + + void fight(T t); + +} +``` + +La clase `MMAFighter` se utiliza para crear luchadores que se distinguen por su categoría de peso. + +```java +public class MmaFighter> implements Fighter { + + private final String name; + private final String surname; + private final String nickName; + private final String speciality; + + public MmaFighter(String name, String surname, String nickName, String speciality) { + this.name = name; + this.surname = surname; + this.nickName = nickName; + this.speciality = speciality; + } + + @Override + public void fight(T opponent) { + LOGGER.info("{} is going to fight against {}", this, opponent); + } + + @Override + public String toString() { + return name + " \"" + nickName + "\" " + surname; + } +``` + +Los siguientes son algunos subtipos de `MmaFighter` + +```java +class MmaBantamweightFighter extends MmaFighter { + + public MmaBantamweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } + +} + +public class MmaHeavyweightFighter extends MmaFighter { + + public MmaHeavyweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } + +} +``` + +Un luchador puede enfrentarse a un oponente de la misma categoría de peso, si el oponente es de una categoría de peso diferente +se produce un error. + +```java +MmaBantamweightFighter fighter1 = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai"); +MmaBantamweightFighter fighter2 = new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo"); +fighter1.fight(fighter2); // This is fine + +MmaHeavyweightFighter fighter3 = new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing"); +MmaHeavyweightFighter fighter4 = new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu"); +fighter3.fight(fighter4); // This is fine too + +fighter1.fight(fighter3); // This will raise a compilation error +``` + +## Diagrama de clases + +![alt text](./etc/crtp.png "Diagrama de clases CRTP") + +## Aplicabilidad + +Utilice el Patrón de Plantilla Curiosamente Recurrente cuando + +* Tienes conflictos de tipos al encadenar métodos en una jerarquía de objetos +* Desea utilizar un método de clase parametrizado que pueda aceptar subclases de la clase como argumentos, permitiendo que se aplique a objetos que heredan de la clase +* Desea que ciertos métodos funcionen sólo con instancias del mismo tipo, por ejemplo, para lograr la comparabilidad mutua. + +## Tutoriales + +* [El blog de NuaH](https://nuah.livejournal.com/328187.html) +* Respuesta de Yogesh Umesh Vaity a [¿Qué significa "Recursive type bound" en Generics?](https://stackoverflow.com/questions/7385949/what-does-recursive-type-bound-in-generics-mean) + +## Usos conocidos + +* [java.lang.Enum](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Enum.html) + +## Créditos + +* [How do I decrypt "Enum>"?](http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ106) +* Chapter 5 Generics, Item 30 in [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) diff --git a/localization/es/crtp/etc/crtp.png b/localization/es/crtp/etc/crtp.png new file mode 100644 index 000000000000..a348c8af6175 Binary files /dev/null and b/localization/es/crtp/etc/crtp.png differ diff --git a/localization/es/data-locality/README.md b/localization/es/data-locality/README.md new file mode 100644 index 000000000000..bef09ce8b383 --- /dev/null +++ b/localization/es/data-locality/README.md @@ -0,0 +1,30 @@ +--- +title: Data Locality +shortTitle: Data Locality +category: Behavioral +language: es +tag: + - Game programming + - Performance +--- + +## Propósito +Acelera el acceso a la memoria organizando los datos para aprovechar la caché de la CPU. + +Las CPU modernas disponen de cachés para acelerar el acceso a la memoria. Éstas pueden acceder mucho más rápido a la memoria adyacente a la memoria a la que se ha accedido recientemente. Aprovéchate de ello para mejorar el rendimiento aumentando la localidad de los datos, manteniéndolos en memoria contigua en el orden en que los procesas. + +## Diagrama de clases +![alt text](./etc/data-locality.urm.png "Data Locality pattern class diagram") + +## Aplicabilidad + +* Como la mayoría de las optimizaciones, la primera pauta para usar el patrón Data Locality es cuando se tiene un problema de rendimiento. +* Con este patrón específicamente, también querrás estar seguro de que tus problemas de rendimiento son causados por pérdidas de caché. + +## Ejemplo del mundo real + +* El motor de juego [Artemis](http://gamadu.com/artemis/) es uno de los primeros y más conocidos frameworks que utiliza IDs simples para las entidades del juego. + +## Créditos + +* [Game Programming Patterns Optimization Patterns: Data Locality](http://gameprogrammingpatterns.com/data-locality.html) \ No newline at end of file diff --git a/localization/es/data-locality/etc/data-locality.urm.png b/localization/es/data-locality/etc/data-locality.urm.png new file mode 100644 index 000000000000..d19873739551 Binary files /dev/null and b/localization/es/data-locality/etc/data-locality.urm.png differ diff --git a/localization/es/decorator/README.md b/localization/es/decorator/README.md new file mode 100644 index 000000000000..92bffb207702 --- /dev/null +++ b/localization/es/decorator/README.md @@ -0,0 +1,170 @@ +--- +title: Decorator +shortTitle: Decorator +category: Structural +language: es +tag: + - Gang of Four + - Extensibility +--- + +## También conocido como + +Wrapper + +## Propósito + +Adjunte responsabilidades adicionales a un objeto de forma dinámica. Los decoradores proporcionan una alternativa +flexible a la subclase para ampliar la funcionalidad. + +## Explicación + +Ejemplo real + +> En las colinas cercanas vive un trol furioso. Normalmente va con las manos desnudas, pero a veces lleva un arma. Para +> armar al troll no es necesario crear un nuevo troll sino decorarlo dinámicamente con un arma adecuada. + +En pocas palabras + +> El patrón decorador permite cambiar dinámicamente el comportamiento de un objeto en tiempo de ejecución envolviéndolo +> en un objeto de una clase decoradora. + +Wikipedia says + +> En programación orientada a objetos, el patrón decorador es un patrón de diseño que permite añadir comportamiento a un +> objeto individual, ya sea de forma estática o dinámica, sin afectar al comportamiento de otros objetos de la misma +> clase. El patrón decorador suele ser útil para adherirse al Principio de Responsabilidad Única, ya que permite dividir +> la funcionalidad entre clases con áreas de interés únicas, así como al Principio Abierto-Cerrado, al permitir extender +> la funcionalidad de una clase sin modificarla. + +**Ejemplo programático** + +Tomemos el ejemplo del troll. En primer lugar tenemos un `SimpleTroll` que implementa la interfaz `Troll`: + +```java +public interface Troll { + void atacar(); + int getPoderAtaque(); + void huirBatalla(); +} + +@Slf4j +public class SimpleTroll implements Troll { + + @Override + public void atacar() { + LOGGER.info("¡El troll intenta atraparte!"); + } + + @Override + public int getPoderAtaque() { + return 10; + } + + @Override + public void huirBatalla() { + LOGGER.info("¡El troll chilla de horror y huye!"); + } +} +``` + +A continuación, queremos añadir un palo para el troll. Podemos hacerlo de forma dinámica mediante el uso de un +decorador: + +```java +@Slf4j +public class TrollConGarrote implements Troll { + + private final Troll decorado; + + public TrollConGarrote(Troll decorado) { + this.decorado = decorado; + } + + @Override + public void atacar() { + decorado.atacar(); + LOGGER.info("¡El troll te golpea con un garrote!"); + } + + @Override + public int getPoderAtaque() { + return decorado.getPoderAtaque() + 10; + } + + @Override + public void huirBatalla() { + decorado.huirBatalla(); + } +} +``` + +Aquí está el troll en acción: + +```java +// troll simple +LOGGER.info("Un troll de aspecto simple se acerca."); +var troll = new SimpleTroll(); +troll.atacar(); +troll.huirBatalla(); +LOGGER.info("Poder del troll simple: {}.\n", troll.getPoderAtaque()); + +// cambia el comportamiento del troll simple agregando un decorador +LOGGER.info("Un troll con un enorme garrote te sorprende."); +var trollConGarrote = new TrollConGarrote(troll); +trollConGarrote.atacar(); +trollConGarrote.huirBatalla(); +LOGGER.info("Poder del troll con garrote: {}.\n", trollConGarrote.getPoderAtaque()); +``` + +Salida del programa: + +```java +Un troll de aspecto simple se acerca. +¡El troll intenta atraparte! +¡El troll chilla de horror y huye! +Poder del troll simple: 10. + +Un troll con un enorme garrote te sorprende. +¡El troll intenta atraparte! +¡El troll te golpea con un garrote! +¡El troll chilla de horror y huye! +Poder del troll con garrote: 20. +``` + +## Diagrama de clases + +![alt text](./etc/decorator.urm.png "Decorator pattern class diagram") + +## Aplicabilidad + +Decorator se utiliza para: + +* Añadir responsabilidades a objetos individuales de forma dinámica y transparente, es decir, sin + afectar a otros objetos. +* Para responsabilidades que pueden ser retiradas. +* Cuando la extensión por subclase es poco práctica. A veces es posible un gran número de extensiones independientes + son posibles y producirían una explosión de subclases para soportar cada combinación. O la definición de una clase + puede estar oculta o no estar disponible para subclases. + +## Tutoriales + +* [Decorator Pattern Tutorial](https://www.journaldev.com/1540/decorator-design-pattern-in-java-example) + +## Usos conocidos + +* [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), + [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) + y [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) +* [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-) +* [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-) +* [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/es/decorator/etc/decorator.urm.png b/localization/es/decorator/etc/decorator.urm.png new file mode 100644 index 000000000000..141c0563f0c6 Binary files /dev/null and b/localization/es/decorator/etc/decorator.urm.png differ diff --git a/localization/es/delegation/README.md b/localization/es/delegation/README.md new file mode 100644 index 000000000000..ba128d45a532 --- /dev/null +++ b/localization/es/delegation/README.md @@ -0,0 +1,126 @@ +--- +title: Delegation +shortTitle: Delegation +category: Structural +language: es +tag: + - Decoupling +--- + +## También conocido como + +Proxy Pattern + +## Propósito + +Es una técnica en la que un objeto expresa cierto comportamiento al exterior pero en realidad delega la responsabilidad +de implementar ese comportamiento en un objeto asociado. + +## Explanation + +Real-world example + +> Imaginemos que tenemos aventureros que luchan contra monstruos con diferentes armas dependiendo de sus habilidades y +> destrezas. Debemos ser capaces de equiparles con diferentes sin tener que modificar su código fuente para cada una de +> ellas. El patrón de delegación lo hace posible delegando el trabajo dinámico a un objeto específico que implementa una +> interfaz con métodos relevantes. + +Wikipedia dice + +> En programación orientada a objetos, la delegación se refiere a la evaluación de un miembro (propiedad o método) de un +> objeto (el receptor) en el contexto de otro objeto original (el emisor). La delegación puede hacerse explícitamente, +> pasando el objeto emisor al objeto receptor, lo que puede hacerse en cualquier lenguaje orientado a objetos; o +> implícitamente, mediante las reglas de búsqueda de miembros del lenguaje, lo que requiere soporte del lenguaje para la +> función. + +**Ejemplo programático** + +Tenemos una interfaz `Printer` y tres implementaciones `CanonPrinter`, `EpsonPrinter` y `HpPrinter`. + +```java +public interface Printer { + void print(final String message); +} + +@Slf4j +public class CanonPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("Canon Printer : {}", message); + } +} + +@Slf4j +public class EpsonPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("Epson Printer : {}", message); + } +} + +@Slf4j +public class HpPrinter implements Printer { + @Override + public void print(String message) { + LOGGER.info("HP Printer : {}", message); + } +} +``` + +El `PrinterController` puede ser utilizado como un `Printer` delegando cualquier trabajo manejado por este +a un objeto que la implemente. + +```java +public class PrinterController implements Printer { + + private final Printer printer; + + public PrinterController(Printer printer) { + this.printer = printer; + } + + @Override + public void print(String message) { + printer.print(message); + } +} +``` + +Now on the client code printer controllers can print messages differently depending on the +object they're delegating that work to. + +```java +private static final String MESSAGE_TO_PRINT = "hello world"; + +var hpPrinterController = new PrinterController(new HpPrinter()); +var canonPrinterController = new PrinterController(new CanonPrinter()); +var epsonPrinterController = new PrinterController(new EpsonPrinter()); + +hpPrinterController.print(MESSAGE_TO_PRINT); +canonPrinterController.print(MESSAGE_TO_PRINT); +epsonPrinterController.print(MESSAGE_TO_PRINT) +``` + +Salida del programa: + +```java +HP Printer : hello world +Canon Printer : hello world +Epson Printer : hello world +``` + +## Diagrama de clases + +![alt text](./etc/delegation.png "Delegate") + +## Aplicabilidad + +Utilice el patrón Delegate para conseguir lo siguiente + +* Reducir el acoplamiento de los métodos a su clase +* Componentes que se comportan de forma idéntica, pero teniendo en cuenta que esta situación puede cambiar en el futuro. + +## Créditos + +* [Delegate Pattern: Wikipedia ](https://en.wikipedia.org/wiki/Delegation_pattern) +* [Proxy Pattern: Wikipedia ](https://en.wikipedia.org/wiki/Proxy_pattern) diff --git a/localization/es/delegation/etc/delegation.png b/localization/es/delegation/etc/delegation.png new file mode 100644 index 000000000000..375ef4d6b00f Binary files /dev/null and b/localization/es/delegation/etc/delegation.png differ diff --git a/localization/es/dependency-injection/README.md b/localization/es/dependency-injection/README.md new file mode 100644 index 000000000000..020e5fddb438 --- /dev/null +++ b/localization/es/dependency-injection/README.md @@ -0,0 +1,104 @@ +--- +title: Dependency Injection +shortTitle: Dependency Injection +category: Creational +language: es +tag: + - Decoupling +--- + +## Propósito + +La inyección de dependencias es un patrón de diseño de software en el que una o más dependencias (o servicios) +se inyectan, o se pasan por referencia, a un objeto dependiente (o cliente) y pasan a formar parte del estado del +cliente. El patrón separa la creación de las dependencias de un cliente de su propio comportamiento, +lo que permite que los diseños de los programas estén poco acoplados y sigan los principios de inversión de control y +responsabilidad única. + +## Explicación + +Ejemplo del mundo real + +> Al viejo mago le gusta llenar su pipa y fumar tabaco de vez en cuando. Sin embargo, no quiere depender de una sola +> marca de tabaco, sino que le gusta poder disfrutar de todas ellas de manera intercambiable. + +En palabras sencillas + +> La Inyección de Dependencias separa la creación de las dependencias del cliente de su propio comportamiento. + +Wikipedia dice + +> En ingeniería de software, la inyección de dependencias es una técnica en la que un objeto recibe otros objetos de los +> que depende. Estos otros objetos se llaman dependencias. + +**Ejemplo programático** + +Presentemos primero la interfaz tabaco `Tobacco` y las marcas concretas. + +```java +@Slf4j +public abstract class Tobacco { + + public void smoke(Wizard wizard) { + LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(), + this.getClass().getSimpleName()); + } +} + +public class SecondBreakfastTobacco extends Tobacco { +} + +public class RivendellTobacco extends Tobacco { +} + +public class OldTobyTobacco extends Tobacco { +} +``` + +A continuación se muestra la interfaz `Wizard` y su implementación. + +```java +public interface Wizard { + + void smoke(); +} + +public class AdvancedWizard implements Wizard { + + private final Tobacco tobacco; + + public AdvancedWizard(Tobacco tobacco) { + this.tobacco = tobacco; + } + + @Override + public void smoke() { + tobacco.smoke(this); + } +} +``` + +Y por último podemos demostrar lo fácil que es darle al viejo mago cualquier marca de tabaco `Tobacco`. + +```java + var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco()); + advancedWizard.smoke(); +``` + +## Diagrama de Clases + +![alt text](./etc/dependency-injection.png "Dependency Injection") + +## Aplicabilidad + +Utilice el patrón de Inyección de Dependencia cuando: + +* Cuando necesites eliminar el conocimiento de la implementación concreta del objeto. +* Para permitir pruebas unitarias de clases de forma aislada utilizando objetos simulados o stubs. + +## Créditos + +* [Dependency Injection Principles, Practices, and Patterns](https://www.amazon.com/gp/product/161729473X/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=161729473X&linkId=57079257a5c7d33755493802f3b884bd) +* [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.com/gp/product/0132350882/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0132350882&linkCode=as2&tag=javadesignpat-20&linkId=2c390d89cc9e61c01b9e7005c7842871) +* [Java 9 Dependency Injection: Write loosely coupled code with Spring 5 and Guice](https://www.amazon.com/gp/product/1788296257/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=1788296257&linkId=4e9137a3bf722a8b5b156cce1eec0fc1) +* [Google Guice: Agile Lightweight Dependency Injection Framework](https://www.amazon.com/gp/product/1590599977/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1590599977&linkId=3b10c90b7ba480a1b7777ff38000f956) diff --git a/localization/es/dependency-injection/etc/dependency-injection.png b/localization/es/dependency-injection/etc/dependency-injection.png new file mode 100644 index 000000000000..2a92c9eb228b Binary files /dev/null and b/localization/es/dependency-injection/etc/dependency-injection.png differ diff --git a/localization/es/dirty-flag/README.md b/localization/es/dirty-flag/README.md new file mode 100644 index 000000000000..71b9351da199 --- /dev/null +++ b/localization/es/dirty-flag/README.md @@ -0,0 +1,28 @@ +--- +title: Dirty Flag +shortTitle: Dirty Flag +category: Behavioral +language: es +tag: + - Game programming + - Performance +--- + +## También conocido como +* IsDirty pattern + +## Propósito +Evitar la costosa readquisición de recursos. Los recursos conservan su identidad, se guardan en algún almacenamiento de acceso rápido y se reutilizan para evitar tener que adquirirlos de nuevo. + +## Diagrama de clases +![alt text](./etc/dirty-flag.png "Dirty Flag") + +## Aplicabilidad +Utilice el patrón Dirty Flag cuando + +* La adquisición, inicialización y liberación repetitiva del mismo recurso causa una sobrecarga de rendimiento innecesaria. + +## Créditos + +* [Design Patterns: Dirty Flag](https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) diff --git a/localization/es/dirty-flag/etc/dirty-flag.png b/localization/es/dirty-flag/etc/dirty-flag.png new file mode 100644 index 000000000000..98d4f679d17c Binary files /dev/null and b/localization/es/dirty-flag/etc/dirty-flag.png differ diff --git a/localization/es/double-buffer/README.md b/localization/es/double-buffer/README.md new file mode 100644 index 000000000000..4caaf3691628 --- /dev/null +++ b/localization/es/double-buffer/README.md @@ -0,0 +1,242 @@ +--- +title: Double Buffer +shortTitle: Double Buffer +category: Behavioral +language: es +tag: + - Performance + - Game programming +--- + +## Propósito + +Doble búfer es un término utilizado para describir un dispositivo que tiene dos búferes. El uso de varios búferes aumenta el rendimiento global de un dispositivo y ayuda a evitar cuellos de botella. Este ejemplo muestra el uso de doble búfer en gráficos. Se utiliza para mostrar una imagen o un fotograma mientras se almacena en el búfer otro fotograma que se mostrará a continuación. Este método hace que las animaciones y los juegos parezcan más realistas que los realizados en modo de búfer único. + +## Explicación + +Ejemplo del mundo real +> Un ejemplo típico, y que todo motor de juego debe abordar, es el renderizado. Cuando el juego dibuja el mundo que ven los usuarios, lo hace pieza a pieza: las montañas a lo lejos, las colinas ondulantes, los árboles, cada uno a su vez. Si el usuario viera cómo se dibuja la vista de forma incremental, se rompería la ilusión de un mundo coherente. La escena debe actualizarse con fluidez y rapidez, mostrando una serie de fotogramas completos, cada uno de los cuales aparece al instante. La doble memoria intermedia resuelve el problema. + +En pocas palabras +> Garantiza un estado que se renderiza correctamente mientras ese estado se modifica de forma incremental. Se utiliza mucho en gráficos por ordenador. + +Wikipedia dice +> En informática, el almacenamiento en búfer múltiple es el uso de más de un búfer para contener un bloque de datos, de modo que un "lector" vea una versión completa (aunque quizás antigua) de los datos, en lugar de una versión parcialmente actualizada de los datos que está creando un "escritor". Se utiliza mucho en las imágenes de ordenador. + +**Ejemplo programático** + +Interfaz `Buffer` que asegura las funcionalidades básicas de un buffer. + +```java +/** + * Buffer interface. + */ +public interface Buffer { + + /** + * Clear the pixel in (x, y). + * + * @param x X coordinate + * @param y Y coordinate + */ + void clear(int x, int y); + + /** + * Draw the pixel in (x, y). + * + * @param x X coordinate + * @param y Y coordinate + */ + void draw(int x, int y); + + /** + * Clear all the pixels. + */ + void clearAll(); + + /** + * Get all the pixels. + * + * @return pixel list + */ + Pixel[] getPixels(); + +} +``` + +Una de las implementaciones de la interfaz `Buffer`. + +```java +/** + * FrameBuffer implementation class. + */ +public class FrameBuffer implements Buffer { + + public static final int WIDTH = 10; + public static final int HEIGHT = 8; + + private final Pixel[] pixels = new Pixel[WIDTH * HEIGHT]; + + public FrameBuffer() { + clearAll(); + } + + @Override + public void clear(int x, int y) { + pixels[getIndex(x, y)] = Pixel.WHITE; + } + + @Override + public void draw(int x, int y) { + pixels[getIndex(x, y)] = Pixel.BLACK; + } + + @Override + public void clearAll() { + Arrays.fill(pixels, Pixel.WHITE); + } + + @Override + public Pixel[] getPixels() { + return pixels; + } + + private int getIndex(int x, int y) { + return x + WIDTH * y; + } +} +``` + +```java +/** + * Pixel enum. Each pixel can be white (not drawn) or black (drawn). + */ +public enum Pixel { + + WHITE, BLACK; +} +``` + +`Scene` representa la escena del juego en la que ya se ha renderizado el búfer actual. + +```java +/** + * Scene class. Render the output frame. + */ +@Slf4j +public class Scene { + + private final Buffer[] frameBuffers; + + private int current; + + private int next; + + /** + * Constructor of Scene. + */ + public Scene() { + frameBuffers = new FrameBuffer[2]; + frameBuffers[0] = new FrameBuffer(); + frameBuffers[1] = new FrameBuffer(); + current = 0; + next = 1; + } + + /** + * Draw the next frame. + * + * @param coordinateList list of pixels of which the color should be black + */ + public void draw(List> coordinateList) { + LOGGER.info("Start drawing next frame"); + LOGGER.info("Current buffer: " + current + " Next buffer: " + next); + frameBuffers[next].clearAll(); + coordinateList.forEach(coordinate -> { + var x = coordinate.getKey(); + var y = coordinate.getValue(); + frameBuffers[next].draw(x, y); + }); + LOGGER.info("Swap current and next buffer"); + swap(); + LOGGER.info("Finish swapping"); + LOGGER.info("Current buffer: " + current + " Next buffer: " + next); + } + + public Buffer getBuffer() { + LOGGER.info("Get current buffer: " + current); + return frameBuffers[current]; + } + + private void swap() { + current = current ^ next; + next = current ^ next; + current = current ^ next; + } + +} +``` + +```java +public static void main(String[] args) { + final var scene = new Scene(); + var drawPixels1 = List.of(new MutablePair<>(1, 1), new MutablePair<>(5, 6), new MutablePair<>(3, 2)); + scene.draw(drawPixels1); + var buffer1 = scene.getBuffer(); + printBlackPixelCoordinate(buffer1); + + var drawPixels2 = List.of(new MutablePair<>(3, 7), new MutablePair<>(6, 1)); + scene.draw(drawPixels2); + var buffer2 = scene.getBuffer(); + printBlackPixelCoordinate(buffer2); +} + +private static void printBlackPixelCoordinate(Buffer buffer) { + StringBuilder log = new StringBuilder("Black Pixels: "); + var pixels = buffer.getPixels(); + for (var i = 0; i < pixels.length; ++i) { + if (pixels[i] == Pixel.BLACK) { + var y = i / FrameBuffer.WIDTH; + var x = i % FrameBuffer.WIDTH; + log.append(" (").append(x).append(", ").append(y).append(")"); + } + } + LOGGER.info(log.toString()); +} +``` + +La salida de la consola + +```text +[main] INFO com.iluwatar.doublebuffer.Scene - Start drawing next frame +[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 0 Next buffer: 1 +[main] INFO com.iluwatar.doublebuffer.Scene - Swap current and next buffer +[main] INFO com.iluwatar.doublebuffer.Scene - Finish swapping +[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 1 Next buffer: 0 +[main] INFO com.iluwatar.doublebuffer.Scene - Get current buffer: 1 +[main] INFO com.iluwatar.doublebuffer.App - Black Pixels: (1, 1) (3, 2) (5, 6) +[main] INFO com.iluwatar.doublebuffer.Scene - Start drawing next frame +[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 1 Next buffer: 0 +[main] INFO com.iluwatar.doublebuffer.Scene - Swap current and next buffer +[main] INFO com.iluwatar.doublebuffer.Scene - Finish swapping +[main] INFO com.iluwatar.doublebuffer.Scene - Current buffer: 0 Next buffer: 1 +[main] INFO com.iluwatar.doublebuffer.Scene - Get current buffer: 0 +[main] INFO com.iluwatar.doublebuffer.App - Black Pixels: (6, 1) (3, 7) +``` + +## Diagrama de clases + +![alt text](./etc/double-buffer.urm.png "Double Buffer pattern class diagram") + +## Aplicabilidad + +Este patrón es uno de esos que sabrás cuándo lo necesitas. Si tienes un sistema que carece de doble búfer, probablemente tendrá un aspecto visiblemente incorrecto (tearing, etc.) o se comportará de forma incorrecta. Pero decir "lo sabrás cuando lo necesites" no da mucho de sí. Más concretamente, este patrón es apropiado cuando todo esto es cierto: + +- Tenemos algún estado que está siendo modificado incrementalmente. +- Ese mismo estado puede ser accedido en medio de la modificación. +- Queremos evitar que el código que está accediendo al estado vea el trabajo en curso. +- Queremos poder leer el estado y no queremos tener que esperar mientras se escribe. + +## Créditos + +* [Game Programming Patterns - Double Buffer](http://gameprogrammingpatterns.com/double-buffer.html) diff --git a/localization/es/double-buffer/etc/double-buffer.urm.png b/localization/es/double-buffer/etc/double-buffer.urm.png new file mode 100644 index 000000000000..072ec4dad8be Binary files /dev/null and b/localization/es/double-buffer/etc/double-buffer.urm.png differ diff --git a/localization/es/embedded-value/README.md b/localization/es/embedded-value/README.md new file mode 100644 index 000000000000..4c1c0700f104 --- /dev/null +++ b/localization/es/embedded-value/README.md @@ -0,0 +1,139 @@ +--- +title: Embedded Value +shortTitle: Embedded Value +category: Structural +language: es +tag: + - Data Access + - Enterprise Application Pattern +--- + +## También conocido como + +Asignación agregada, Compositor + +## Propósito + +Muchos objetos pequeños tienen sentido en un sistema OO que no tienen sentido como tablas en una base de datos. Un valor +incrustado asigna los valores de un objeto a campos del registro del propietario del objeto. + +## Explicación + +Ejemplo real + +> Algunos ejemplos son los objetos monetarios y los intervalos de fechas. Aunque el pensamiento por defecto es guardar +> un objeto como una tabla, ninguna persona en su sano juicio querría una tabla de valores monetarios. +> Otro ejemplo serían los pedidos online que tienen una dirección de envío como calle, ciudad, estado. Asignamos estos +> valores del objeto Dirección de envío a los campos del registro del objeto Pedido. + +En pocas palabras + +> El patrón de valores incrustados permite asignar un objeto a varios campos de la tabla de otro objeto. + +**Ejemplo programático** + +Consideremos el ejemplo de un pedido online donde tenemos detalles del artículo pedido y la dirección de envío. Tenemos +la dirección de envío incrustada en el objeto Pedido. Pero en la base de datos asignamos los valores de la dirección de +envío en el registro del pedido en lugar de crear una tabla separada para la dirección de envío y utilizar una clave +externa para hacer referencia al objeto del pedido. + +Primero, tenemos POJOs `Order` y `ShippingAddress`. + +```java +public class Order { + + private int id; + private String item; + private String orderedBy; + private ShippingAddress ShippingAddress; + + public Order(String item, String orderedBy, ShippingAddress ShippingAddress) { + this.item = item; + this.orderedBy = orderedBy; + this.ShippingAddress = ShippingAddress; + } +``` + +```java +public class ShippingAddress { + + private String city; + private String state; + private String pincode; + + public ShippingAddress(String city, String state, String pincode) { + this.city = city; + this.state = state; + this.pincode = pincode; + } +} +``` + +Ahora, tenemos que crear sólo una tabla para el Pedido junto con los campos para los atributos de la dirección de envío. + +```Sql +CREATE TABLE Orders (Id INT AUTO_INCREMENT, item VARCHAR(50) NOT NULL, orderedBy VARCHAR(50) city VARCHAR(50), state VARCHAR(50), pincode CHAR(6) NOT NULL, PRIMARY KEY(Id)) +``` + +Mientras realizamos las consultas e inserciones en la base de datos, encasillamos y desencasillamos los detalles de las +direcciones de envío. + +```java +final String INSERT_ORDER = "INSERT INTO Orders (item, orderedBy, city, state, pincode) VALUES (?, ?, ?, ?, ?)"; + +public boolean insertOrder(Order order) throws Exception { + var insertOrder = new PreparedStatement(INSERT_ORDER); + var address = order.getShippingAddress(); + conn.setAutoCommit(false); + insertIntoOrders.setString(1, order.getItem()); + insertIntoOrders.setString(2, order.getOrderedBy()); + insertIntoOrders.setString(3, address.getCity()); + insertIntoOrders.setString(4, address.getState()); + insertIntoOrders.setString(5, address.getPincode()); + + var affectedRows = insertIntoOrders.executeUpdate(); + if(affectedRows == 1){ + Logger.info("Inserted successfully"); + }else{ + Logger.info("Couldn't insert " + order); + } +} +``` + +## Diagrama de clases + +![alt text](./etc/embedded-value.urm.png "Embedded value class diagram") + +## Aplicabilidad + +Utilice el patrón Valor incrustado cuando + +* Muchos objetos pequeños tienen sentido en un sistema OO que no tienen sentido como tablas en una base de datos. +* Los casos más simples para Embedded Value son los claros y simples Value Objects como dinero y rango de fechas. +* Si está mapeando a un esquema existente, puede utilizar este patrón cuando una tabla contiene datos que desea dividir + en más de un objeto en memoria. Esto puede ocurrir cuando se desea factorizar algún comportamiento en el modelo de + objetos. +* En la mayoría de los casos, sólo utilizará el valor incrustado en un objeto de referencia cuando la asociación entre + ellos tenga un único valor en ambos extremos (una asociación uno a uno). + +## Tutoriales + +* [Dzone](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-3) +* [Ram N Java](https://ramj2ee.blogspot.com/2013/08/embedded-value-design-pattern.html) +* [Five's Weblog](https://powerdream5.wordpress.com/2007/10/09/embedded-value/) + +## Consecuencias + +* La gran ventaja del valor incrustado es que permite realizar consultas SQL contra los valores del objeto dependiente. +* El objeto valor incrustado no tiene ningún comportamiento de persistencia. +* Al usar esto, tienes que tener cuidado de que cualquier cambio en el dependiente marque al propietario como sucio-lo + cual no es un problema con los Objetos de Valor que son reemplazados en el propietario. +* Otro problema es la carga y el guardado. Si sólo carga la memoria del objeto incrustado cuando carga el propietario, + eso es un argumento para guardar ambos en la misma tabla. +* Otra cuestión es si querrás acceder a los datos de los objetos incrustados por separado a través de SQL. Esto puede + ser importante si estás haciendo informes a través de SQL y no tienes una base de datos separada para los informes. + +## Créditos + +* [Fowler, Martin - Patterns of enterprise application architecture-Addison-Wesley](https://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420) +* [Ram N Java](https://ramj2ee.blogspot.com/2013/08/embedded-value-design-pattern.html) \ No newline at end of file diff --git a/localization/es/embedded-value/etc/embedded-value.urm.png b/localization/es/embedded-value/etc/embedded-value.urm.png new file mode 100644 index 000000000000..52d3ffb62352 Binary files /dev/null and b/localization/es/embedded-value/etc/embedded-value.urm.png differ diff --git a/localization/es/event-aggregator/README.md b/localization/es/event-aggregator/README.md new file mode 100644 index 000000000000..83e40117dd4d --- /dev/null +++ b/localization/es/event-aggregator/README.md @@ -0,0 +1,171 @@ +--- +title: Event Aggregator +shortTitle: Event Aggregator +category: Structural +language: es +tag: + - Reactive +--- + +## Nombre + +Agregador de eventos + +## Intención + +Un sistema con muchos objetos puede resultar complejo cuando un cliente quiere suscribirse a eventos. El cliente tiene +que encontrar y registrarse para +cada objeto individualmente, si cada objeto tiene múltiples eventos entonces cada evento requiere una suscripción +separada. Un Agregador de Eventos actúa como una única fuente +de eventos para muchos objetos. Se registra para todos los eventos de los muchos objetos permitiendo a los clientes +registrarse sólo con el agregador. + +## Explicación + +Un ejemplo real + +> El rey Joffrey se sienta en el trono de hierro y gobierna los siete reinos de Poniente. Recibe la mayor parte de su +> información crítica de Mano del Rey, el segundo al mando. La Mano del Rey tiene muchos consejeros cercanos que le +> proporcionan información relevante sobre los acontecimientos que ocurren en el reino. + +En pocas palabras + +> El Agregador de Eventos es un mediador de eventos que recoge eventos de múltiples fuentes y los entrega a los +> observadores registrados. + +**Ejemplo programático** + +En nuestro ejemplo programático, demostramos la implementación de un patrón agregador de eventos. Algunos de los objetos +son escuchadores de eventos, otros son emisores de eventos, y el agregador de eventos hace ambas cosas. + +```java +public interface EventObserver { + void onEvent(Event e); +} + +public abstract class EventEmitter { + + private final Map> observerLists; + + public EventEmitter() { + observerLists = new HashMap<>(); + } + + public final void registerObserver(EventObserver obs, Event e) { + ... + } + + protected void notifyObservers(Event e) { + ... + } +} +``` + +`KingJoffrey` está escuchando eventos de `KingsHand`. + +```java +@Slf4j +public class KingJoffrey implements EventObserver { + @Override + public void onEvent(Event e) { + LOGGER.info("Received event from the King's Hand: {}", e.toString()); + } +} +``` + +El `ReyMano` está escuchando los acontecimientos de sus subordinados `LordBaelish`, `LordVarys` y `Scout`. +Lo que escuche de ellos, se lo entrega al "Rey Joffrey". + +```java +public class KingsHand extends EventEmitter implements EventObserver { + + public KingsHand() { + } + + public KingsHand(EventObserver obs, Event e) { + super(obs, e); + } + + @Override + public void onEvent(Event e) { + notifyObservers(e); + } +} +``` + +Por ejemplo, `LordVarys` encuentra un traidor cada domingo y lo notifica al `KingsHand`. + +```java +@Slf4j +public class LordVarys extends EventEmitter implements EventObserver { + @Override + public void timePasses(Weekday day) { + if (day == Weekday.SATURDAY) { + notifyObservers(Event.TRAITOR_DETECTED); + } + } +} +``` + +El siguiente fragmento muestra cómo se construyen y conectan los objetos. + +```java + var kingJoffrey = new KingJoffrey(); + + var kingsHand = new KingsHand(); + kingsHand.registerObserver(kingJoffrey, Event.TRAITOR_DETECTED); + kingsHand.registerObserver(kingJoffrey, Event.STARK_SIGHTED); + kingsHand.registerObserver(kingJoffrey, Event.WARSHIPS_APPROACHING); + kingsHand.registerObserver(kingJoffrey, Event.WHITE_WALKERS_SIGHTED); + + var varys = new LordVarys(); + varys.registerObserver(kingsHand, Event.TRAITOR_DETECTED); + varys.registerObserver(kingsHand, Event.WHITE_WALKERS_SIGHTED); + + var scout = new Scout(); + scout.registerObserver(kingsHand, Event.WARSHIPS_APPROACHING); + scout.registerObserver(varys, Event.WHITE_WALKERS_SIGHTED); + + var baelish = new LordBaelish(kingsHand, Event.STARK_SIGHTED); + + var emitters = List.of( + kingsHand, + baelish, + varys, + scout + ); + + Arrays.stream(Weekday.values()) + .>map(day -> emitter -> emitter.timePasses(day)) + .forEachOrdered(emitters::forEach); +``` + +La salida de la consola después de ejecutar el ejemplo. + +``` +18:21:52.955 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: Warships approaching +18:21:52.960 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: White walkers sighted +18:21:52.960 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: Stark sighted +18:21:52.960 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: Traitor detected +``` + +## Diagrama de clases + +![alt text](etc/classes.png "Event Aggregator") + +## Aplicabilidad + +Utilice el patrón Agregador de eventos cuando + +* El Agregador de Eventos es una buena opción cuando tienes muchos objetos que son fuentes potenciales de eventos. En + lugar de hacer que el observador se ocupe de registrarse con todos ellos, puedes centralizar la lógica de registro en + el Agregador de Eventos. Además de simplificar el registro, un Agregador de Eventos también simplifica los problemas + de gestión de memoria en el uso de observadores. + +## Patrones relacionados + +* [Observer](https://java-design-patterns.com/patterns/observer/) + +## Créditos + +* [Martin Fowler - Event Aggregator](http://martinfowler.com/eaaDev/EventAggregator.html) diff --git a/localization/es/event-aggregator/etc/classes.png b/localization/es/event-aggregator/etc/classes.png new file mode 100644 index 000000000000..295719ea3712 Binary files /dev/null and b/localization/es/event-aggregator/etc/classes.png differ diff --git a/localization/es/extension-objects/README.md b/localization/es/extension-objects/README.md new file mode 100644 index 000000000000..5e01d85c8740 --- /dev/null +++ b/localization/es/extension-objects/README.md @@ -0,0 +1,143 @@ +--- +title: Extension objects +shortTitle: Extension objects +category: Behavioral +language: es +tag: + - Extensibility +--- + +# Extention Objects Pattern + +## Propósito +Anticipar que la interfaz de un objeto debe ampliarse en el futuro. Las interfaces adicionales se definen mediante objetos de extensión (Extension objects). + +## Explicación +Ejemplo real + +> Suponga que está desarrollando un juego basado en Java para un cliente y, en mitad del proceso de desarrollo, le sugieren nuevas funcionalidades. El patrón Extension Objects permite a su programa adaptarse a cambios imprevistos con una refactorización mínima, especialmente al integrar funcionalidades adicionales en su proyecto. + +En palabras sencillas + +> El patrón Extension Objects se utiliza para añadir dinámicamente funcionalidad a los objetos sin modificar sus clases principales. Es un patrón de diseño de comportamiento utilizado para añadir nuevas funcionalidades a clases y objetos existentes dentro de un programa. Este patrón proporciona a los programadores la capacidad de extender/modificar la funcionalidad de las clases sin tener que refactorizar el código fuente existente. + +Wikipedia dice + +> En la programación informática orientada a objetos, un patrón de objetos de extensión es un patrón de diseño añadido a un objeto después de que el objeto original fue compilado. El objeto modificado es a menudo una clase, un prototipo o un tipo. Los patrones de objetos de extensión son características de algunos lenguajes de programación orientados a objetos. No hay diferencia sintáctica entre llamar a un método de extensión y llamar a un método declarado en la definición del tipo. + +**Ejemplo programático** + +El objetivo de utilizar el patrón de objetos de extensión (Extension objects) es implementar nuevas características/funcionalidades sin tener que refactorizar cada clase. +Los siguientes ejemplos muestran la utilización de este patrón para una clase Enemigo que extiende Entidad dentro de un juego: + +Clase App primaria desde la que ejecutar nuestro programa. + +```java +public class App { + public static void main(String[] args) { + Entity enemy = new Enemy("Enemy"); + checkExtensionsForEntity(enemy); + } + + private static void checkExtensionsForEntity(Entity entity) { + Logger logger = Logger.getLogger(App.class.getName()); + String name = entity.getName(); + Function func = (e) -> () -> logger.info(name + " without " + e); + + String extension = "EnemyExtension"; + Optional.ofNullable(entity.getEntityExtension(extension)) + .map(e -> (EnemyExtension) e) + .ifPresentOrElse(EnemyExtension::extendedAction, func.apply(extension)); + } +} +``` +Clase de enemigo con acciones iniciales y extensiones. + +```java +class Enemy extends Entity { + public Enemy(String name) { + super(name); + } + + @Override + protected void performInitialAction() { + super.performInitialAction(); + System.out.println("Enemy wants to attack you."); + } + + @Override + public EntityExtension getEntityExtension(String extensionName) { + if (extensionName.equals("EnemyExtension")) { + return Optional.ofNullable(entityExtension).orElseGet(EnemyExtension::new); + } + return super.getEntityExtension(extensionName); + } +} +``` + +Clase EnemyExtension con sobreescritura del método extendAction(). + +```java +class EnemyExtension implements EntityExtension { + @Override + public void extendedAction() { + System.out.println("Enemy has advanced towards you!"); + } +} +``` + +Clase de entidad que será extendida por Enemy. + +```java +class Entity { + private String name; + protected EntityExtension entityExtension; + + public Entity(String name) { + this.name = name; + performInitialAction(); + } + + protected void performInitialAction() { + System.out.println(name + " performs the initial action."); + } + + public EntityExtension getEntityExtension(String extensionName) { + return null; + } + + public String getName() { + return name; + } +} +``` +Interfaz EntityExtension que utilizará EnemyExtension. + +```java +interface EntityExtension { + void extendedAction(); +} +``` +Salida del programa: + +```markdown +Enemy performs the initial action. +Enemy wants to attack you. +Enemy has advanced towards you! +``` +En este ejemplo, el patrón de Objetos de Extensión permite a la entidad enemiga realizar acciones iniciales únicas y acciones avanzadas cuando se aplican extensiones específicas. Este patrón proporciona flexibilidad y extensibilidad a la base de código a la vez que minimiza la necesidad de realizar cambios importantes en el código. + +## Diagrama de clases +![Extension_objects](./etc/extension_obj.png "Extension objects") + +## Aplicabilidad +Utilice el patrón de Objetos de Extensión (Extension objects) cuando: + +* Necesita soportar la adición de interfaces nuevas o imprevistas a clases existentes y no quieres impactar a clientes que no necesitan esta nueva interfaz. Los objetos de extensión te permiten mantener juntas operaciones relacionadas definiéndolas en una clase separada +* Una clase que representa una abstracción clave desempeña diferentes funciones para diferentes clientes. El número de funciones que puede desempeñar la clase debe ser ilimitado. Es necesario preservar la propia abstracción clave. Por ejemplo, un objeto cliente sigue siendo un objeto cliente aunque distintos subsistemas lo vean de forma diferente. +* Una clase debe ser extensible con nuevos comportamientos sin necesidad de subclasificar a partir de ella. + +## Ejemplos del mundo real + +* [OpenDoc](https://en.wikipedia.org/wiki/OpenDoc) +* [Object Linking and Embedding](https://en.wikipedia.org/wiki/Object_Linking_and_Embedding) diff --git a/localization/es/extension-objects/etc/extension_obj.png b/localization/es/extension-objects/etc/extension_obj.png new file mode 100644 index 000000000000..a2b750e9dedd Binary files /dev/null and b/localization/es/extension-objects/etc/extension_obj.png differ diff --git a/localization/es/facade/README.md b/localization/es/facade/README.md new file mode 100644 index 000000000000..75f59817aaea --- /dev/null +++ b/localization/es/facade/README.md @@ -0,0 +1,225 @@ +--- +title: Facade +shortTitle: Facade +category: Structural +language: es +tag: + - Gang Of Four + - Decoupling +--- + +## Propósito + +Proporcionar una interfaz unificada a un conjunto de interfaces de un subsistema. La fachada define una interfaz que +facilita el uso del subsistema. + +## Explicación + +Un ejemplo real + +> ¿Cómo funciona una mina de oro? "¡Bueno, los mineros bajan y sacan oro!" dices. Eso es lo que crees porque estás +> usando una interfaz simple que la mina de oro proporciona en el exterior, internamente tiene que hacer un montón de +> cosas para que suceda. Esta interfaz simple al subsistema complejo es una fachada. + +En pocas palabras + +> El patrón Facade proporciona una interfaz simplificada a un subsistema complejo. + +Wikipedia dice + +> Una fachada es un objeto que proporciona una interfaz simplificada a un cuerpo de código mayor, como una biblioteca de +> clases. + +**Ejemplo programático** + +Tomemos el ejemplo de la mina de oro. Aquí tenemos la jerarquía de los trabajadores enanos de la mina. Primero hay una +clase base `DwarvenMineWorker`: + +```java + +@Slf4j +public abstract class DwarvenMineWorker { + + public void goToSleep() { + LOGGER.info("{} goes to sleep.", name()); + } + + public void wakeUp() { + LOGGER.info("{} wakes up.", name()); + } + + public void goHome() { + LOGGER.info("{} goes home.", name()); + } + + public void goToMine() { + LOGGER.info("{} goes to the mine.", name()); + } + + private void action(Action action) { + switch (action) { + case GO_TO_SLEEP -> goToSleep(); + case WAKE_UP -> wakeUp(); + case GO_HOME -> goHome(); + case GO_TO_MINE -> goToMine(); + case WORK -> work(); + default -> LOGGER.info("Undefined action"); + } + } + + public void action(Action... actions) { + Arrays.stream(actions).forEach(this::action); + } + + public abstract void work(); + + public abstract String name(); + + enum Action { + GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK + } +} +``` + +Luego tenemos las clases concretas enanas `DwarvenTunnelDigger`, `DwarvenGoldDigger` y `DwarvenCartOperator`: + +```java +@Slf4j +public class DwarvenTunnelDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} creates another promising tunnel.", name()); + } + + @Override + public String name() { + return "Dwarven tunnel digger"; + } +} + +@Slf4j +public class DwarvenGoldDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} digs for gold.", name()); + } + + @Override + public String name() { + return "Dwarf gold digger"; + } +} + +@Slf4j +public class DwarvenCartOperator extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} moves gold chunks out of the mine.", name()); + } + + @Override + public String name() { + return "Dwarf cart operator"; + } +} + +``` + +Para manejar a todos estos trabajadores de la mina de oro tenemos la `FachadaDwarvenGoldmine`: + +```java +public class DwarvenGoldmineFacade { + + private final List workers; + + public DwarvenGoldmineFacade() { + workers = List.of( + new DwarvenGoldDigger(), + new DwarvenCartOperator(), + new DwarvenTunnelDigger()); + } + + public void startNewDay() { + makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); + } + + public void digOutGold() { + makeActions(workers, DwarvenMineWorker.Action.WORK); + } + + public void endDay() { + makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); + } + + private static void makeActions(Collection workers, + DwarvenMineWorker.Action... actions) { + workers.forEach(worker -> worker.action(actions)); + } +} +``` + +Ahora vamos a utilizar la fachada: + +```java +var facade = new DwarvenGoldmineFacade(); +facade.startNewDay(); +facade.digOutGold(); +facade.endDay(); +``` + +Salida del programa: + +```java +// Dwarf gold digger wakes up. +// Dwarf gold digger goes to the mine. +// Dwarf cart operator wakes up. +// Dwarf cart operator goes to the mine. +// Dwarven tunnel digger wakes up. +// Dwarven tunnel digger goes to the mine. +// Dwarf gold digger digs for gold. +// Dwarf cart operator moves gold chunks out of the mine. +// Dwarven tunnel digger creates another promising tunnel. +// Dwarf gold digger goes home. +// Dwarf gold digger goes to sleep. +// Dwarf cart operator goes home. +// Dwarf cart operator goes to sleep. +// Dwarven tunnel digger goes home. +// Dwarven tunnel digger goes to sleep. +``` + +## Diagrama de clases + +![alt text](./etc/facade.urm.png "Facade pattern class diagram") + +## Aplicabilidad + +Utilice el patrón Fachada cuando + +* Quieres proporcionar una interfaz sencilla a un subsistema complejo. Los subsistemas a menudo se vuelven más complejos + a medida que evolucionan. La mayoría de los patrones, cuando se aplican, dan como resultado más clases y más pequeñas. + Esto hace que el subsistema sea más reutilizable y más fácil de personalizar, pero también se vuelve más difícil de + usar para los clientes que no necesitan personalizarlo. Una fachada puede proporcionar una simple vista por defecto + del subsistema que es lo suficiente para la mayoría de los clientes. Sólo los clientes que necesiten más + personalización tendrán que mirar más allá de la fachada. +* Hay muchas dependencias entre los clientes y las clases de implementación de una abstracción. + Introducir una fachada para desacoplar el subsistema de los clientes y otros subsistemas, promoviendo así + independencia y portabilidad del subsistema. +* Quieres estratificar tus subsistemas. Utiliza una fachada para definir un punto de entrada a cada nivel de subsistema. + Si los subsistemas son dependientes, puedes simplificar las dependencias entre ellos haciéndolos que se comuniquen + entre sí únicamente a través de sus fachadas. + +## Tutoriales + +*[DigitalOcean](https://www.digitalocean.com/community/tutorials/facade-design-pattern-in-java) + +* [Refactoring Guru](https://refactoring.guru/design-patterns/facade) +* [GeekforGeeks](https://www.geeksforgeeks.org/facade-design-pattern-introduction/) +* [Tutorialspoint](https://www.tutorialspoint.com/design_pattern/facade_pattern.htm) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/es/facade/etc/facade.urm.png b/localization/es/facade/etc/facade.urm.png new file mode 100644 index 000000000000..8e3ec7aca45e Binary files /dev/null and b/localization/es/facade/etc/facade.urm.png differ diff --git a/localization/es/factory-kit/README.md b/localization/es/factory-kit/README.md new file mode 100644 index 000000000000..cd5fca8f5b50 --- /dev/null +++ b/localization/es/factory-kit/README.md @@ -0,0 +1,133 @@ +--- +title: Factory Kit +shortTitle: Factory Kit +category: Creational +language: es +tag: + - Extensibility +--- + +## También conocido como + +Abstract-Factory + +## Propósito + +Define una fábrica de contenido inmutable con interfaces de constructor y fábrica separadas. + +## Explicación + +Ejemplo del mundo real + +> Imagina una fábrica de armas mágicas que puede crear cualquier tipo de arma que se desee. Cuando la fábrica se +> desempaqueta, el maestro recita los tipos de armas necesarios para prepararla. Después de eso, cualquiera de esos +> tipos +> de armas pueden ser invocados en un instante. + +En palabras sencillas + +> El kit de fábrica (Kit Factory) es un constructor de objetos configurable, una fábrica para crear fábricas. + +**Ejemplo programático** + +Definamos primero la interfaz simple arma `Weapon`. + +```java +public interface Weapon { +} + +public enum WeaponType { + SWORD, + AXE, + BOW, + SPEAR +} + +public class Sword implements Weapon { + @Override + public String toString() { + return "Sword"; + } +} + +// Hacha `Axe`, Arco `Bow` y Lanza `Spear` se definen de forma similar +``` + +A continuación, definimos una interfaz funcional que permite añadir un constructor con un nombre a la fábrica. + +```java +public interface Builder { + void add(WeaponType name, Supplier supplier); +} +``` + +El núcleo del ejemplo es la interfaz `WeaponFactory` que implementa el patrón de fábrica. El método `#factory` se +utiliza para configurar la fábrica con las clases que necesita para ser capaz de construir. El método `#create` se +utiliza para crear instancias del objeto. + +```java +public interface WeaponFactory { + + static WeaponFactory factory(Consumer consumer) { + var map = new HashMap>(); + consumer.accept(map::put); + return name -> map.get(name).get(); + } + + Weapon create(WeaponType name); +} +``` + +Ahora, podemos mostrar cómo se puede utilizar `WeaponFactory`. + +```java +var factory = WeaponFactory.factory(builder -> { + builder.add(WeaponType.SWORD, Sword::new); + builder.add(WeaponType.AXE, Axe::new); + builder.add(WeaponType.SPEAR, Spear::new); + builder.add(WeaponType.BOW, Bow::new); +}); +var list = new ArrayList(); +list.add(factory.create(WeaponType.AXE)); +list.add(factory.create(WeaponType.SPEAR)); +list.add(factory.create(WeaponType.SWORD)); +list.add(factory.create(WeaponType.BOW)); +list.stream().forEach(weapon -> LOGGER.info("{}", weapon.toString())); +``` + +Esta es la salida de la consola cuando se ejecuta el ejemplo. + +``` +21:15:49.709 [main] INFO com.iluwatar.factorykit.App - Axe +21:15:49.713 [main] INFO com.iluwatar.factorykit.App - Spear +21:15:49.713 [main] INFO com.iluwatar.factorykit.App - Sword +21:15:49.713 [main] INFO com.iluwatar.factorykit.App - Bow +``` + +## Diagrama de clases + +![alt text](./etc/factory-kit.png "Factory Kit") + +## Aplicabilidad + +Utilice el patrón Factory Kit cuando + +* La clase de fábrica no puede anticipar los tipos de objetos que debe crear. +* Se necesita una nueva instancia de un constructor personalizado en lugar de uno global. +* Los tipos de objetos que la fábrica puede construir necesitan ser definidos fuera de la clase. +* Es necesario separar las interfaces del constructor y del creador. +* Desarrollos de juegos y otras aplicaciones que tienen personalización del usuario + +## Patrones relacionados + +* [Builder](https://java-design-patterns.com/patterns/builder/) +* [Factory](https://java-design-patterns.com/patterns/factory/) +* [Abstract-Factory](https://java-design-patterns.com/patterns/abstract-factory/) + +## Tutoriales + +* [Factory kit implementation tutorial](https://diego-pacheco.medium.com/factory-kit-pattern-66d5ccb0c405) + +## Créditos + +* [Design Pattern Reloaded by Remi Forax](https://www.youtube.com/watch?v=-k2X7guaArU) diff --git a/localization/es/factory-kit/etc/factory-kit.png b/localization/es/factory-kit/etc/factory-kit.png new file mode 100644 index 000000000000..7093193cb8d0 Binary files /dev/null and b/localization/es/factory-kit/etc/factory-kit.png differ diff --git a/localization/es/factory-method/README.md b/localization/es/factory-method/README.md new file mode 100644 index 000000000000..b4e9144ac247 --- /dev/null +++ b/localization/es/factory-method/README.md @@ -0,0 +1,115 @@ +--- +title: Factory Method +shortTitle: Factory Method +category: Creational +language: es +tag: + - Extensibility + - Gang of Four +--- + +## También conocido como + +Virtual Constructor + +## Propósito + +Definir una interfaz para crear un objeto, pero dejar que las subclases decidan qué clase instanciar. El método de +fábrica permite que una clase difiera la instanciación a las subclases. + +## Explicación + +Ejemplo del mundo real + +> El herrero fabrica armas. Los elfos requieren armas élficas y los orcos requieren armas orcas. Dependiendo del cliente +> en cuestión, se convoca al tipo correcto de herrero. + +En palabras sencillas + +> Proporciona una forma de delegar la lógica de instanciación a las clases hijas. + +Wikipedia dice + +> En la programación basada en clases, el patrón de método de fábrica es un patrón de creación que utiliza métodos de +> fábrica para lidiar con el problema de crear objetos sin tener que especificar la clase exacta del objeto que se +> creará. +> Esto se hace creando objetos llamando a un método de fábrica — ya sea especificado en una interfaz e implementado por +> clases hijas, o implementado en una clase base y opcionalmente sobrescrito por clases derivadas — en lugar de llamar a +> un constructor. + +**Ejemplo programático** + +Tomando nuestro ejemplo del herrero. En primer lugar, tenemos una interfaz `Blacksmith` y algunas implementaciones para +ello: + +```java +public interface Blacksmith { + Weapon manufactureWeapon(WeaponType weaponType); +} + +public class ElfBlacksmith implements Blacksmith { + public Weapon manufactureWeapon(WeaponType weaponType) { + return ELFARSENAL.get(weaponType); + } +} + +public class OrcBlacksmith implements Blacksmith { + public Weapon manufactureWeapon(WeaponType weaponType) { + return ORCARSENAL.get(weaponType); + } +} +``` + +Cuando llegan los clientes, se llama al herrero adecuado y se fabrican las armas solicitadas: + +```java +Blacksmith blacksmith = new OrcBlacksmith(); +Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); +LOGGER.info("{} manufactured {}", blacksmith, weapon); +weapon = blacksmith.manufactureWeapon(WeaponType.AXE); +LOGGER.info("{} manufactured {}", blacksmith, weapon); + +blacksmith = new ElfBlacksmith(); +weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); +LOGGER.info("{} manufactured {}", blacksmith, weapon); +weapon = blacksmith.manufactureWeapon(WeaponType.AXE); +LOGGER.info("{} manufactured {}", blacksmith, weapon); +``` + +Salida del programa: + +``` +The orc blacksmith manufactured an orcish spear +The orc blacksmith manufactured an orcish axe +The elf blacksmith manufactured an elven spear +The elf blacksmith manufactured an elven axe +``` + +## Diagrama de clases + +![alt text](./etc/factory-method.urm.png "Factory Method pattern diagrama de clases") + +## Aplicabilidad + +Utilice el patrón Método de Fábrica cuando: + +* La clase no puede anticipar la clase de objetos que debe crear. +* La clase quiere que sus subclases especifiquen los objetos que crea. +* Las clases delegan la responsabilidad a una de varias subclases ayudantes, y desea localizar el conocimiento de qué + subclase ayudante es el delegado. conocimiento de qué subclase ayudante es el delegado. + +## Usos conocidos + +* [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +* [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +* [java.text.NumberFormat](http://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +* [java.nio.charset.Charset](http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +* [java.net.URLStreamHandlerFactory](http://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html#createURLStreamHandler-java.lang.String-) +* [java.util.EnumSet](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of-E-) +* [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/factory-method/etc/factory-method.urm.png b/localization/es/factory-method/etc/factory-method.urm.png new file mode 100644 index 000000000000..7c97aff91ee6 Binary files /dev/null and b/localization/es/factory-method/etc/factory-method.urm.png differ diff --git a/localization/es/factory/README.md b/localization/es/factory/README.md new file mode 100644 index 000000000000..d27076e45148 --- /dev/null +++ b/localization/es/factory/README.md @@ -0,0 +1,144 @@ +--- +title: Factory +shortTitle: Factory +category: Creational +language: es +tag: + - Gang of Four +--- + +## También conocido como + +* Simple Factory +* Static Factory Method + +## Propósito + +Proporcionar un método estático encapsulado en una clase llamada fábrica (Factory), para ocultar la lógica de +implementación y +hacer que el código del cliente se centre en el uso en lugar de inicializar nuevos objetos. + +## Explicación + +Ejemplo del mundo real + +> Imagina un alquimista que está a punto de fabricar monedas. El alquimista debe ser capaz de crear tanto monedas de oro +> como de cobre y cambiar entre ellas debe ser posible sin modificar el código fuente existente. El patrón de fábrica lo +> hace posible proporcionando un método de construcción estático que puede ser llamado con los parámetros relevantes. + +Wikipedia dice + +> La fábrica (Factory) es un objeto para crear otros objetos: formalmente, una fábrica es una función o método que +> devuelve objetos de un prototipo o clase variable. + +**Ejemplo programático** + +Tenemos una interfaz moneda `Coin` y dos implementaciones moneda de oro `GoldCoin` y moneda de cobre `CopperCoin`. + +```java +public interface Coin { + String getDescription(); +} + +public class GoldCoin implements Coin { + + static final String DESCRIPTION = "This is a gold coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class CopperCoin implements Coin { + + static final String DESCRIPTION = "This is a copper coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +La siguiente enumeración representa los tipos de monedas que admitimos (`GoldCoin` y `CopperCoin`). + +```java +@RequiredArgsConstructor +@Getter +public enum CoinType { + + COPPER(CopperCoin::new), + GOLD(GoldCoin::new); + + private final Supplier constructor; +} +``` + +Luego tenemos el método estático obtener moneda `getCoin` para crear objetos moneda encapsulados en la clase fábrica +`CoinFactory`. + +```java +public class CoinFactory { + + public static Coin getCoin(CoinType type) { + return type.getConstructor().get(); + } +} +``` + +Ahora en el código cliente podemos crear diferentes tipos de monedas utilizando la clase fábrica. + +```java +LOGGER.info("The alchemist begins his work."); +var coin1 = CoinFactory.getCoin(CoinType.COPPER); +var coin2 = CoinFactory.getCoin(CoinType.GOLD); +LOGGER.info(coin1.getDescription()); +LOGGER.info(coin2.getDescription()); +``` + +Salida del programa: + +```java +The alchemist begins his work. +This is a copper coin. +This is a gold coin. +``` + +## Diagrama de clases + +![alt text](./etc/factory.urm.png "Factory pattern diagrama de clases") + +## Aplicabilidad + +Utilice el patrón de fábrica cuando solo se preocupe por la creación de un objeto, no de cómo crearlo +y gestionarlo. + +Ventajas + +* Permite mantener toda la creación de objetos en un solo lugar y evitar la propagación de la palabra clave 'new' a + través de la base de código. +* Permite escribir código poco acoplado. Algunas de sus principales ventajas incluyen mejor testabilidad, código fácil + de entender, componentes intercambiables, escalabilidad y características aisladas. + +Contras + +* El código se vuelve más complicado de lo que debería. + +## Usos conocidos + +* [java.util.Calendar#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +* [java.util.ResourceBundle#getBundle()](https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +* [java.text.NumberFormat#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +* [java.nio.charset.Charset#forName()](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +* [java.net.URLStreamHandlerFactory#createURLStreamHandler(String)](https://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html) ( + devuelve diferentes objetos singleton, en función de un protocolo) +* [java.util.EnumSet#of()](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of(E)) +* [javax.xml.bind.JAXBContext#createMarshaller()](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) + y otros métodos similares. + +## Patrones relacionados + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/) diff --git a/localization/es/factory/etc/factory.urm.png b/localization/es/factory/etc/factory.urm.png new file mode 100644 index 000000000000..4b3420792e06 Binary files /dev/null and b/localization/es/factory/etc/factory.urm.png differ diff --git a/localization/es/feature-toggle/README.md b/localization/es/feature-toggle/README.md new file mode 100644 index 000000000000..3e5a2134d55b --- /dev/null +++ b/localization/es/feature-toggle/README.md @@ -0,0 +1,76 @@ +--- +title: Feature Toggle +shortTitle: Feature Toggle +category: Behavioral +language: es +tag: + - Extensibility +--- + +## También conocido como +Feature Flag + +## Propósito +Técnica utilizada en el desarrollo de software para controlar y gestionar el despliegue de características o funcionalidades específicas en un programa sin cambiar el código. Puede actuar como un interruptor de encendido/apagado de funciones en función del estado o las propiedades de otros valores del programa. Esto es similar a las pruebas A/B, en las que las funciones se despliegan en función de propiedades como la ubicación o el dispositivo. La implementación de este patrón de diseño puede aumentar la complejidad del código, y es importante recordar eliminar el código redundante si este patrón de diseño se utiliza para eliminar gradualmente un sistema o característica. + +## Explicación +Ejemplo del mundo real +> Este patrón de diseño funciona realmente bien en cualquier tipo de desarrollo, en particular en el desarrollo móvil. Digamos que quieres introducir una característica como el modo oscuro, pero quieres asegurarte de que la característica funciona correctamente y no quieres desplegar la característica a todo el mundo inmediatamente. Escribes el código y lo desactivas por defecto. A partir de aquí, es fácil activar el código para usuarios específicos basándose en criterios de selección, o aleatoriamente. Esto también permitirá que la función se desactive fácilmente sin ningún cambio drástico en el código, o cualquier necesidad de redistribución o actualizaciones. + +En pocas palabras +> Feature Toggle es una forma de introducir nuevas funciones gradualmente en lugar de desplegarlas todas a la vez. + +Wikipedia dice +> Una función de conmutación en el desarrollo de software proporciona una alternativa al mantenimiento de múltiples ramas de características en el código fuente. Una condición dentro del código activa o desactiva una característica durante el tiempo de ejecución. En un entorno ágil, el conmutador se utiliza en producción, para activar la función bajo demanda, para algunos o todos los usuarios. + +**Ejemplo programático** +Este ejemplo muestra código Java que permite mostrar una funcionalidad cuando es activada por el desarrollador, y cuando un usuario es miembro Premium de la aplicación. Esto es útil para características bloqueadas por suscripción. + +```java +public class FeatureToggleExample { + // Bool for feature enabled or disabled + private static boolean isNewFeatureEnabled = false; + + public static void main(String[] args) { + boolean userIsPremium = true; // Example: Check if the user is a premium user + + // Check if the new feature should be enabled for the user + if (userIsPremium && isNewFeatureEnabled) { + // User is premium and the new feature is enabled + showNewFeature(); + } + } + + private static void showNewFeature() { + // If user is allowed to see locked feature, this is where the code would go + } +} +``` +El código muestra lo sencillo que es aplicar este patrón de diseño, y los criterios pueden refinarse o ampliarse aún más si los desarrolladores así lo deciden. + +## Diagrama de clases +![alt text](./etc/feature-toggle.png "Feature Toggle") + +## Aplicabilidad +Utilice el patrón de alternancia de funciones cuando + +* Dar diferentes características a diferentes usuarios. +* Desplegar una nueva característica de forma incremental. +* Cambiar entre entornos de desarrollo y producción. +* Desactivar rápidamente funciones problemáticas. +* Gestión externa del despliegue de características. +* Capacidad de mantener múltiples versiones de una característica. +* Despliegue "oculto", liberando una característica en código para pruebas designadas, pero sin ponerla a disposición del público. + +## Consecuencias +Consecuencias del uso del patrón de alternancia de funciones + +* Aumenta la complejidad del código +* Probar múltiples estados es más difícil y consume más tiempo +* Confusión entre amigos sobre por qué faltan características +* Mantener la documentación actualizada con todas las características puede ser difícil. + +## Créditos + +* [Martin Fowler 29 October 2010 (2010-10-29).](http://martinfowler.com/bliki/FeatureToggle.html) +* [Feature Toggle - Java Design Patterns](https://java-design-patterns.com/patterns/feature-toggle/) diff --git a/localization/es/feature-toggle/etc/feature-toggle.png b/localization/es/feature-toggle/etc/feature-toggle.png new file mode 100644 index 000000000000..5c118e57e44e Binary files /dev/null and b/localization/es/feature-toggle/etc/feature-toggle.png differ diff --git a/localization/es/flux/README.md b/localization/es/flux/README.md new file mode 100644 index 000000000000..c54e6b662cd4 --- /dev/null +++ b/localization/es/flux/README.md @@ -0,0 +1,26 @@ +--- +title: Flux +shortTitle: Flux +category: Structural +language: es +tag: + - Decoupling +--- + +## Propósito +Flux evita MVC en favor de un flujo de datos unidireccional. Cuando un usuario +usuario interactúa con una vista, ésta propaga una acción a través de un +central, a los distintos almacenes que contienen los datos de la aplicación y la +que actualiza todas las vistas afectadas. + +## Diagrama de clases +![alt text](./etc/flux.png "Flux") + +## Aplicabilidad +Utilice el patrón Flux cuando + +* Debes centrarte en crear rutas de actualización explícitas y comprensibles para los datos de tu aplicación, lo que simplifica el seguimiento de los cambios durante el desarrollo y facilita la localización y corrección de errores. + +## Créditos + +* [Flux - Application architecture for building user interfaces](http://facebook.github.io/flux/) diff --git a/localization/es/flux/etc/flux.png b/localization/es/flux/etc/flux.png new file mode 100644 index 000000000000..9cb596eaf03d Binary files /dev/null and b/localization/es/flux/etc/flux.png differ diff --git a/localization/es/flyweight/README.md b/localization/es/flyweight/README.md new file mode 100644 index 000000000000..8ef93943aa82 --- /dev/null +++ b/localization/es/flyweight/README.md @@ -0,0 +1,209 @@ +--- +title: Flyweight +shortTitle: Flyweight +category: Structural +language: es +tag: + - Gang of Four + - Performance +--- + +## Propósito + +Utilice la compartición para dar soporte a un gran número de objetos finos de forma eficiente. + +## Explicación + +Un ejemplo real + +> La tienda del alquimista tiene estanterías llenas de pociones mágicas. Muchas de las pociones son las mismas, por lo +> que no es necesario crear un nuevo objeto para cada una de ellas. En su lugar, una instancia de objeto puede +> representar +> múltiples elementos de la estantería para que la huella de memoria siga siendo pequeña. + +En pocas palabras + +> Se utiliza para minimizar el uso de memoria o los gastos computacionales compartiendo todo lo posible con objetos +> similares. + +Wikipedia dice + +> En programación informática, flyweight es un patrón de diseño de software. Un flyweight es un objeto que minimiza el +> uso de memoria compartiendo tantos datos como sea posible con otros objetos similares; es una forma de utilizar +> objetos +> en grandes cantidades cuando una simple representación repetida utilizaría una cantidad inaceptable de memoria. + +**Ejemplo programático** + +Traduciendo nuestro ejemplo de la tienda de alquimia de arriba. En primer lugar, tenemos diferentes tipos de +pociones `Potion`: `HealingPotion`, `HolyWaterPotion` e `InvisibilityPotion`: + +```java +public interface Potion { + void drink(); +} + +@Slf4j +public class HealingPotion implements Potion { + @Override + public void drink() { + LOGGER.info("You feel healed. (Potion={})", System.identityHashCode(this)); + } +} + +@Slf4j +public class HolyWaterPotion implements Potion { + @Override + public void drink() { + LOGGER.info("You feel blessed. (Potion={})", System.identityHashCode(this)); + } +} + +@Slf4j +public class InvisibilityPotion implements Potion { + @Override + public void drink() { + LOGGER.info("You become invisible. (Potion={})", System.identityHashCode(this)); + } +} +``` + +Luego la clase Flyweight `PotionFactory`, que es la fábrica para crear pociones. + +```java +public class PotionFactory { + + private final Map potions; + + public PotionFactory() { + potions = new EnumMap<>(PotionType.class); + } + + Potion createPotion(PotionType type) { + var potion = potions.get(type); + if (potion == null) { + switch (type) { + case HEALING -> { + potion = new HealingPotion(); + potions.put(type, potion); + } + case HOLY_WATER -> { + potion = new HolyWaterPotion(); + potions.put(type, potion); + } + case INVISIBILITY -> { + potion = new InvisibilityPotion(); + potions.put(type, potion); + } + default -> { + } + } + } + return potion; + } +} +``` + +`AlchemistShop` contiene dos estantes de pociones mágicas. Las pociones se crean utilizando la antes +mencionada `PotionFactory`. + +```java +@Slf4j +public class AlchemistShop { + + private final List topShelf; + private final List bottomShelf; + + public AlchemistShop() { + var factory = new PotionFactory(); + topShelf = List.of( + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.STRENGTH), + factory.createPotion(PotionType.HEALING), + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.STRENGTH), + factory.createPotion(PotionType.HEALING), + factory.createPotion(PotionType.HEALING) + ); + bottomShelf = List.of( + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.HOLY_WATER), + factory.createPotion(PotionType.HOLY_WATER) + ); + } + + public final List getTopShelf() { + return List.copyOf(this.topShelf); + } + + public final List getBottomShelf() { + return List.copyOf(this.bottomShelf); + } + + public void drinkPotions() { + LOGGER.info("Drinking top shelf potions\n"); + topShelf.forEach(Potion::drink); + LOGGER.info("Drinking bottom shelf potions\n"); + bottomShelf.forEach(Potion::drink); + } +} +``` + +En nuestro escenario, un valiente visitante entra en la tienda del alquimista y se bebe todas las pociones. + +```java +// create the alchemist shop with the potions +var alchemistShop = new AlchemistShop(); +// a brave visitor enters the alchemist shop and drinks all the potions +alchemistShop.drinkPotions(); +``` + +Salida del programa: + +```java +Drinking top shelf potions +You become invisible. (Potion=1509514333) +You become invisible. (Potion=1509514333) +You feel strong. (Potion=739498517) +You feel healed. (Potion=125130493) +You become invisible. (Potion=1509514333) +You feel strong. (Potion=739498517) +You feel healed. (Potion=125130493) +You feel healed. (Potion=125130493) +Drinking bottom shelf potions +Urgh! This is poisonous. (Potion=166239592) +Urgh! This is poisonous. (Potion=166239592) +Urgh! This is poisonous. (Potion=166239592) +You feel blessed. (Potion=991505714) +You feel blessed. (Potion=991505714) +``` + +## Diagrama de clases + +![alt text](./etc/flyweight.urm.png "Flyweight pattern class diagram") + +## Aplicabilidad + +La eficacia del patrón Flyweight depende en gran medida de cómo y dónde se utilice. Aplique el patrón +Flyweight cuando se cumplan todas las condiciones siguientes: + +* Una aplicación utiliza un gran número de objetos. +* Los costes de almacenamiento son altos debido a la gran cantidad de objetos. +* La mayor parte del estado de los objetos puede hacerse extrínseco. +* Muchos grupos de objetos pueden ser reemplazados por relativamente pocos objetos compartidos una vez que el estado extrínseco + extrínseco. +* La aplicación no depende de la identidad de los objetos. Dado que los objetos flyweight pueden ser compartidos, las pruebas de identidad + devolverán verdadero para objetos conceptualmente distintos. + +## Usos conocidos + +* [java.lang.Integer#valueOf(int)](http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#valueOf%28int%29) y + de forma similar para Byte, Carácter y otros tipos envueltos (Wrappers). + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/es/flyweight/etc/flyweight.urm.png b/localization/es/flyweight/etc/flyweight.urm.png new file mode 100644 index 000000000000..299cdb7bdf86 Binary files /dev/null and b/localization/es/flyweight/etc/flyweight.urm.png differ diff --git a/localization/es/front-controller/README.md b/localization/es/front-controller/README.md new file mode 100644 index 000000000000..58997f265cea --- /dev/null +++ b/localization/es/front-controller/README.md @@ -0,0 +1,34 @@ +--- +title: Front Controller +shortTitle: Front Controller +category: Structural +language: es +tag: + - Decoupling +--- + +## Propósito +Introducir un gestor común para todas las solicitudes de un sitio web. De esta +manera podemos encapsular funcionalidad común como la seguridad, +internacionalización, enrutamiento y registro en un solo lugar. + +## Diagrama de clases +![alt text](./etc/front-controller.png "Front Controller") + +## Aplicabilidad +Utilice el patrón del controlador frontal cuando + +* Desea encapsular la funcionalidad común de gestión de peticiones en un único lugar. +* Desea implementar la gestión dinámica de peticiones, es decir, cambiar el enrutamiento sin modificar el código. +* hacer portable la configuración del servidor web, sólo necesitas registrar el manejador de forma específica para el servidor web + +## Ejemplos del mundo real + +* [Apache Struts](https://struts.apache.org/) + +## Créditos + +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Presentation Tier Patterns](http://www.javagyan.com/tutorials/corej2eepatterns/presentation-tier-patterns) +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321127420&linkCode=as2&tag=javadesignpat-20&linkId=d9f7d37b032ca6e96253562d075fcc4a) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/es/front-controller/etc/front-controller.png b/localization/es/front-controller/etc/front-controller.png new file mode 100644 index 000000000000..77c14ef019cc Binary files /dev/null and b/localization/es/front-controller/etc/front-controller.png differ diff --git a/localization/es/game-loop/README.md b/localization/es/game-loop/README.md new file mode 100644 index 000000000000..3333c4bbad19 --- /dev/null +++ b/localization/es/game-loop/README.md @@ -0,0 +1,246 @@ +--- +title: Game Loop +shortTitle: Game Loop +category: Behavioral +language: es +tag: + - Game programming +--- + +## Propósito + +Un bucle de juego se ejecuta continuamente durante la partida. En cada vuelta del bucle, procesa las entradas del usuario sin bloquearse, actualiza el estado del juego y lo renderiza. Realiza un seguimiento del paso del tiempo para controlar el ritmo de juego. + +Este patrón desvincula la progresión del tiempo de juego de la entrada del usuario y de la velocidad del procesador. + +## Aplicabilidad + +Este patrón se utiliza en todos los motores de juego. + +## Explicación + +Ejemplo del mundo real + +> El bucle de juego es el proceso principal de todos los hilos de renderizado del juego. Está presente en todos los juegos modernos. Controla el proceso de entrada, la actualización del estado interno, el renderizado, la IA y todos los demás procesos. + +En pocas palabras + +> El patrón de bucle de juego garantiza que el tiempo de juego progrese a la misma velocidad en todas las configuraciones de hardware diferentes. + +Wikipedia dice + +> El componente central de cualquier juego, desde el punto de vista de la programación, es el bucle de juego. El bucle de juego permite que el juego se ejecute sin problemas, independientemente de la entrada de un usuario, o la falta de ella. + +**Ejemplo programático** + +Empecemos con algo sencillo. Aquí está la clase `Bullet`. Las balas se moverán en nuestro juego. Para propósitos de demostración es suficiente que tenga una posición unidimensional. + +```java +public class Bullet { + + private float position; + + public Bullet() { + position = 0.0f; + } + + public float getPosition() { + return position; + } + + public void setPosition(float position) { + this.position = position; + } +} +``` + +El `GameController` es el responsable de mover los objetos del juego, incluida la mencionada bala. + +```java +public class GameController { + + protected final Bullet bullet; + + public GameController() { + bullet = new Bullet(); + } + + public void moveBullet(float offset) { + var currentPosition = bullet.getPosition(); + bullet.setPosition(currentPosition + offset); + } + + public float getBulletPosition() { + return bullet.getPosition(); + } +} +``` + +Ahora introducimos el bucle de juego. O en realidad en esta demo tenemos 3 bucles de juego diferentes. Veamos primero la clase base `GameLoop`. + +```java +public enum GameStatus { + + RUNNING, STOPPED +} + +public abstract class GameLoop { + + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + + protected volatile GameStatus status; + + protected GameController controller; + + private Thread gameThread; + + public GameLoop() { + controller = new GameController(); + status = GameStatus.STOPPED; + } + + public void run() { + status = GameStatus.RUNNING; + gameThread = new Thread(this::processGameLoop); + gameThread.start(); + } + + public void stop() { + status = GameStatus.STOPPED; + } + + public boolean isGameRunning() { + return status == GameStatus.RUNNING; + } + + protected void processInput() { + try { + var lag = new Random().nextInt(200) + 50; + Thread.sleep(lag); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + + protected void render() { + var position = controller.getBulletPosition(); + logger.info("Current bullet position: " + position); + } + + protected abstract void processGameLoop(); +} +``` + +Aquí está la primera implementación del bucle de juego, `FrameBasedGameLoop`: + +```java +public class FrameBasedGameLoop extends GameLoop { + + @Override + protected void processGameLoop() { + while (isGameRunning()) { + processInput(); + update(); + render(); + } + } + + protected void update() { + controller.moveBullet(0.5f); + } +} +``` + +Por último, mostramos todos los bucles del juego en acción. + +```java + try { + LOGGER.info("Start frame-based game loop:"); + var frameBasedGameLoop = new FrameBasedGameLoop(); + frameBasedGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + frameBasedGameLoop.stop(); + LOGGER.info("Stop frame-based game loop."); + + LOGGER.info("Start variable-step game loop:"); + var variableStepGameLoop = new VariableStepGameLoop(); + variableStepGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + variableStepGameLoop.stop(); + LOGGER.info("Stop variable-step game loop."); + + LOGGER.info("Start fixed-step game loop:"); + var fixedStepGameLoop = new FixedStepGameLoop(); + fixedStepGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + fixedStepGameLoop.stop(); + LOGGER.info("Stop variable-step game loop."); + + } catch (InterruptedException e) { + LOGGER.error(e.getMessage()); + } +``` + +Salida del programa: + +```java +Start frame-based game loop: +Current bullet position: 0.5 +Current bullet position: 1.0 +Current bullet position: 1.5 +Current bullet position: 2.0 +Current bullet position: 2.5 +Current bullet position: 3.0 +Current bullet position: 3.5 +Current bullet position: 4.0 +Current bullet position: 4.5 +Current bullet position: 5.0 +Current bullet position: 5.5 +Current bullet position: 6.0 +Stop frame-based game loop. +Start variable-step game loop: +Current bullet position: 6.5 +Current bullet position: 0.038 +Current bullet position: 0.084 +Current bullet position: 0.145 +Current bullet position: 0.1805 +Current bullet position: 0.28 +Current bullet position: 0.32 +Current bullet position: 0.42549998 +Current bullet position: 0.52849996 +Current bullet position: 0.57799995 +Current bullet position: 0.63199997 +Current bullet position: 0.672 +Current bullet position: 0.778 +Current bullet position: 0.848 +Current bullet position: 0.8955 +Current bullet position: 0.9635 +Stop variable-step game loop. +Start fixed-step game loop: +Current bullet position: 0.0 +Current bullet position: 1.086 +Current bullet position: 0.059999995 +Current bullet position: 0.12999998 +Current bullet position: 0.24000004 +Current bullet position: 0.33999994 +Current bullet position: 0.36999992 +Current bullet position: 0.43999985 +Current bullet position: 0.5399998 +Current bullet position: 0.65999967 +Current bullet position: 0.68999964 +Current bullet position: 0.7299996 +Current bullet position: 0.79999954 +Current bullet position: 0.89999944 +Current bullet position: 0.98999935 +Stop variable-step game loop. +``` + +## Diagrama de clases + +![alt text](./etc/game-loop.urm.png "Game Loop pattern class diagram") + +## Créditos + +* [Game Programming Patterns - Game Loop](http://gameprogrammingpatterns.com/game-loop.html) +* [Game Programming Patterns](https://www.amazon.com/gp/product/0990582906/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0990582906&linkId=1289749a703b3fe0e24cd8d604d7c40b) +* [Game Engine Architecture, Third Edition](https://www.amazon.com/gp/product/1138035459/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1138035459&linkId=94502746617211bc40e0ef49d29333ac) diff --git a/localization/es/game-loop/etc/game-loop.urm.png b/localization/es/game-loop/etc/game-loop.urm.png new file mode 100644 index 000000000000..b7ffc11d2659 Binary files /dev/null and b/localization/es/game-loop/etc/game-loop.urm.png differ diff --git a/localization/es/gateway/README.md b/localization/es/gateway/README.md new file mode 100644 index 000000000000..2bef6e4f785c --- /dev/null +++ b/localization/es/gateway/README.md @@ -0,0 +1,147 @@ +--- +title: Gateway +shortTitle: Gateway +category: Structural +language: es +tag: +- Decoupling + +--- + +## Propósito + +Proporcionar una interfaz de acceso a un conjunto de sistemas o funcionalidades externas. Gateway proporciona una vista simple y uniforme de +recursos externos a los internos de una aplicación. + +## Explicación + +Un ejemplo real + +> Gateway actúa como una verdadera puerta de entrada de una ciudad determinada. Las personas dentro de la ciudad se llaman sistema interno, y las diferentes ciudades externas se llaman servicios externos. La puerta de enlace está aquí para proporcionar acceso al sistema interno a diferentes servicios externos. + +En pocas palabras + +> La pasarela puede proporcionar una interfaz que permita al sistema interno utilizar un servicio externo. + +Wikipedia dice + +> Un servidor que actúa como front-end de la API, recibe solicitudes de la API, aplica políticas de estrangulamiento y seguridad, pasa las solicitudes al servicio back-end y, a continuación, devuelve la respuesta al solicitante. + +**Ejemplo programático** + +La clase principal de nuestro ejemplo es el `ExternalService` que contiene elementos. + +```java +class ExternalServiceA implements Gateway { + @Override + public void execute() throws Exception { + LOGGER.info("Executing Service A"); + // Simulate a time-consuming task + Thread.sleep(1000); + } +} + +/** + * ExternalServiceB is one of external services. + */ +class ExternalServiceB implements Gateway { + @Override + public void execute() throws Exception { + LOGGER.info("Executing Service B"); + // Simulate a time-consuming task + Thread.sleep(1000); + } +} + +/** + * ExternalServiceC is one of external services. + */ +class ExternalServiceC implements Gateway { + @Override + public void execute() throws Exception { + LOGGER.info("Executing Service C"); + // Simulate a time-consuming task + Thread.sleep(1000); + } + + public void error() throws Exception { + // Simulate an exception + throw new RuntimeException("Service C encountered an error"); + } +} +``` + +Para operar estos servicios externos, aquí está la clase `App`: + +```java +public class App { + /** + * Simulate an application calling external services. + */ + public static void main(String[] args) throws Exception { + GatewayFactory gatewayFactory = new GatewayFactory(); + + // Register different gateways + gatewayFactory.registerGateway("ServiceA", new ExternalServiceA()); + gatewayFactory.registerGateway("ServiceB", new ExternalServiceB()); + gatewayFactory.registerGateway("ServiceC", new ExternalServiceC()); + + // Use an executor service for asynchronous execution + Gateway serviceA = gatewayFactory.getGateway("ServiceA"); + Gateway serviceB = gatewayFactory.getGateway("ServiceB"); + Gateway serviceC = gatewayFactory.getGateway("ServiceC"); + + // Execute external services + try { + serviceA.execute(); + serviceB.execute(); + serviceC.execute(); + } catch (ThreadDeath e) { + LOGGER.info("Interrupted!" + e); + throw e; + } + } +} +``` + +La interfaz `Gateway` es extremadamente sencilla. + +```java +interface Gateway { + void execute() throws Exception; +} +``` + +Salida del programa: + +```java + Executing Service A + Executing Service B + Executing Service C +``` + +## Diagrama de clases + +![alt text](./etc/gateway.urm.png "gateway") + +## Aplicabilidad + +Utilizar el patrón Gateway + +* Para acceder al contenido de un objeto agregado sin exponer su representación interna. +* Para la integración con múltiples servicios externos o APIs. +* Para proporcionar una interfaz uniforme para recorrer diferentes estructuras de agregados. + +## Tutoriales + +* [Pattern: API Gateway / Backends for Frontends](https://microservices.io/patterns/apigateway.html) + +## Usos conocidos + +* [API Gateway](https://java-design-patterns.com/patterns/microservices-api-gateway/) +* [10 most common use cases of an API Gateway](https://apisix.apache.org/blog/2022/10/27/ten-use-cases-api-gateway/) + +## Créditos + +* [Gateway](https://martinfowler.com/articles/gateway-pattern.html) +* [What is the difference between Facade and Gateway design patterns?](https://stackoverflow.com/questions/4422211/what-is-the-difference-between-facade-and-gateway-design-patterns) diff --git a/localization/es/gateway/etc/gateway.urm.png b/localization/es/gateway/etc/gateway.urm.png new file mode 100644 index 000000000000..2d8ad6c9a8f8 Binary files /dev/null and b/localization/es/gateway/etc/gateway.urm.png differ diff --git a/localization/es/health-check/README.md b/localization/es/health-check/README.md new file mode 100644 index 000000000000..a13f67542e3e --- /dev/null +++ b/localization/es/health-check/README.md @@ -0,0 +1,452 @@ +--- +title: Health Check Pattern +shortTitle: Health Check Pattern +category: Behavioral +language: es +tag: + - Performance + - Microservices + - Resilience + - Observability +--- + +# Health Check Pattern + +## También conocido como +Health Monitoring, Service Health Check + +## Propósito +Garantizar la estabilidad y resistencia de los servicios en una arquitectura de microservicios proporcionando una forma de supervisar y diagnosticar su estado. + +## Explicación +En la arquitectura de microservicios, es crítico comprobar continuamente la salud de los servicios individuales. El Health Check Pattern es un mecanismo para que los microservicios expongan su estado de salud. Este patrón se implementa incluyendo un punto final de comprobación de salud en los microservicios que devuelve el estado actual del servicio. Esto es vital para mantener la resistencia del sistema y la disponibilidad operativa. + +Para obtener más información, consulte el patrón API Health Check en [Microservices.io](https://microservices.io/patterns/observability/health-check-api.html). + + +## Ejemplo del mundo real +En un entorno nativo en la nube, como Kubernetes o AWS ECS, las comprobaciones de estado se utilizan para garantizar que los contenedores se ejecutan correctamente. Si un servicio falla su chequeo de salud, puede ser reiniciado o reemplazado automáticamente, asegurando alta disponibilidad y resiliencia. + +## En pocas palabras +El patrón de comprobación de la salud es como una visita periódica al médico para los servicios en una arquitectura de microservicios. Ayuda en la detección temprana de problemas y asegura que los servicios estén sanos y disponibles. + + +## Ejemplo Programático +Aquí, se proporcionan ejemplos detallados de implementaciones de chequeo de salud en un entorno de microservicios. + +### AsynchronousHealthChecker +Un componente de comprobación de salud asíncrono que ejecuta comprobaciones de salud en un hilo separado. + +```java + /** + * Performs a health check asynchronously using the provided health check logic with a specified + * timeout. + * + * @param healthCheck the health check logic supplied as a {@code Supplier} + * @param timeoutInSeconds the maximum time to wait for the health check to complete, in seconds + * @return a {@code CompletableFuture} object that represents the result of the health + * check + */ + public CompletableFuture performCheck( + Supplier healthCheck, long timeoutInSeconds) { + CompletableFuture future = + CompletableFuture.supplyAsync(healthCheck, healthCheckExecutor); + + // Schedule a task to enforce the timeout + healthCheckExecutor.schedule( + () -> { + if (!future.isDone()) { + LOGGER.error(HEALTH_CHECK_TIMEOUT_MESSAGE); + future.completeExceptionally(new TimeoutException(HEALTH_CHECK_TIMEOUT_MESSAGE)); + } + }, + timeoutInSeconds, + TimeUnit.SECONDS); + + return future.handle( + (result, throwable) -> { + if (throwable != null) { + LOGGER.error(HEALTH_CHECK_FAILED_MESSAGE, throwable); + // Check if the throwable is a TimeoutException or caused by a TimeoutException + Throwable rootCause = + throwable instanceof CompletionException ? throwable.getCause() : throwable; + if (!(rootCause instanceof TimeoutException)) { + LOGGER.error(HEALTH_CHECK_FAILED_MESSAGE, rootCause); + return Health.down().withException(rootCause).build(); + } else { + LOGGER.error(HEALTH_CHECK_TIMEOUT_MESSAGE, rootCause); + // If it is a TimeoutException, rethrow it wrapped in a CompletionException + throw new CompletionException(rootCause); + } + } else { + return result; + } + }); + } +``` + +### CpuHealthIndicator +Un indicador de salud que comprueba la salud de la CPU del sistema. + +```java + /** + * Checks the health of the system's CPU and returns a health indicator object. + * + * @return a health indicator object + */ + @Override + public Health health() { + if (!(osBean instanceof com.sun.management.OperatingSystemMXBean sunOsBean)) { + LOGGER.error("Unsupported operating system MXBean: {}", osBean.getClass().getName()); + return Health.unknown() + .withDetail(ERROR_MESSAGE, "Unsupported operating system MXBean") + .build(); + } + + double systemCpuLoad = sunOsBean.getCpuLoad() * 100; + double processCpuLoad = sunOsBean.getProcessCpuLoad() * 100; + int availableProcessors = sunOsBean.getAvailableProcessors(); + double loadAverage = sunOsBean.getSystemLoadAverage(); + + Map details = new HashMap<>(); + details.put("timestamp", Instant.now()); + details.put("systemCpuLoad", String.format("%.2f%%", systemCpuLoad)); + details.put("processCpuLoad", String.format("%.2f%%", processCpuLoad)); + details.put("availableProcessors", availableProcessors); + details.put("loadAverage", loadAverage); + + if (systemCpuLoad > systemCpuLoadThreshold) { + LOGGER.error(HIGH_SYSTEM_CPU_LOAD_MESSAGE, systemCpuLoad); + return Health.down() + .withDetails(details) + .withDetail(ERROR_MESSAGE, HIGH_SYSTEM_CPU_LOAD_MESSAGE_WITHOUT_PARAM) + .build(); + } else if (processCpuLoad > processCpuLoadThreshold) { + LOGGER.error(HIGH_PROCESS_CPU_LOAD_MESSAGE, processCpuLoad); + return Health.down() + .withDetails(details) + .withDetail(ERROR_MESSAGE, HIGH_PROCESS_CPU_LOAD_MESSAGE_WITHOUT_PARAM) + .build(); + } else if (loadAverage > (availableProcessors * loadAverageThreshold)) { + LOGGER.error(HIGH_LOAD_AVERAGE_MESSAGE, loadAverage); + return Health.up() + .withDetails(details) + .withDetail(ERROR_MESSAGE, HIGH_LOAD_AVERAGE_MESSAGE_WITHOUT_PARAM) + .build(); + } else { + return Health.up().withDetails(details).build(); + } + } + +``` + + + +### CustomHealthIndicator +Un indicador de estado personalizado que comprueba periódicamente el estado de una base de datos y almacena en caché el resultado. Aprovecha un comprobador de estado asíncrono para realizar las comprobaciones de estado. + +- `AsynchronousHealthChecker`: Un componente para realizar comprobaciones de estado de forma asíncrona. +- `CacheManager`: Gestiona el almacenamiento en caché de los resultados de los controles de salud. +- `HealthCheckRepository`: Un repositorio para consultar datos relacionados con la salud desde la base de datos. + +```java +/** + * Perform a health check and cache the result. + * + * @return the health status of the application + * @throws HealthCheckInterruptedException if the health check is interrupted + */ +@Override +@Cacheable(value = "health-check", unless = "#result.status == 'DOWN'") +public Health health() { + LOGGER.info("Performing health check"); + CompletableFuture healthFuture = + healthChecker.performCheck(this::check, timeoutInSeconds); + try { + return healthFuture.get(timeoutInSeconds, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.error("Health check interrupted", e); + throw new HealthCheckInterruptedException(e); + } catch (Exception e) { + LOGGER.error("Health check failed", e); + return Health.down(e).build(); + } +} + +/** + * Checks the health of the database by querying for a simple constant value expected from the + * database. + * + * @return Health indicating UP if the database returns the constant correctly, otherwise DOWN. + */ +private Health check() { + Integer result = healthCheckRepository.checkHealth(); + boolean databaseIsUp = result != null && result == 1; + LOGGER.info("Health check result: {}", databaseIsUp); + return databaseIsUp + ? Health.up().withDetail("database", "reachable").build() + : Health.down().withDetail("database", "unreachable").build(); +} + +/** + * Evicts all entries from the health check cache. This is scheduled to run at a fixed rate + * defined in the application properties. + */ +@Scheduled(fixedRateString = "${health.check.cache.evict.interval:60000}") +public void evictHealthCache() { + LOGGER.info("Evicting health check cache"); + try { + Cache healthCheckCache = cacheManager.getCache("health-check"); + LOGGER.info("Health check cache: {}", healthCheckCache); + if (healthCheckCache != null) { + healthCheckCache.clear(); + } + } catch (Exception e) { + LOGGER.error("Failed to evict health check cache", e); + } +} + +``` + +### DatabaseTransactionHealthIndicator +Un indicador de salud que comprueba la salud de las transacciones de la base de datos intentando realizar una transacción de prueba utilizando un mecanismo de reintento. + +- Repositorio de comprobaciones de estado**: Un repositorio para realizar comprobaciones de salud en la base de datos. +- AsynchronousHealthChecker**: Un comprobador de salud asíncrono utilizado para ejecutar comprobaciones de salud en un hilo independiente. +- Plantilla de reintento**: Una plantilla de reintento utilizada para reintentar la transacción de prueba si falla debido a un error transitorio. + +```java +/** + * Performs a health check by attempting to perform a test transaction with retry support. + * + * @return the health status of the database transactions + */ +@Override +public Health health() { + LOGGER.info("Calling performCheck with timeout {}", timeoutInSeconds); + Supplier dbTransactionCheck = + () -> { + try { + healthCheckRepository.performTestTransaction(); + return Health.up().build(); + } catch (Exception e) { + LOGGER.error("Database transaction health check failed", e); + return Health.down(e).build(); + } + }; + try { + return asynchronousHealthChecker.performCheck(dbTransactionCheck, timeoutInSeconds).get(); + } catch (InterruptedException | ExecutionException e) { + LOGGER.error("Database transaction health check timed out or was interrupted", e); + Thread.currentThread().interrupt(); + return Health.down(e).build(); + } +} +``` + + +### GarbageCollectionHealthIndicator +Un indicador de salud personalizado que comprueba el estado de recogida de basura de la aplicación e informa del estado de salud en consecuencia. + +```java + /** + * Performs a health check by gathering garbage collection metrics and evaluating the overall + * health of the garbage collection system. + * + * @return a {@link Health} object representing the health status of the garbage collection system + */ + @Override + public Health health() { + List gcBeans = getGarbageCollectorMxBeans(); + List memoryPoolMxBeans = getMemoryPoolMxBeans(); + Map> gcDetails = new HashMap<>(); + + for (GarbageCollectorMXBean gcBean : gcBeans) { + Map collectorDetails = createCollectorDetails(gcBean, memoryPoolMxBeans); + gcDetails.put(gcBean.getName(), collectorDetails); + } + return Health.up().withDetails(gcDetails).build(); + } + +``` + +### MemoryHealthIndicator +Un indicador de salud personalizado que comprueba el uso de memoria de la aplicación e informa del estado de salud en consecuencia. + +```java + /** + * Performs a health check by checking the memory usage of the application. + * + * @return the health status of the application + */ + public Health checkMemory() { + Supplier memoryCheck = + () -> { + MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean(); + MemoryUsage heapMemoryUsage = memoryMxBean.getHeapMemoryUsage(); + long maxMemory = heapMemoryUsage.getMax(); + long usedMemory = heapMemoryUsage.getUsed(); + + double memoryUsage = (double) usedMemory / maxMemory; + String format = String.format("%.2f%% of %d max", memoryUsage * 100, maxMemory); + + if (memoryUsage < memoryThreshold) { + LOGGER.info("Memory usage is below threshold: {}", format); + return Health.up().withDetail("memory usage", format).build(); + } else { + return Health.down().withDetail("memory usage", format).build(); + } + }; + + try { + CompletableFuture future = + asynchronousHealthChecker.performCheck(memoryCheck, timeoutInSeconds); + return future.get(); + } catch (InterruptedException e) { + LOGGER.error("Health check interrupted", e); + Thread.currentThread().interrupt(); + return Health.down().withDetail("error", "Health check interrupted").build(); + } catch (ExecutionException e) { + LOGGER.error("Health check failed", e); + Throwable cause = e.getCause() == null ? e : e.getCause(); + return Health.down().withDetail("error", cause.toString()).build(); + } + } + + /** + * Retrieves the health status of the application by checking the memory usage. + * + * @return the health status of the application + */ + @Override + public Health health() { + return checkMemory(); + } +} +``` + + + +## Usando Spring Boot Actuator para Comprobaciones de Salud +Spring Boot Actuator proporciona una funcionalidad de comprobación de salud incorporada que puede integrarse fácilmente en su aplicación. Añadiendo la dependencia Spring Boot Actuator, puede exponer la información de comprobación de estado a través de un punto final predefinido, normalmente `/actuator/health`. + +## Salida +Esto muestra la salida del patrón de comprobación de salud utilizando una petición GET al punto final de salud de Actuator. + +### HTTP GET Request +``` +curl -X GET "http://localhost:6161/actuator/health" +``` + +### Output +```json +{ + "status": "UP", + "components": { + "cpu": { + "status": "UP", + "details": { + "processCpuLoad": "0.03%", + "availableProcessors": 10, + "systemCpuLoad": "21.40%", + "loadAverage": 3.3916015625, + "timestamp": "2023-12-03T08:44:19.488422Z" + } + }, + "custom": { + "status": "UP", + "details": { + "database": "reachable" + } + }, + "databaseTransaction": { + "status": "UP" + }, + "db": { + "status": "UP", + "details": { + "database": "H2", + "validationQuery": "isValid()" + } + }, + "diskSpace": { + "status": "UP", + "details": { + "total": 994662584320, + "free": 377635827712, + "threshold": 10485760, + "exists": true + } + }, + "garbageCollection": { + "status": "UP", + "details": { + "G1 Young Generation": { + "count": "11", + "time": "30ms", + "memoryPools": "G1 Old Gen: 0.005056262016296387%" + }, + "G1 Old Generation": { + "count": "0", + "time": "0ms", + "memoryPools": "G1 Old Gen: 0.005056262016296387%" + } + } + }, + "livenessState": { + "status": "UP" + }, + "memory": { + "status": "UP", + "details": { + "memory usage": "1.36% of 4294967296 max" + } + }, + "ping": { + "status": "UP" + }, + "readinessState": { + "status": "UP" + } + }, + "groups": [ + "liveness", + "readiness" + ] +} +``` + +## Diagrama de clases +![Health Check Pattern](./etc/health-check.png) + +## Aplicabilidad +Utilice el Patrón de Comprobación de Salud cuando: +- Tienes una aplicación compuesta por múltiples servicios y necesitas monitorizar la salud de cada servicio individualmente. +- Desea implementar la recuperación o sustitución automática de servicios basándose en el estado de salud. +- Está empleando herramientas de orquestación o automatización que se basan en comprobaciones de estado para gestionar instancias de servicio. + +## Tutoriales +- Implementación de Health Checks en Java usando Spring Boot Actuator. + +## Usos conocidos +- Kubernetes Liveness y Readiness Probes +- Comprobaciones de estado de AWS Elastic Load Balancing +- Actuador Spring Boot + +## Consecuencias +**Pros:** +- Mejora la tolerancia a fallos del sistema detectando fallos y permitiendo una rápida recuperación. +- Mejora la visibilidad del estado del sistema para la supervisión operativa y las alertas. + +**Contras:** +- Añade complejidad a la implementación del servicio. +- Requiere una estrategia para gestionar los fallos en cascada cuando los servicios dependientes no están en buen estado. + +## Patrones relacionados +- Circuit Breaker +- Retry Pattern +- Timeout Pattern + +## Créditos +Inspirado en el patrón Health Check API de [microservices.io](https://microservices.io/patterns/observability/health-check-api.html), y el tema [#2695](https://github.com/iluwatar/java-design-patterns/issues/2695) en el repositorio de patrones de diseño Java de iluwatar. \ No newline at end of file diff --git a/localization/es/health-check/etc/health-check.png b/localization/es/health-check/etc/health-check.png new file mode 100644 index 000000000000..89966c464cb5 Binary files /dev/null and b/localization/es/health-check/etc/health-check.png differ diff --git a/localization/es/identity-map/README.md b/localization/es/identity-map/README.md new file mode 100644 index 000000000000..8ff37811ea34 --- /dev/null +++ b/localization/es/identity-map/README.md @@ -0,0 +1,192 @@ +--- +title: Identity Map +shortTitle: Identity Map +category: Behavioral +language: es +tag: +- Performance +- Data access +--- + +## Propósito + +Garantiza que cada objeto se cargue una sola vez guardando cada objeto cargado en un mapa. +Busca objetos utilizando el mapa cuando se refiere a ellos. + +## Explicación + +Ejemplo del mundo real + +> Estamos escribiendo un programa que el usuario puede utilizar para encontrar los registros de una persona determinada en una base de datos. + +En palabras simples + +> Construir un mapa de identidades que almacene los registros de los elementos buscados recientemente en la base de datos. Cuando busquemos el mismo registro la próxima vez lo cargaremos desde el mapa no iremos a la base de datos. + +Wikipedia dice + +> En el diseño de DBMS, el patrón de mapa de identidad es un patrón de diseño de acceso a base de datos utilizado para mejorar el rendimiento, proporcionando un contexto específico, en la memoria caché para evitar la recuperación duplicada de los mismos datos de objetos de la base de datos + +**Ejemplo programático** + +* Para el propósito de esta demostración supongamos que ya hemos creado una instancia de base de datos **db**. +* Veamos primero la implementación de una entidad persona y sus campos: + +```java +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@Getter +@Setter +@AllArgsConstructor +public final class Person implements Serializable { + + private static final long serialVersionUID = 1L; + + @EqualsAndHashCode.Include + private int personNationalId; + private String name; + private long phoneNum; + + @Override + public String toString() { + + return "Person ID is : " + personNationalId + " ; Person Name is : " + name + " ; Phone Number is :" + phoneNum; + + } + +} + +``` + +* La siguiente es la implementación del personFinder que es la entidad que el usuario utilizará para buscar un registro en nuestra base de datos. Tiene adjunta la BD correspondiente. También mantiene un IdentityMap para almacenar los registros leídos recientemente. + +```java +@Slf4j +@Getter +@Setter +public class PersonFinder { + private static final long serialVersionUID = 1L; + // Access to the Identity Map + private IdentityMap identityMap = new IdentityMap(); + private PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + /** + * get person corresponding to input ID. + * + * @param key : personNationalId to look for. + */ + public Person getPerson(int key) { + // Try to find person in the identity map + Person person = this.identityMap.getPerson(key); + if (person != null) { + LOGGER.info("Person found in the Map"); + return person; + } else { + // Try to find person in the database + person = this.db.find(key); + if (person != null) { + this.identityMap.addPerson(person); + LOGGER.info("Person found in DB."); + return person; + } + LOGGER.info("Person with this ID does not exist."); + return null; + } + } +} + +``` + +* El campo de mapa de identidad en la clase anterior es simplemente una abstracción de un hashMap con **personNationalId** como claves y el objeto persona correspondiente como valor. Aquí está su implementación: + +```java +@Slf4j +@Getter +public class IdentityMap { + private Map personMap = new HashMap<>(); + /** + * Add person to the map. + */ + public void addPerson(Person person) { + if (!personMap.containsKey(person.getPersonNationalId())) { + personMap.put(person.getPersonNationalId(), person); + } else { // Ensure that addPerson does not update a record. This situation will never arise in our implementation. Added only for testing purposes. + LOGGER.info("Key already in Map"); + } + } + + /** + * Get Person with given id. + * + * @param id : personNationalId as requested by user. + */ + public Person getPerson(int id) { + Person person = personMap.get(id); + if (person == null) { + LOGGER.info("ID not in Map."); + } + return person; + } + + /** + * Get the size of the map. + */ + public int size() { + if (personMap == null) { + return 0; + } + return personMap.size(); + } + +} + +``` + +* Ahora debemos construir una persona ficticia para fines de demostración y poner a esa persona en nuestra base de datos. + +```java + Person person1 = new Person(1, "John", 27304159); + db.insert(person1); +``` + +* Ahora vamos a crear un objeto person finder y buscar a la persona con personNationalId = 1(supongamos que el objeto personFinder ya tiene la db y un IdentityMap adjunto): + +```java + PersonFinder finder = new PersonFinder(); + finder.getPerson(1); +``` + +* En esta etapa este registro se cargará desde la base de datos y la salida sería: + +```java + ID not in Map. + Person ID is:1;Person Name is:John;Phone Number is:27304159 + Person found in DB. +``` + +* Sin embargo, la próxima vez que busquemos de nuevo este registro lo encontraremos en el mapa, por lo que no necesitaremos ir a la base de datos. + +```java + Person ID is:1;Person Name is:John;Phone Number is:27304159 + Person found in Map. +``` + +* Si el registro correspondiente no está en la base de datos, se lanza una excepción. Esta es su implementación. + +```java +public class IdNotFoundException extends RuntimeException { + public IdNotFoundException(final String message) { + super(message); + } +} +``` +## Diagrama de clases + +![alt text](./etc/IdentityMap.png "Identity Map Pattern") + +## Aplicabilidad + +* La idea detrás del patrón Identity Map es que cada vez que leemos un registro de la base de datos, primero comprobamos el Identity Map para ver si el registro ya ha sido recuperado. Esto nos permite simplemente devolver una nueva referencia al registro en memoria en lugar de crear un nuevo objeto, manteniendo la integridad referencial. +* Una ventaja secundaria del Mapa de Identidad es que, al actuar como caché, reduce el número de llamadas a la base de datos necesarias para recuperar objetos, lo que supone una mejora del rendimiento. + +## Créditos + +* [Identity Map](https://www.sourcecodeexamples.net/2018/04/identity-map-pattern.html) diff --git a/localization/es/identity-map/etc/IdentityMap.png b/localization/es/identity-map/etc/IdentityMap.png new file mode 100644 index 000000000000..1bac10ebf294 Binary files /dev/null and b/localization/es/identity-map/etc/IdentityMap.png differ diff --git a/localization/es/intercepting-filter/README.md b/localization/es/intercepting-filter/README.md new file mode 100644 index 000000000000..3322a79156b9 --- /dev/null +++ b/localization/es/intercepting-filter/README.md @@ -0,0 +1,166 @@ +--- +title: Intercepting Filter +shortTitle: Intercepting Filter +category: Behavioral +language: es +tag: + - Decoupling +--- + +## Propósito +Un filtro de intercepción es un útil patrón de diseño Java que se utiliza cuando se desea preprocesar o postprocesar una petición en una aplicación. Estos filtros se crean y se aplican a la solicitud antes de que se le da a la aplicación de destino. Algunos ejemplos de uso incluyen la autenticación, que es necesario procesar antes de que la solicitud se entregue a la aplicación. + +## Explicación +Ejemplo del mundo real +> Un ejemplo de uso del patrón de diseño Filtro Interceptor es relevante a la hora de realizar una plataforma de comercio electrónico. Es importante implementar varios filtros para la autenticación de la cuenta, la autenticación del pago, el registro y el almacenamiento en caché. Los tipos de filtros importantes en este ejemplo son los filtros de autenticación, registro, seguridad y almacenamiento en caché. + +En palabras sencillas +> Un filtro de intercepción en Java es como una serie de puntos de control de seguridad para peticiones y respuestas en una aplicación de software. Comprueba y procesa los datos a medida que entran y salen, ayudando con tareas como la autenticación, el registro y la seguridad, mientras mantiene el núcleo de la aplicación seguro y limpio. + +Wikipedia dice +> El filtro de intercepción es un patrón de Java que crea filtros conectables para procesar servicios comunes de una manera estándar sin necesidad de realizar cambios en el código de procesamiento de solicitudes. + +## Ejemplo Programático +Como ejemplo, podemos crear una clase Filtro básica y definir un Filtro de Autenticación. Al filtro le falta lógica, pero + +```java +// 1. Define a Filter interface +interface Filter { + void runFilter(String request); +} +// 2. Create a Authentication filter +class AuthenticationFilter implements Filter { + public void runFilter(String request) { + // Authentication logic would be passed in here + if (request.contains("authenticated=true")) { + System.out.println("Authentication successful for request: " + request); + } else { + System.out.println("Authentication failed for request: " + request); + } + } +} +// 3. Create a Client to send requests and activate the filter +class Client { + // create an instance of the filter in the Client class + private Filter filter; + + // create constructor + public Client(Filter filter) { + this.filter = filter; + } + + // send the String request to the filter, the request does not have to be a string + // it can be anything + public void sendRequest(String request) { + filter.runFilter(request); + } +} +// 4. Demonstrate the Authentication Filter +public class AuthenticationFilterExample { + public static void main(String[] args) { + Filter authenticationFilter = new AuthenticationFilter(); + Client client = new Client(authenticationFilter); + + // Simulate requests for false + client.sendRequest("GET /public-page"); + // this request would come back as true as the link includes an argument + // for successful authentication + client.sendRequest("GET /private-page?authenticated=true"); + } +} +``` +Este es un ejemplo básico de cómo implementar el esqueleto de un filtro. Falta la lógica de autenticación en AuthenticationFilterExample, pero se puede rellenar en los huecos. + +Además, el cliente puede ser configurado para ejecutar múltiples filtros en su solicitud utilizando un bucle For poblado con filtros como se puede ver a continuación: + +```java +// 1. Define a Filter interface +interface Filter { + void runFilter(String request); +} + +// 2. Create an Authentication filter +class AuthenticationFilter implements Filter { + public void runFilter(String request) { + // Authentication logic would be placed here + if (request.contains("authenticated=true")) { + System.out.println("Authentication successful for request: " + request); + } else { + System.out.println("Authentication failed for request: " + request); + } + } +} + +// 3. Create a Client to send requests and activate multiple filters +class Client { + // create a list of filters in the Client class + private List filters = new ArrayList<>(); + + // add filters to the list + public void addFilter(Filter filter) { + filters.add(filter); + } + + // send the request through all the filters + public void sendRequest(String request) { + for (Filter filter : filters) { + filter.runFilter(request); + } + } +} + +// 4. Demonstrate multiple filters +public class MultipleFiltersExample { + public static void main(String[] args) { + // Create a client + Client client = new Client(); + + // Add filters to the client + Filter authenticationFilter = new AuthenticationFilter(); + client.addFilter(authenticationFilter); + + // Add more filters as needed + // Filter anotherFilter = new AnotherFilter(); + // client.addFilter(anotherFilter); + + // Simulate requests + client.sendRequest("GET /public-page"); + client.sendRequest("GET /private-page?authenticated=true"); + } +} +``` +Este método permite manipular y comprobar los datos de forma rápida y sencilla antes de autenticar un inicio de sesión o finalizar otro tipo de acción. + +## Diagrama de clases +![alt text](./etc/intercepting-filter.png "Intercepting Filter") + +## Aplicabilidad +Utilice el patrón Filtro interceptor cuando + +* Un programa necesita preprocesar o postprocesar datos +* Un sistema necesita servicios de autorización/autenticación para acceder a datos sensibles +* Desea registrar/auditar peticiones o respuestas con fines de depuración o almacenamiento, como marcas de tiempo y acciones del usuario +* Desea transformar datos de un tipo a otro antes de entregarlos al proceso final. +* Desea implementar un manejo específico de excepciones + +## Consecuencias +Consecuencias de la aplicación del filtro de interceptación + +* Aumento de la complejidad del código, disminuyendo la facilidad de lectura +* Puede haber problemas en el orden en que se aplican los filtros si el orden es importante +* Aplicar múltiples filtros a una petición puede crear un retraso en el tiempo de respuesta +* Probar los efectos de múltiples filtros en una petición puede ser difícil. +* La compatibilidad y la gestión de versiones pueden ser difíciles si se tienen muchos filtros. + +## Tutoriales + +* [Introduction to Intercepting Filter Pattern in Java](https://www.baeldung.com/intercepting-filter-pattern-in-java) + +## Ejemplos del mundo real + +* [javax.servlet.FilterChain](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/FilterChain.html) and [javax.servlet.Filter](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/Filter.html) +* [Struts 2 - Interceptors](https://struts.apache.org/core-developers/interceptors.html) + +## Créditos + +* [TutorialsPoint - Intercepting Filter](http://www.tutorialspoint.com/design_pattern/intercepting_filter_pattern.htm) diff --git a/localization/es/intercepting-filter/etc/intercepting-filter.png b/localization/es/intercepting-filter/etc/intercepting-filter.png new file mode 100644 index 000000000000..ec792639eab5 Binary files /dev/null and b/localization/es/intercepting-filter/etc/intercepting-filter.png differ diff --git a/localization/es/interpreter/README.md b/localization/es/interpreter/README.md new file mode 100644 index 000000000000..a2cfacf9c3be --- /dev/null +++ b/localization/es/interpreter/README.md @@ -0,0 +1,170 @@ +--- +title: Interpreter +shortTitle: Interpreter +category: Behavioral +language: es +tag: + - Gang of Four +--- + +## Propósito + +Dado un lenguaje, defina una representación para su gramática junto con un intérprete que utilice la +representación para interpretar las frases del lenguaje. + +## Explicación + +Ejemplo real + +> Los niños enanos están aprendiendo matemáticas básicas en la escuela. Empiezan por lo más básico: "1 + 1", "4 - 2", "5 + 5", etcétera. + +En palabras simples + +> El patrón intérprete interpreta las frases en el idioma deseado. + +Wikipedia dice + +> En programación informática, el patrón intérprete es un patrón de diseño que especifica cómo evaluar sentencias en un lenguaje. La idea básica es tener una clase para cada símbolo (terminal o no terminal) en un lenguaje informático especializado. El árbol sintáctico de una sentencia en el lenguaje es una instancia del patrón compuesto y se utiliza para evaluar (interpretar) la sentencia para un cliente. + +**Ejemplo programático** + +Para poder interpretar matemáticas básicas, necesitamos una jerarquía de expresiones. La abstracción básica para ello es la clase `Expression`. + +```java +public abstract class Expression { + + public abstract int interpret(); + + @Override + public abstract String toString(); +} +``` + +La más sencilla de las expresiones es la `NumberExpression` que contiene un único número entero. + +```java +public class NumberExpression extends Expression { + + private final int number; + + public NumberExpression(int number) { + this.number = number; + } + + public NumberExpression(String s) { + this.number = Integer.parseInt(s); + } + + @Override + public int interpret() { + return number; + } + + @Override + public String toString() { + return "number"; + } +} +``` + +Las expresiones más complejas son operaciones como `PlusExpression`, `MinusExpression` y +`MultiplicarExpresión`. Aquí está la primera de ellas, las otras son similares. + +```java +public class PlusExpression extends Expression { + + private final Expression leftExpression; + private final Expression rightExpression; + + public PlusExpression(Expression leftExpression, Expression rightExpression) { + this.leftExpression = leftExpression; + this.rightExpression = rightExpression; + } + + @Override + public int interpret() { + return leftExpression.interpret() + rightExpression.interpret(); + } + + @Override + public String toString() { + return "+"; + } +} +``` + +Ahora podemos mostrar el patrón del intérprete en acción analizando algunas matemáticas sencillas. + +```java + // the halfling kids are learning some basic math at school + // define the math string we want to parse + final var tokenString = "4 3 2 - 1 + *"; + + // the stack holds the parsed expressions + var stack = new Stack(); + + // tokenize the string and go through them one by one + var tokenList = tokenString.split(" "); + for (var s : tokenList) { + if (isOperator(s)) { + // when an operator is encountered we expect that the numbers can be popped from the top of + // the stack + var rightExpression = stack.pop(); + var leftExpression = stack.pop(); + LOGGER.info("popped from stack left: {} right: {}", + leftExpression.interpret(), rightExpression.interpret()); + var operator = getOperatorInstance(s, leftExpression, rightExpression); + LOGGER.info("operator: {}", operator); + var result = operator.interpret(); + // the operation result is pushed on top of the stack + var resultExpression = new NumberExpression(result); + stack.push(resultExpression); + LOGGER.info("push result to stack: {}", resultExpression.interpret()); + } else { + // numbers are pushed on top of the stack + var i = new NumberExpression(s); + stack.push(i); + LOGGER.info("push to stack: {}", i.interpret()); + } + } + // in the end, the final result lies on top of the stack + LOGGER.info("result: {}", stack.pop().interpret()); +``` + +La ejecución del programa produce la siguiente salida de consola. + +``` +popped from stack left: 1 right: 1 +operator: + +push result to stack: 2 +popped from stack left: 4 right: 2 +operator: * +push result to stack: 8 +result: 8 +``` + +## Diagrama de clases + +![alt text](./etc/interpreter_1.png "Interpreter") + +## Aplicabilidad + +Utilice el patrón Intérprete cuando exista un lenguaje que interpretar, y pueda representar las sentencias +del lenguaje como árboles sintácticos abstractos. El patrón Intérprete funciona mejor cuando + +* La gramática es simple. Para gramáticas complejas, la jerarquía de clases para la gramática se hace grande e inmanejable. Herramientas como los generadores de analizadores sintácticos son una mejor alternativa en estos casos. Pueden interpretar expresiones sin construir árboles sintácticos abstractos, lo que puede ahorrar espacio y posiblemente tiempo. +* La eficiencia no es una preocupación crítica. Por lo general, los intérpretes más eficientes no se implementan interpretando directamente los árboles de análisis sintáctico, sino traduciéndolos primero a otra forma. Por ejemplo, las expresiones regulares suelen transformarse en máquinas de estados. Pero incluso entonces, el traductor puede ser implementado por el patrón Intérprete, por lo que el patrón sigue siendo aplicable. + +## Usos conocidos + +* [java.util.Pattern](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) +* [java.text.Normalizer](http://docs.oracle.com/javase/8/docs/api/java/text/Normalizer.html) +* Todas las subclases de [java.text.Format](http://docs.oracle.com/javase/8/docs/api/java/text/Format.html) +* [javax.el.ELResolver](http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html) + + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/interpreter/etc/interpreter_1.png b/localization/es/interpreter/etc/interpreter_1.png new file mode 100644 index 000000000000..f10342a1df90 Binary files /dev/null and b/localization/es/interpreter/etc/interpreter_1.png differ diff --git a/localization/es/iterator/README.md b/localization/es/iterator/README.md new file mode 100644 index 000000000000..7a9be6ef016a --- /dev/null +++ b/localization/es/iterator/README.md @@ -0,0 +1,154 @@ +--- +title: Iterator +shortTitle: Iterator +category: Behavioral +language: es +tag: + - Gang of Four +--- + +## También conocido como + +Cursor + +## Propósito +Proporcionar una forma de acceder a los elementos de un objeto agregado secuencialmente sin exponer su +representación subyacente. + +## Explicación + +Ejemplo del mundo real + +> El cofre del tesoro contiene un conjunto de objetos mágicos. Hay múltiples tipos de artículos tales como anillos, +> Los objetos pueden buscarse por tipo utilizando un iterador que proporciona +> el cofre del tesoro. + +En palabras sencillas + +> Los contenedores pueden proporcionar una interfaz de iterador agnóstica de representación +> para proporcionar acceso a los elementos. + +Wikipedia dice + +> En programación orientada a objetos, el patrón iterador es un patrón de diseño en el que +> se utiliza un iterador para recorrer un contenedor y acceder a sus elementos. + +**Ejemplo programático** + +La clase principal de nuestro ejemplo es `TreasureChest` que contiene ítems. + +```java +public class TreasureChest { + + private final List items; + + public TreasureChest() { + items = List.of( + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); + } + + public Iterator iterator(ItemType itemType) { + return new TreasureChestItemIterator(this, itemType); + } + + public List getItems() { + return new ArrayList<>(items); + } +} +``` + +Esta es la clase `Item`: + +```java +public class Item { + + private ItemType type; + private final String name; + + public Item(ItemType type, String name) { + this.setType(type); + this.name = name; + } + + @Override + public String toString() { + return name; + } + + public ItemType getType() { + return type; + } + + public final void setType(ItemType type) { + this.type = type; + } +} + +public enum ItemType { + + ANY, WEAPON, RING, POTION + +} +``` + +La interfaz `Iterator` es extremadamente sencilla. + +```java +public interface Iterator { + + boolean hasNext(); + + T next(); +} +``` + +En el siguiente ejemplo, iteramos a través de los objetos de tipo anillo encontrados en el cofre. + +```java +var itemIterator = TREASURE_CHEST.iterator(ItemType.RING); +while (itemIterator.hasNext()) { + LOGGER.info(itemIterator.next().toString()); +} +``` + +Salida del programa: + +```java +Ring of shadows +Ring of armor +``` + +## Diagrama de clases + +![alt text](./etc/iterator_1.png "Iterator") + +## Aplicabilidad + +Utilizar el patrón Iterator + +* Para acceder al contenido de un objeto agregado sin exponer su representación interna. +* Para soportar múltiples recorridos de objetos agregados. +* Proporcionar una interfaz uniforme para recorrer diferentes estructuras de agregados. + +## Tutoriales + +* [How to Use Iterator?](http://www.tutorialspoint.com/java/java_using_iterator.htm) + +## Usos conocidos + +* [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html) +* [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/es/iterator/etc/iterator_1.png b/localization/es/iterator/etc/iterator_1.png new file mode 100644 index 000000000000..d8313bc5881f Binary files /dev/null and b/localization/es/iterator/etc/iterator_1.png differ diff --git a/localization/es/layers/README.md b/localization/es/layers/README.md new file mode 100644 index 000000000000..f6101b077948 --- /dev/null +++ b/localization/es/layers/README.md @@ -0,0 +1,97 @@ +--- +title: Layers +shortTitle: Layers +category: Architectural +language: es +tag: +- Decoupling +--- + +## Propósito + +Capas (*Layers* en inglés) es un patrón arquitectónico donde las responsabilidades del software se dividen entre diferentes +capas de la aplicación. + +## Explicación + +Ejemplo del mundo real + +> Considere un sitio web que muestra pasteles decorados para bodas y similares. En lugar de que la página web +> acceda directamente a la base de datos, depende de un servicio para entregar esta información. Luego, el +> servicio consulta la capa de datos para recopilar la información necesaria. + +En otras palabras + +> Con el patrón arquitectónico de Capas, diferentes responsabilidades residen en capas separadas. La capa de vista solo +> está interesada en la renderización, la capa de servicio ensambla los datos solicitados de varias fuentes, y +> la capa de datos obtiene la información del almacenamiento de datos. + +Wikipedia dice + +> En ingeniería de software, la arquitectura de varios niveles _multitier_ (a menudo referida como arquitectura n-tier) o +> arquitectura multicapa es una arquitectura cliente-servidor en la que las funciones de presentación, procesamiento de aplicaciones +> y gestión de datos están físicamente separadas. + +**Ejemplo programático** + +En la capa de datos, guardamos nuestros elementos básicos. `Cake` consta de capas (*layers*) y cobertura (*topping*). + +```java +@Entity +public class Cake { + @Id + @GeneratedValue + private Long id; + @OneToOne(cascade = CascadeType.REMOVE) + private CakeTopping topping; + @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER) + private Set layers; +} +``` + +La capa de servicio ofrece `CakeBakingService` para un fácil acceso a diferentes aspectos de los pasteles. + +```java +public interface CakeBakingService { + void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException; + List getAllCakes(); + void saveNewTopping(CakeToppingInfo toppingInfo); + List getAvailableToppings(); + void saveNewLayer(CakeLayerInfo layerInfo); + List getAvailableLayers(); +} +``` + +En la parte superior tenemos nuestra `View`, responsable de renderizar los pasteles. + +```java +public interface View { + void render(); +} +@Slf4j +public class CakeViewImpl implements View { + private final CakeBakingService cakeBakingService; + public CakeViewImpl(CakeBakingService cakeBakingService) { + this.cakeBakingService = cakeBakingService; + } + public void render() { + cakeBakingService.getAllCakes().forEach(cake -> LOGGER.info(cake.toString())); + } +} +``` + +## Diagrama de clases + +![alt text](./etc/layers.png "Layers") + +## Aplicabilidad + +Utilice la arquitectura de Capas cuando: + +* Quiera dividir claramente las responsabilidades del software en diferentes partes del programa. +* Quiera evitar que un cambio se propague a lo largo de la aplicación. +* Quiera hacer su aplicación más mantenible y testeable. + +## Créditos + +* [Pattern Oriented Software Architecture Volume 1: A System of Patterns](https://www.amazon.com/gp/product/0471958697/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0471958697&linkCode=as2&tag=javadesignpat-20&linkId=e3f42d7a2a4cc8c619bbc0136b20dadb) diff --git a/localization/es/layers/etc/layers.png b/localization/es/layers/etc/layers.png new file mode 100644 index 000000000000..a4bd8b19ddad Binary files /dev/null and b/localization/es/layers/etc/layers.png differ diff --git a/localization/es/lazy-loading/README.md b/localization/es/lazy-loading/README.md new file mode 100644 index 000000000000..8120732f607d --- /dev/null +++ b/localization/es/lazy-loading/README.md @@ -0,0 +1,30 @@ +--- +title: Lazy Loading +shortTitle: Lazy Loading +category: Idiom +language: es +tag: + - Performance +--- + +## Propósito +La carga diferida (*Lazy loading* en inglés) es un patrón de diseño comúnmente usado para diferir +la inicialización de un objeto hasta el punto en que se necesita. Puede +contribuir a la eficiencia en la operación del programa si se usa de manera adecuada. + +## Diagrama de clases +![alt text](./etc/lazy-loading.png "Lazy Loading") + +## Aplicabilidad +Utilice el modelo de Carga Diferida cuando: + +* La carga anticipada es costosa o el objeto a cargar podría no ser necesario en absoluto + +## Ejemplos del mundo real + +* Anotaciones JPA `@OneToOne`, `@OneToMany`, `@ManyToOne`, `@ManyToMany` y `fetch = FetchType.LAZY` + +## Créditos + +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321127420&linkCode=as2&tag=javadesignpat-20&linkId=d9f7d37b032ca6e96253562d075fcc4a) diff --git a/localization/es/lazy-loading/etc/lazy-loading.png b/localization/es/lazy-loading/etc/lazy-loading.png new file mode 100644 index 000000000000..bec0a7afbefe Binary files /dev/null and b/localization/es/lazy-loading/etc/lazy-loading.png differ diff --git a/localization/es/leader-election/README.md b/localization/es/leader-election/README.md new file mode 100644 index 000000000000..424b50731c8d --- /dev/null +++ b/localization/es/leader-election/README.md @@ -0,0 +1,836 @@ +--- +title: Leader Election +shortTitle: Leader Election +category: Behavioral +language: es +tag: + - Cloud distributed +--- + +## Propósito +El patrón de elección (Leader pattern) del líder se utiliza habitualmente en el diseño de sistemas en la nube. Puede ayudar a garantizar que las instancias de tarea seleccionen la instancia líder correctamente y no entren en conflicto entre sí, causen contención por recursos compartidos o interfieran inadvertidamente con el trabajo que otras instancias de tarea están realizando. + +## Explicación + +Ejemplo del mundo real +> En un sistema basado en la nube de escalado horizontal, múltiples instancias de la misma tarea podrían estar ejecutándose al mismo tiempo con cada instancia sirviendo a un usuario diferente. Si estas instancias escriben en un recurso compartido, es necesario coordinar sus acciones para evitar que cada instancia sobrescriba los cambios realizados por las demás. En otro escenario, si las tareas están realizando elementos individuales de un cálculo complejo en paralelo, los resultados necesitan ser agregados cuando todos ellos se completan. + +En palabras sencillas +> este patrón se utiliza en sistemas distribuidos basados en la nube en los que el líder debe actuar como coordinador/agregador entre instancias de escalado horizontal para evitar conflictos en los recursos compartidos. + +Wikipedia dice +> En computación distribuida, la elección del líder es el proceso de designar un único proceso como organizador de alguna tarea distribuida entre varios ordenadores (nodos). + +**Ejemplo programático** + +El algoritmo Ring y el algoritmo Bully implementan el patrón de elección de líder. +Cada algoritmo requiere que cada instancia participante tenga un ID único. + +```java +public interface Instance { + + /** + * Comprueba si la instancia está viva o no. + * + * @return {@code true} si la instancia está viva. + */ + boolean isAlive(); + + /** + * Establece el estado de salud de la instancia en cuestión. + * + * @param alive {@code true} por vivo. + */ + void setAlive(boolean alive); + + /** + * Consumir mensajes de otras instancias. + * + * @param message Mensaje enviado por otras instancias + */ + void onMessage(Message message); + +} +``` + +Clase abstracta que implementa las interfaces Instance y Runnable. + +```java +public abstract class AbstractInstance implements Instance, Runnable { + + protected static final int HEARTBEAT_INTERVAL = 5000; + private static final String INSTANCE = "Instance "; + + protected MessageManager messageManager; + protected Queue messageQueue; + protected final int localId; + protected int leaderId; + protected boolean alive; + + /** + * Constructor de BullyInstance. + */ + public AbstractInstance(MessageManager messageManager, int localId, int leaderId) { + this.messageManager = messageManager; + this.messageQueue = new ConcurrentLinkedQueue<>(); + this.localId = localId; + this.leaderId = leaderId; + this.alive = true; + } + + /** + * La instancia ejecutará el mensaje en su cola de mensajes periódicamente una vez que esté viva. + */ + @Override + @SuppressWarnings("squid:S2189") + public void run() { + while (true) { + if (!this.messageQueue.isEmpty()) { + this.processMessage(this.messageQueue.remove()); + } + } + } + + /** + * Una vez que los mensajes son enviados a una instancia determinada, se añaden a la cola y esperan a ser ejecutados. + * + * @param message Mensaje enviado por otras instancias + */ + @Override + public void onMessage(Message message) { + messageQueue.offer(message); + } + + /** + * Comprueba si la instancia está viva o no. + * + * @return {@code true} si la instancia está viva. + */ + @Override + public boolean isAlive() { + return alive; + } + + /** + * Establece el estado de salud de la instancia en cuestión. + * + * @param alive {@code true} por vivo. + */ + @Override + public void setAlive(boolean alive) { + this.alive = alive; + } + + /** + * Procesa el mensaje según su tipo. + * + * @param message Mensaje sondeado desde la cola. + */ + private void processMessage(Message message) { + switch (message.getType()) { + case ELECTION -> { + LOGGER.info(INSTANCE + localId + " - Election Message handling..."); + handleElectionMessage(message); + } + case LEADER -> { + LOGGER.info(INSTANCE + localId + " - Leader Message handling..."); + handleLeaderMessage(message); + } + case HEARTBEAT -> { + LOGGER.info(INSTANCE + localId + " - Heartbeat Message handling..."); + handleHeartbeatMessage(message); + } + case ELECTION_INVOKE -> { + LOGGER.info(INSTANCE + localId + " - Election Invoke Message handling..."); + handleElectionInvokeMessage(); + } + case LEADER_INVOKE -> { + LOGGER.info(INSTANCE + localId + " - Leader Invoke Message handling..."); + handleLeaderInvokeMessage(); + } + case HEARTBEAT_INVOKE -> { + LOGGER.info(INSTANCE + localId + " - Heartbeat Invoke Message handling..."); + handleHeartbeatInvokeMessage(); + } + default -> { + } + } + } + + /** + * Métodos abstractos para manejar diferentes tipos de mensajes. + * Estos métodos deben implementarse en la clase de instancia concreta para implementar el patrón de selección de líder correspondiente. + */ + protected abstract void handleElectionMessage(Message message); + + protected abstract void handleElectionInvokeMessage(); + + protected abstract void handleLeaderMessage(Message message); + + protected abstract void handleLeaderInvokeMessage(); + + protected abstract void handleHeartbeatMessage(Message message); + + protected abstract void handleHeartbeatInvokeMessage(); + +} +``` + +```java +/** + * Mensaje utilizado para transportar datos entre instancias. + */ +@Setter +@Getter +@EqualsAndHashCode +@AllArgsConstructor +@NoArgsConstructor +public class Message { + + private MessageType type; + private String content; + +} +``` + +```java +public interface MessageManager { + + /** + * Envía un mensaje heartbeat a la instancia líder para comprobar si la instancia líder está viva. + * + * @param leaderId ID de instancia de la instancia líder. + * @return {@code true} si la instancia líder está viva, o {@code false} si no. + */ + boolean sendHeartbeatMessage(int leaderId); + + /** + * Enviar mensaje electoral a otras instancias. + * + * @param currentId ID de la instancia que envía este mensaje. + * @param content Contenido del mensaje electoral. + * @return {@code true} si el mensaje es aceptado por las instancias de destino. + */ + boolean sendElectionMessage(int currentId, String content); + + /** + * Enviar mensaje de notificación de nuevo líder a otras instancias. + * + * @param currentId ID de la instancia que envía este mensaje. + * @param leaderId Contenido del mensaje del líder. + * @return {@code true} si el mensaje es aceptado por las instancias de destino. + */ + boolean sendLeaderMessage(int currentId, int leaderId); + + /** + * Enviar mensaje de invocación de heartbeat. Esto invocará la tarea heartbeat en la instancia de destino. + * + * @param currentId ID de la instancia que envía este mensaje. + */ + void sendHeartbeatInvokeMessage(int currentId); + +} +``` +These type of messages are used to pass among instances. +```java +/** + * Enum de tipo de mensaje. + */ +public enum MessageType { + + /** + * Comienza la elección. El contenido del mensaje almacena ID(s) de la(s) instancia(s) candidata(s). + */ + ELECTION, + + /** + * Nodifica al nuevo líder. El contenido del mensaje debe ser el ID del líder. + */ + LEADER, + + /** + * Comprueba la salud de la instancia de líder actual. + */ + HEARTBEAT, + + /** + * Informar a la instancia de destino para iniciar la elección. + */ + ELECTION_INVOKE, + + /** + * Informar a la instancia de destino para que notifique a todas las demás instancias que es el nuevo líder. + */ + LEADER_INVOKE, + + /** + * Informar a la instancia de destino para que inicie el heartbeat. + */ + HEARTBEAT_INVOKE + +} +``` + +Clase abstracta que implementa la interfaz MessageManager. Ayuda a gestionar mensajes entre instancias. + +```java +/** + * Clase abstracta de todas las clases de gestores de mensajes. + */ +public abstract class AbstractMessageManager implements MessageManager { + + /** + * Contiene todas las instancias del sistema. La clave es su ID y el valor es la propia instancia. + */ + + protected Map instanceMap; + + /** + * Constructor de AbstractMessageManager. + */ + public AbstractMessageManager(Map instanceMap) { + this.instanceMap = instanceMap; + } + + /** + * Encuentra la siguiente instancia con el ID más pequeño. + * + * @return La siguiente instancia. + */ + protected Instance findNextInstance(int currentId) { + Instance result = null; + var candidateList = instanceMap.keySet() + .stream() + .filter((i) -> i > currentId && instanceMap.get(i).isAlive()) + .sorted() + .toList(); + if (candidateList.isEmpty()) { + var index = instanceMap.keySet() + .stream() + .filter((i) -> instanceMap.get(i).isAlive()) + .sorted() + .toList() + .get(0); + result = instanceMap.get(index); + } else { + var index = candidateList.get(0); + result = instanceMap.get(index); + } + return result; + } + +} +``` + +Here the implementation of Ring Algorithm +```java +/** + * Implementación con algoritmo token ring. Las instancias en el sistema se organizan como un anillo. + * Cada instancia debe tener un id secuencial y la instancia con el id más pequeño (o más grande) debe + * ser el líder inicial. Todas las demás instancias envían un mensaje heartbeat al líder periódicamente para + * comprobar su salud. Si una instancia determinada encuentra que el servidor ha terminado, enviará un mensaje de elección + * a la siguiente instancia viva en el anillo, que contiene su propio ID. Entonces la siguiente instancia añade su + * ID en el mensaje y se lo pasa a la siguiente. Después de que todos los ID de las instancias vivas se añaden al * mensaje, el mensaje se devuelve. + * mensaje, el mensaje es enviado de vuelta a la primera instancia y ésta elegirá la instancia con + * menor ID para ser el nuevo líder, y entonces enviará un mensaje de líder a otras instancias para informar del + * resultado. + */ +@Slf4j +public class RingInstance extends AbstractInstance { + private static final String INSTANCE = "Instance "; + + /** + * Constructor de RingInstance. + */ + public RingInstance(MessageManager messageManager, int localId, int leaderId) { + super(messageManager, localId, leaderId); + } + + /** + * Procesar el mensaje de invocación heartbeat. Después de recibir el mensaje, la instancia enviará un + * heartbeat (latido) al líder para comprobar su salud. Si está vivo, informará a la siguiente instancia para hacer el + * heartbeat. Si no, iniciará el proceso de elección. + */ + @Override + protected void handleHeartbeatInvokeMessage() { + try { + var isLeaderAlive = messageManager.sendHeartbeatMessage(this.leaderId); + if (isLeaderAlive) { + LOGGER.info(INSTANCE + localId + "- Leader is alive. Start next heartbeat in 5 second."); + Thread.sleep(HEARTBEAT_INTERVAL); + messageManager.sendHeartbeatInvokeMessage(this.localId); + } else { + LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election."); + messageManager.sendElectionMessage(this.localId, String.valueOf(this.localId)); + } + } catch (InterruptedException e) { + LOGGER.info(INSTANCE + localId + "- Interrupted."); + } + } + + /** + * Procesar mensaje de elección. Si el ID local está contenido en la lista de ID, la instancia seleccionará + * la instancia viva con menor ID para ser el nuevo líder, y enviará el mensaje de información al líder. + * Si no, añadirá su ID local a la lista y enviará el mensaje a la siguiente instancia en el anillo. + * anillo. + */ + @Override + protected void handleElectionMessage(Message message) { + var content = message.getContent(); + LOGGER.info(INSTANCE + localId + " - Election Message: " + content); + var candidateList = Arrays.stream(content.trim().split(",")) + .map(Integer::valueOf) + .sorted() + .toList(); + if (candidateList.contains(localId)) { + var newLeaderId = candidateList.get(0); + LOGGER.info(INSTANCE + localId + " - New leader should be " + newLeaderId + "."); + messageManager.sendLeaderMessage(localId, newLeaderId); + } else { + content += "," + localId; + messageManager.sendElectionMessage(localId, content); + } + } + + /** + * Procesar mensaje de líder. La instancia establecerá el ID de líder para que sea el nuevo y enviará el + * mensaje a la siguiente instancia hasta que todas las instancias vivas del anillo estén informadas. + */ + @Override + protected void handleLeaderMessage(Message message) { + var newLeaderId = Integer.valueOf(message.getContent()); + if (this.leaderId != newLeaderId) { + LOGGER.info(INSTANCE + localId + " - Update leaderID"); + this.leaderId = newLeaderId; + messageManager.sendLeaderMessage(localId, newLeaderId); + } else { + LOGGER.info(INSTANCE + localId + " - Leader update done. Start heartbeat."); + messageManager.sendHeartbeatInvokeMessage(localId); + } + } + + /** + * No se utiliza en la instancia Ring. + */ + @Override + protected void handleLeaderInvokeMessage() { + // No se utiliza en la instancia Ring. + } + + @Override + protected void handleHeartbeatMessage(Message message) { + // No se utiliza en la instancia Ring. + } + + @Override + protected void handleElectionInvokeMessage() { + // No se utiliza en la instancia Ring. + } + +} +``` + +```java +/** + * Implementación de RingMessageManager. + */ +public class RingMessageManager extends AbstractMessageManager { + + /** + * Constructor de RingMessageManager. + */ + public RingMessageManager(Map instanceMap) { + super(instanceMap); + } + + /** + * Envía un mensaje de heartbeat a la instancia líder actual para comprobar su estado. + * + * @param leaderId leaderID + * @return {@code true} si el líder está vivo. + */ + @Override + public boolean sendHeartbeatMessage(int leaderId) { + var leaderInstance = instanceMap.get(leaderId); + var alive = leaderInstance.isAlive(); + return alive; + } + + /** + * Enviar mensaje de elección a la siguiente instancia. + * + * @param currentId currentID + * @param content contiene todos los ID de las instancias que han recibido este mensaje de elección + * mensaje. + * @return {@code true} si el mensaje de elección es aceptado por la instancia de destino. + */ + @Override + public boolean sendElectionMessage(int currentId, String content) { + var nextInstance = this.findNextInstance(currentId); + var electionMessage = new Message(MessageType.ELECTION, content); + nextInstance.onMessage(electionMessage); + return true; + } + + /** + * Enviar mensaje de líder a la siguiente instancia. + * + * @param currentId ID de la instancia que envía este mensaje. + * @param leaderId Contenido del mensaje del líder. + * @return {@code true} si el mensaje de líder es aceptado por la instancia de destino. + */ + @Override + public boolean sendLeaderMessage(int currentId, int leaderId) { + var nextInstance = this.findNextInstance(currentId); + var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); + nextInstance.onMessage(leaderMessage); + return true; + } + + /** + * Enviar mensaje de invocación de heartbeat a la siguiente instancia. + * + * @param currentId ID de la instancia que envía este mensaje. + */ + @Override + public void sendHeartbeatInvokeMessage(int currentId) { + var nextInstance = this.findNextInstance(currentId); + var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); + nextInstance.onMessage(heartbeatInvokeMessage); + } + +} +``` +```java +public static void main(String[] args) { + + Map instanceMap = new HashMap<>(); + var messageManager = new RingMessageManager(instanceMap); + + var instance1 = new RingInstance(messageManager, 1, 1); + var instance2 = new RingInstance(messageManager, 2, 1); + var instance3 = new RingInstance(messageManager, 3, 1); + var instance4 = new RingInstance(messageManager, 4, 1); + var instance5 = new RingInstance(messageManager, 5, 1); + + instanceMap.put(1, instance1); + instanceMap.put(2, instance2); + instanceMap.put(3, instance3); + instanceMap.put(4, instance4); + instanceMap.put(5, instance5); + + instance2.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); + + final var thread1 = new Thread(instance1); + final var thread2 = new Thread(instance2); + final var thread3 = new Thread(instance3); + final var thread4 = new Thread(instance4); + final var thread5 = new Thread(instance5); + + thread1.start(); + thread2.start(); + thread3.start(); + thread4.start(); + thread5.start(); + + instance1.setAlive(false); + } +``` + +The console output +``` +[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Heartbeat Invoke Message handling... +[Thread-1] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 2- Leader is not alive. Start election. +[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Election Message handling... +[Thread-2] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 3 - Election Message: 2 +[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Election Message handling... +[Thread-3] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 4 - Election Message: 2,3 +[Thread-4] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 5 - Election Message handling... +[Thread-4] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 5 - Election Message: 2,3,4 +[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Election Message handling... +[Thread-1] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 2 - Election Message: 2,3,4,5 +[Thread-1] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 2 - New leader should be 2. +[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Leader Message handling... +[Thread-2] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 3 - Update leaderID +[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Leader Message handling... +[Thread-3] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 4 - Update leaderID +[Thread-4] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 5 - Leader Message handling... +[Thread-4] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 5 - Update leaderID +[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Leader Message handling... +[Thread-1] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 2 - Update leaderID +[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Leader Message handling... +[Thread-2] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 3 - Leader update done. Start heartbeat. +[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Heartbeat Invoke Message handling... +[Thread-3] INFO com.iluwatar.leaderelection.ring.RingInstance - Instance 4- Leader is alive. Start next heartbeat in 5 second. +``` +Here the implementation of Bully algorithm +```java +/** + * Impelemetación con algoritmo bully. Cada instancia debe tener un id secuencial y es capaz de + * comunicarse con otras instancias del sistema. Inicialmente la instancia con menor (o mayor) + * ID más pequeño (o más grande) es seleccionado para ser el líder. Todas las demás instancias envían un mensaje heartbeat al líder + * periódicamente para comprobar su salud. Si una instancia determinada considera que el servidor ha terminado, enviará un mensaje de elección a todas las instancias del sistema. + * mensaje de elección a todas las instancias cuyo ID sea mayor. Si la instancia objetivo está viva, + * devolverá un mensaje alive (en este ejemplo devolverá true) y entonces enviará un mensaje de elección con + * su ID. Si no, la instancia original enviará un mensaje de líder a todas las demás instancias. + */ +@Slf4j +public class BullyInstance extends AbstractInstance { + private static final String INSTANCE = "Instance "; + + /** + * Constructor de BullyInstance. + */ + public BullyInstance(MessageManager messageManager, int localId, int leaderId) { + super(messageManager, localId, leaderId); + } + + /** + * Procesar el mensaje de invocación heartbeat. Después de recibir el mensaje, la instancia enviará un + * heartbeat al líder para comprobar su salud. Si está vivo, informará a la siguiente instancia para hacer el + * heartbeat. Si no, iniciará el proceso de elección. + */ + @Override + protected void handleHeartbeatInvokeMessage() { + try { + boolean isLeaderAlive = messageManager.sendHeartbeatMessage(leaderId); + if (isLeaderAlive) { + LOGGER.info(INSTANCE + localId + "- Leader is alive."); + Thread.sleep(HEARTBEAT_INTERVAL); + messageManager.sendHeartbeatInvokeMessage(localId); + } else { + LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election."); + boolean electionResult = + messageManager.sendElectionMessage(localId, String.valueOf(localId)); + if (electionResult) { + LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification."); + messageManager.sendLeaderMessage(localId, localId); + } + } + } catch (InterruptedException e) { + LOGGER.info(INSTANCE + localId + "- Interrupted."); + } + } + + /** + * Procesar mensaje de invocación de elección. Enviar mensaje de elección a todas las instancias con menor ID. Si + * alguna de ellas está viva, no hacer nada. Si ninguna instancia está viva, enviar mensaje de líder a todas las instancias vivas y reiniciar el heartbeat. + * instancia viva y reiniciar heartbeat. + */ + @Override + protected void handleElectionInvokeMessage() { + if (!isLeader()) { + LOGGER.info(INSTANCE + localId + "- Start election."); + boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId)); + if (electionResult) { + LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification."); + leaderId = localId; + messageManager.sendLeaderMessage(localId, localId); + messageManager.sendHeartbeatInvokeMessage(localId); + } + } + } + + /** + * Procesar mensaje de líder. Actualizar la información del líder local. + */ + @Override + protected void handleLeaderMessage(Message message) { + leaderId = Integer.valueOf(message.getContent()); + LOGGER.info(INSTANCE + localId + " - Leader update done."); + } + + private boolean isLeader() { + return localId == leaderId; + } + + @Override + protected void handleLeaderInvokeMessage() { + // Not used in Bully Instance + } + + @Override + protected void handleHeartbeatMessage(Message message) { + // Not used in Bully Instance + } + + @Override + protected void handleElectionMessage(Message message) { + // Not used in Bully Instance + } +} +``` + +```java +/** + * Implementación de BullyMessageManager. + */ +public class BullyMessageManager extends AbstractMessageManager { + + /** + * Constructor de BullyMessageManager. + */ + public BullyMessageManager(Map instanceMap) { + super(instanceMap); + } + + /** + * Envía un mensaje de heartbeat a la instancia líder actual para comprobar su estado. + * + * @param leaderId leaderID + * @return {@code true} si el líder está vivo. + */ + @Override + public boolean sendHeartbeatMessage(int leaderId) { + var leaderInstance = instanceMap.get(leaderId); + var alive = leaderInstance.isAlive(); + return alive; + } + + /** + * Enviar mensaje electoral a todas las instancias con menor ID. + * + * @param currentId ID de la instancia que envía este mensaje. + * @param content Contenido del mensaje electoral. + * @return {@code true} si ninguna instancia viva tiene menor ID, para que se acepte la elección. + */ + @Override + public boolean sendElectionMessage(int currentId, String content) { + var candidateList = findElectionCandidateInstanceList(currentId); + if (candidateList.isEmpty()) { + return true; + } else { + var electionMessage = new Message(MessageType.ELECTION_INVOKE, ""); + candidateList.stream().forEach((i) -> instanceMap.get(i).onMessage(electionMessage)); + return false; + } + } + + /** + * Enviar mensaje de líder a todas las instancias para notificar el nuevo líder. + * + * @param currentId ID de la instancia que envía este mensaje. + * @param leaderId Contenido del mensaje del líder. + * @return {@code true} si se acepta el mensaje. + */ + @Override + public boolean sendLeaderMessage(int currentId, int leaderId) { + var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); + instanceMap.keySet() + .stream() + .filter((i) -> i != currentId) + .forEach((i) -> instanceMap.get(i).onMessage(leaderMessage)); + return false; + } + + /** + * Enviar mensaje de invocación de heartbeat a la siguiente instancia. + * + * @param currentId ID de la instancia que envía este mensaje. + */ + @Override + public void sendHeartbeatInvokeMessage(int currentId) { + var nextInstance = this.findNextInstance(currentId); + var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); + nextInstance.onMessage(heartbeatInvokeMessage); + } + + /** + * Encuentra todas las instancias vivas con un ID menor que la instancia actual. + * + * @param currentId ID de la instancia actual. + * @return Lista de ID de todas las instancias candidatas. + */ + private List findElectionCandidateInstanceList(int currentId) { + return instanceMap.keySet() + .stream() + .filter((i) -> i < currentId && instanceMap.get(i).isAlive()) + .toList(); + } + +} +``` + +```java +public static void main(String[] args) { + + Map instanceMap = new HashMap<>(); + var messageManager = new BullyMessageManager(instanceMap); + + var instance1 = new BullyInstance(messageManager, 1, 1); + var instance2 = new BullyInstance(messageManager, 2, 1); + var instance3 = new BullyInstance(messageManager, 3, 1); + var instance4 = new BullyInstance(messageManager, 4, 1); + var instance5 = new BullyInstance(messageManager, 5, 1); + + instanceMap.put(1, instance1); + instanceMap.put(2, instance2); + instanceMap.put(3, instance3); + instanceMap.put(4, instance4); + instanceMap.put(5, instance5); + + instance4.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, "")); + + final var thread1 = new Thread(instance1); + final var thread2 = new Thread(instance2); + final var thread3 = new Thread(instance3); + final var thread4 = new Thread(instance4); + final var thread5 = new Thread(instance5); + + thread1.start(); + thread2.start(); + thread3.start(); + thread4.start(); + thread5.start(); + + instance1.setAlive(false); + } +``` + +La salida de la consola +``` +[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Heartbeat Invoke Message handling... +[Thread-3] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 4- Leader is alive. +[Thread-4] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 5 - Heartbeat Invoke Message handling... +[Thread-4] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 5- Leader is not alive. Start election. +[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Election Invoke Message handling... +[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Election Invoke Message handling... +[Thread-3] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 4- Start election. +[Thread-2] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 3- Start election. +[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Election Invoke Message handling... +[Thread-2] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 3- Start election. +[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Election Invoke Message handling... +[Thread-1] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 2- Start election. +[Thread-1] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 2- Succeed in election. Start leader notification. +[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Election Invoke Message handling... +[Thread-3] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 4 - Leader Message handling... +[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Leader Message handling... +[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Election Invoke Message handling... +[Thread-4] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 5 - Leader Message handling... +[Thread-0] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 1 - Leader Message handling... +[Thread-1] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 2 - Election Invoke Message handling... +[Thread-3] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 4 - Leader update done. +[Thread-2] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 3 - Leader update done. +[Thread-0] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 1 - Leader update done. +[Thread-4] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 5 - Leader update done. +[Thread-2] INFO com.iluwatar.leaderelection.AbstractInstance - Instance 3 - Heartbeat Invoke Message handling... +[Thread-2] INFO com.iluwatar.leaderelection.bully.BullyInstance - Instance 3- Leader is alive. +``` + +## Diagrama de clases +![alt text](./etc/leader-election.urm.png "Leader Election pattern class diagram") + +## Aplicabilidad +Utilice este patrón cuando + +* las tareas en una aplicación distribuida, como una solución alojada en la nube, requieren una coordinación cuidadosa y no hay un líder natural. + +No utilice este patrón cuando + +* exista un líder natural o un proceso dedicado que pueda actuar siempre como líder. Por ejemplo, puede ser posible implementar un proceso singleton que coordine las instancias de tareas. Si este proceso falla o se vuelve insalubre, el sistema puede apagarlo y reiniciarlo. +* la coordinación entre tareas puede lograrse fácilmente utilizando un mecanismo más ligero. Por ejemplo, si varias instancias de tareas simplemente requieren un acceso coordinado a un recurso compartido, una solución preferible podría ser utilizar un bloqueo optimista o pesimista para controlar el acceso a ese recurso. + +## Créditos + +* [Leader Election pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/leader-election) +* [Raft Leader Election](https://github.com/ronenhamias/raft-leader-election) diff --git a/localization/es/leader-election/etc/leader-election.urm.png b/localization/es/leader-election/etc/leader-election.urm.png new file mode 100644 index 000000000000..85a90b75b636 Binary files /dev/null and b/localization/es/leader-election/etc/leader-election.urm.png differ diff --git a/localization/es/map-reduce/README.md b/localization/es/map-reduce/README.md new file mode 100644 index 000000000000..28a77f0062a1 --- /dev/null +++ b/localization/es/map-reduce/README.md @@ -0,0 +1,256 @@ +--- +title: "Patrón de Diseño MapReduce en Java" +shortTitle: MapReduce +description: "Aprende el patrón de diseño MapReduce en Java con ejemplos de la vida real, diagramas de clases y tutoriales. Entiende su intención, aplicación, beneficios y usos conocidos para mejorar tu conocimiento sobre patrones de diseño." +category: Optimización de Rendimiento +language: es +tag: + - Data processing + - Code simplification + - Delegation + - Performance + - Procesamiento de datos + - Simplificación de coódigo + - Delegación + - Rendimiento +--- + +## También conocido como: + +- Estrategia Separa-Aplica-Combina (Split-Apply-Combine Strategy) +- Patrón Dispersa-Recolecta (Scatter-Gather Pattern) + +## Intención del Patrón de Diseño Map Reduce + +MapReduce pretende procesar y generar grandes conjuntos de datos con un algoritmo en paralelo y distribuido en un grupo. Divide la carga de trabajo en dos fases principales: Mapear (Map) y Reducir (Reduce), permitiendo así una mayor eficiencia en procesamiento de datos en paralelo. + +## Explicación Detallada del Patrón de Diseño Map Reduce con Ejemplos del Mundo Real + +Ejemplo Práctico + +> Imagina una compañía de comercio en línea (e-commerce) que quiere analizar sus datos de ventas a lo largo de múltplies regiones. Tienen terabytes de datos de transacciones almacenados en cientos de servidores. Usando MapReduce, pueden procesar estos datos eficientemente para calcular las ventas totales por categoría de producto. La función Map procesaría registros de ventas individuales, regresando pares clave-valor de (categoría, cantidad de venta). La función Reduce entonces sumaría todas las cantidades de ventas por cada categoría, produciendo el resultado final. + +En palabras sencillas + +> MapReduce divide un gran problema en partes más pequeñas, las procesa en paralelo y después combina los resultados. + +En Wikipedia dice: + +> "MapReduce es un modelo de programación e implementación asociada para procesar y generar grandes conjuntos de información con un algoritmo en paralelo y distribuido en un grupo". +> MapReduce consiste de dos funciones principales: +> El nodo principal toma la entrada de información, la divide en problemas más pequeños (sub-problemas) y los distribuye a los nodos restantes (de trabajo). Un nodo de trabajo puede repetir este proceso llevando a una estructura de árbol multinivel. El nodo de trabajo procesa el sub-problema y le regresa la respuesta al nodo principal. +> El nodo principal recolecta todas las respuestas de todos los sub-problemas y las combina de cierta manera para regresar la salida de información - la respuesta del principal problema que estaba resolviendo. +> Este acercamiento permite un procesamiento eficiente de grandes cantidades de datos através de múltiples máquinas, convirtiéndola en una técnica fundamental en análisis de cantidades enormes de datos y computo distribuido. + +## Ejemplo Programático de Map Reduce en Java + +### 1. Fase de Map (Mapeador; División & Procesamiento de Datos) + +- El Mapper toma una entrada de texto (string), lo divide en palabras y cuenta las ocurrencias. +- Salida: Un mapa {palabra → conteo} por cada línea de entrada. + +#### `Mapper.java` + +```java +public class Mapper { + public static Map map(String input) { + Map wordCount = new HashMap<>(); + String[] words = input.split("\\s+"); + for (String word : words) { + word = word.toLowerCase().replaceAll("[^a-z]", ""); + if (!word.isEmpty()) { + wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); + } + } + return wordCount; + } +} +``` + +Ejemplo de Entrada: `"Hello world hello"` +Salida: `{hello=2, world=1}` + +### 2. Fase de Shuffle (Combinación; Agrupar Datos por Clave) + +- La Combinación recolecta pares clave-valor de múltiples mapeadores (mappers) y valores de grupo por clave. + +#### `Shuffler.java` + +```java +public class Shuffler { + public static Map> shuffleAndSort(List> mapped) { + Map> grouped = new HashMap<>(); + for (Map map : mapped) { + for (Map.Entry entry : map.entrySet()) { + grouped.putIfAbsent(entry.getKey(), new ArrayList<>()); + grouped.get(entry.getKey()).add(entry.getValue()); + } + } + return grouped; + } +} +``` + +Ejemplo de Entrada: + +``` +[ + {"hello": 2, "world": 1}, + {"hello": 1, "java": 1} +] +``` + +Salida: + +``` +{ + "hello": [2, 1], + "world": [1], + "java": [1] +} +``` + +### 3. Fase de Reduce (Reductor; Agregar Resultados) + +- El Reductor suma todas las ocurrencias de cada palabra. + +#### `Reducer.java` + +```java +public class Reducer { + public static List> reduce(Map> grouped) { + Map reduced = new HashMap<>(); + for (Map.Entry> entry : grouped.entrySet()) { + reduced.put(entry.getKey(), entry.getValue().stream().mapToInt(Integer::intValue).sum()); + } + + List> result = new ArrayList<>(reduced.entrySet()); + result.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); + return result; + } +} +``` + +Ejemplo de Entrada: + +``` +{ + "hello": [2, 1], + "world": [1], + "java": [1] +} +``` + +Salida: + +``` +[ + {"hello": 3}, + {"world": 1}, + {"java": 1} +] +``` + +### 4. Ejecutar el Proceso Completo de MapReduce + +- La clase MapReduce coordina los tres pasos. + +#### `MapReduce.java` + +```java +public class MapReduce { + public static List> mapReduce(List inputs) { + List> mapped = new ArrayList<>(); + for (String input : inputs) { + mapped.add(Mapper.map(input)); + } + + Map> grouped = Shuffler.shuffleAndSort(mapped); + + return Reducer.reduce(grouped); + } +} +``` + +### 5. Ejecución Principal (Llamar a MapReduce) + +- La clase Main ejecuta el "pipeline" de MapReduce y regresa el conteo final de palabras. + +#### `Main.java` + +```java + public static void main(String[] args) { + List inputs = Arrays.asList( + "Hello world hello", + "MapReduce is fun", + "Hello from the other side", + "Hello world" + ); + List> result = MapReduce.mapReduce(inputs); + for (Map.Entry entry : result) { + System.out.println(entry.getKey() + ": " + entry.getValue()); + } +} +``` + +Salida: + +``` +hello: 4 +world: 2 +the: 1 +other: 1 +side: 1 +mapreduce: 1 +is: 1 +from: 1 +fun: 1 +``` + +## Cuándo Usar el Patrón de Diseño MapReduce en Java + +Usa MapReduce cuando se están: + +- Procesando grandes conjuntos de información que no quepa en la memoria de una sola máquina. +- Realizando cálculos que se puedan desarrollar en paralelo. +- Trabajando en escenarios tolerante a fallos y computación distribuida. +- Analizando archivos de registro, datos de rastreo web o datos científicos. + +## Tutoriales del Patrón de Diseño MapReduce en Java + +- [Tutorial MapReduce (Apache Hadoop)](https://hadoop.apache.org/docs/stable/hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduceTutorial.html) +- [Ejemplo MapReduce (Simplilearn)](https://www.youtube.com/watch?v=l2clwKnrtO8) + +## Ventajas y Desventajas del Patrón de Diseño MapReduce + +Ventajas: + +- Escalabilidad: Puede procesar grandes cantidades de datos através de múltiples máquinas +- Tolerancia a Fallos: Maneja los fallos elegantemente +- Simplicidad: Resume detalles complejos de distribución computacional + +Desventajas: + +- Costo-Beneficio: Ineficiente para conjuntos de datos chicos por la preparación y coordinación necesaria +- Flexibilidad Limitada: Inadecuado para todos los tipos de computación o algoritmos +- Latencia: En relación a lotes de información podría ser inadecaudo para necesidades de procesamiento en tiempo real + +## Aplicaciones Reales para el Patrón de Diseño MapReduce en Java + +- Implementación original de Google para indexar páginas web +- Hadoop MapReduce para procesamiento de información extensa +- Sistemas de análisis de registros a gran escala +- Secuencia genómica en análisis de bio-informática + +## Patrones de Diseño relacionados a Java + +- Patrón de Encadenamiento (Chaining Pattern) +- Patrón de Maestro-Trabajador (Master-Worker Pattern) +- Patrón de Tubería (Pipeline Pattern) + +## Referencias y Creditos + +- [¿Qué es MapReduce?](https://www.ibm.com/think/topics/mapreduce) +- [¿Por qué MapReduce no ha muerto?](https://www.codemotion.com/magazine/ai-ml/big-data/mapreduce-not-dead-heres-why-its-still-ruling-in-the-cloud/) +- [Soluciones Escalables de Procesamiento de Datos Distribuidos](https://tcpp.cs.gsu.edu/curriculum/?q=system%2Ffiles%2Fch07.pdf) +- [Patrones de Diseño en Java: Experiencia Práctica con Ejemplos del Mundo Real](https://amzn.to/3HWNf4U) diff --git a/localization/es/marker/README.md b/localization/es/marker/README.md new file mode 100644 index 000000000000..0073f398a6f6 --- /dev/null +++ b/localization/es/marker/README.md @@ -0,0 +1,29 @@ +--- +title: Marker Interface +shortTitle: Marker Interface +category: Structural +language: es +tag: + - Decoupling +--- + +## Propósito +Utilización de interfaces vacías como marcadores para distinguir objetos con un tratamiento especial. + +## Diagrama de clases +![alt text](./etc/MarkerDiagram.png "Marker Interface") + +## Aplicabilidad +Utilice el patrón de interfaz de marcador cuando + +* Desea identificar los objetos especiales de los objetos normales (para tratarlos de forma diferente) +* Desea indicar que un objeto está disponible para cierto tipo de operaciones. + +## Ejemplos del mundo real + +* [javase.8.docs.api.java.io.Serializable](https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html) +* [javase.8.docs.api.java.lang.Cloneable](https://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html) + +## Créditos + +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) diff --git a/marker/etc/MarkerDiagram.png b/localization/es/marker/etc/MarkerDiagram.png similarity index 100% rename from marker/etc/MarkerDiagram.png rename to localization/es/marker/etc/MarkerDiagram.png diff --git a/localization/es/mediator/README.md b/localization/es/mediator/README.md new file mode 100644 index 000000000000..c70384cc9a0e --- /dev/null +++ b/localization/es/mediator/README.md @@ -0,0 +1,191 @@ +--- +title: Mediator +shortTitle: Mediator +category: Behavioral +language: es +tag: + - Gang Of Four + - Decoupling +--- + +## Propósito + +Define un objeto que encapsula cómo interactúa un conjunto de objetos. Mediator fomenta el acoplamiento flexible al evitar que los objetos se refieran entre sí de forma explícita, y te permite variar su interacción de forma independiente. + +## Explicación + +Un ejemplo real + +> Pícaro, mago, hobbit y cazador han decidido unir sus fuerzas y viajar en la misma party. Para evitar acoplar a cada miembro entre sí, utilizan la interfaz de la party para comunicarse entre ellos. + +En pocas palabras + +> Mediator desacopla un conjunto de clases forzando su flujo de comunicaciones a través de un objeto mediador. + +Wikipedia dice + +> En ingeniería de software, el patrón mediador define un objeto que encapsula cómo interactúa un conjunto de objetos. Este patrón se considera un patrón de comportamiento debido a la forma en que puede alterar el comportamiento de ejecución del programa. En la programación orientada a objetos, los programas suelen constar de muchas clases. La lógica de negocio y la computación se distribuyen entre estas clases. Sin embargo, a medida que se añaden más clases a un programa, especialmente durante el mantenimiento y/o la refactorización, el problema de la comunicación entre estas clases puede volverse más complejo. Esto hace que el programa sea más difícil de leer y mantener. Además, puede resultar difícil modificar el programa, ya que cualquier cambio puede afectar al código de otras clases. Con el patrón mediador, la comunicación entre objetos se encapsula en un objeto mediador. Los objetos ya no se comunican directamente entre sí, sino a través del mediador. Esto reduce las dependencias entre los objetos que se comunican, reduciendo así el acoplamiento. + +**Ejemplo programático** + +En este ejemplo, el mediador encapsula cómo interactúan un conjunto de objetos. En lugar de referirse unos a otros directamente, utilizan la interfaz del mediador. + +Los miembros de la party `Rogue`, `Wizard`, `Hobbit`, y `Hunter` heredan del `PartyMemberBase` implementando la interfaz `PartyMember`. + +```java +public interface PartyMember { + + void joinedParty(Party party); + + void partyAction(Action action); + + void act(Action action); +} + +@Slf4j +public abstract class PartyMemberBase implements PartyMember { + + protected Party party; + + @Override + public void joinedParty(Party party) { + LOGGER.info("{} joins the party", this); + this.party = party; + } + + @Override + public void partyAction(Action action) { + LOGGER.info("{} {}", this, action.getDescription()); + } + + @Override + public void act(Action action) { + if (party != null) { + LOGGER.info("{} {}", this, action); + party.act(this, action); + } + } + + @Override + public abstract String toString(); +} + +public class Rogue extends PartyMemberBase { + + @Override + public String toString() { + return "Rogue"; + } +} + +// Wizard, Hobbit, and Hunter are implemented similarly +``` + +Nuestro sistema mediador consta de la interfaz `Party` y su implementación. + +```java +public interface Party { + + void addMember(PartyMember member); + + void act(PartyMember actor, Action action); +} + +public class PartyImpl implements Party { + + private final List members; + + public PartyImpl() { + members = new ArrayList<>(); + } + + @Override + public void act(PartyMember actor, Action action) { + for (var member : members) { + if (!member.equals(actor)) { + member.partyAction(action); + } + } + } + + @Override + public void addMember(PartyMember member) { + members.add(member); + member.joinedParty(this); + } +} +``` + +Aquí tienes una demo que muestra el patrón mediador (Mediator) en acción. + +```java + // create party and members + Party party = new PartyImpl(); + var hobbit = new Hobbit(); + var wizard = new Wizard(); + var rogue = new Rogue(); + var hunter = new Hunter(); + + // add party members + party.addMember(hobbit); + party.addMember(wizard); + party.addMember(rogue); + party.addMember(hunter); + + // perform actions -> the other party members + // are notified by the party + hobbit.act(Action.ENEMY); + wizard.act(Action.TALE); + rogue.act(Action.GOLD); + hunter.act(Action.HUNT); +``` + +Esta es la salida de la consola al ejecutar el ejemplo. + +``` +Hobbit joins the party +Wizard joins the party +Rogue joins the party +Hunter joins the party +Hobbit spotted enemies +Wizard runs for cover +Rogue runs for cover +Hunter runs for cover +Wizard tells a tale +Hobbit comes to listen +Rogue comes to listen +Hunter comes to listen +Rogue found gold +Hobbit takes his share of the gold +Wizard takes his share of the gold +Hunter takes his share of the gold +Hunter hunted a rabbit +Hobbit arrives for dinner +Wizard arrives for dinner +Rogue arrives for dinner +``` + +## Diagrama de clases + +![alt text](./etc/mediator_1.png "Mediator") + +## Aplicabilidad + +Utilice el patrón Mediator cuando: + +* Un conjunto de objetos se comunican de formas bien definidas pero complejas. Las interdependencias resultantes no están estructuradas y son difíciles de entender +* La reutilización de un objeto es difícil porque hace referencia y se comunica con muchos otros objetos. +* Un comportamiento que se distribuye entre varias clases debe ser personalizable sin muchas subclases. + +## Usos conocidos + +* Todos los métodos scheduleXXX() de [java.util.Timer](http://docs.oracle.com/javase/8/docs/api/java/util/Timer.html) +* [java.util.concurrent.Executor#execute()](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-) +* Métodos submit() e invokeXXX() de [java.util.concurrent.ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) +* Método scheduleXXX() de [java.util.concurrent.ScheduledExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html) +* [java.lang.reflect.Method#invoke()](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#invoke-java.lang.Object-java.lang.Object...-) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/es/mediator/etc/mediator_1.png b/localization/es/mediator/etc/mediator_1.png new file mode 100644 index 000000000000..0b48ffdbaee7 Binary files /dev/null and b/localization/es/mediator/etc/mediator_1.png differ diff --git a/localization/es/memento/README.md b/localization/es/memento/README.md new file mode 100644 index 000000000000..9b0e44ee7c09 --- /dev/null +++ b/localization/es/memento/README.md @@ -0,0 +1,170 @@ +--- +title: Memento +shortTitle: Memento +category: Behavioral +language: es +tag: + - Gang of Four +--- + +## También conocido como + +Token + +## Propósito + +Sin violar la encapsulación, capturar y externalizar el estado interno de un objeto para que el objeto pueda ser restaurado a este estado más tarde. + +## Explicación + +Ejemplo del mundo real + +> Estamos trabajando en una aplicación de astrología en la que necesitamos analizar las propiedades de las estrellas a lo largo del tiempo. Estamos creando instantáneas de los estados de las estrellas utilizando el patrón Memento. + +En palabras sencillas + +> El patrón Memento captura el estado interno de los objetos facilitando su almacenamiento y restauración en cualquier punto del tiempo. + +Wikipedia dice + +> El patrón memento es un patrón de diseño de software que proporciona la capacidad de restaurar un objeto a su estado anterior (deshacer vía rollback). + +**Ejemplo programático** + +Definamos primero los tipos de estrellas que somos capaces de manejar. + +```java +public enum StarType { + SUN("sun"), + RED_GIANT("red giant"), + WHITE_DWARF("white dwarf"), + SUPERNOVA("supernova"), + DEAD("dead star"); + ... +} +``` + +A continuación, vayamos directamente a lo esencial. Aquí está la clase `Star` junto con los mementos que necesitamos manipular. Presta especial atención a los métodos `getMemento` y `setMemento`. + +```java +public interface StarMemento { +} + +public class Star { + + private StarType type; + private int ageYears; + private int massTons; + + public Star(StarType startType, int startAge, int startMass) { + this.type = startType; + this.ageYears = startAge; + this.massTons = startMass; + } + + public void timePasses() { + ageYears *= 2; + massTons *= 8; + switch (type) { + case RED_GIANT -> type = StarType.WHITE_DWARF; + case SUN -> type = StarType.RED_GIANT; + case SUPERNOVA -> type = StarType.DEAD; + case WHITE_DWARF -> type = StarType.SUPERNOVA; + case DEAD -> { + ageYears *= 2; + massTons = 0; + } + default -> { + } + } + } + + StarMemento getMemento() { + var state = new StarMementoInternal(); + state.setAgeYears(ageYears); + state.setMassTons(massTons); + state.setType(type); + return state; + } + + void setMemento(StarMemento memento) { + var state = (StarMementoInternal) memento; + this.type = state.getType(); + this.ageYears = state.getAgeYears(); + this.massTons = state.getMassTons(); + } + + @Override + public String toString() { + return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons); + } + + private static class StarMementoInternal implements StarMemento { + + private StarType type; + private int ageYears; + private int massTons; + + // setters and getters -> + ... + } +} +``` + +Y, por último, así es como utilizamos los recuerdos para almacenar y restaurar estados estelares. + +```java + var states = new Stack<>(); + var star = new Star(StarType.SUN, 10000000, 500000); + LOGGER.info(star.toString()); + states.add(star.getMemento()); + star.timePasses(); + LOGGER.info(star.toString()); + states.add(star.getMemento()); + star.timePasses(); + LOGGER.info(star.toString()); + states.add(star.getMemento()); + star.timePasses(); + LOGGER.info(star.toString()); + states.add(star.getMemento()); + star.timePasses(); + LOGGER.info(star.toString()); + while (states.size() > 0) { + star.setMemento(states.pop()); + LOGGER.info(star.toString()); + } +``` + +Salida del programa: + +``` +sun age: 10000000 years mass: 500000 tons +red giant age: 20000000 years mass: 4000000 tons +white dwarf age: 40000000 years mass: 32000000 tons +supernova age: 80000000 years mass: 256000000 tons +dead star age: 160000000 years mass: 2048000000 tons +supernova age: 80000000 years mass: 256000000 tons +white dwarf age: 40000000 years mass: 32000000 tons +red giant age: 20000000 years mass: 4000000 tons +sun age: 10000000 years mass: 500000 tons +``` + +## Diagrama de clases + +![alt text](./etc/memento.png "Memento") + +## Aplicabilidad + +Utilice el patrón Memento cuando: + +* Es necesario guardar una instantánea del estado de un objeto para poder restaurarlo más tarde, y +* Una interfaz directa para obtener el estado expondría detalles de implementación y rompería la encapsulación del objeto. + +## Usos conocidos + +* [java.util.Date](http://docs.oracle.com/javase/8/docs/api/java/util/Date.html) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/es/memento/etc/memento.png b/localization/es/memento/etc/memento.png new file mode 100644 index 000000000000..dcfe7a749b04 Binary files /dev/null and b/localization/es/memento/etc/memento.png differ diff --git a/localization/es/module/README.md b/localization/es/module/README.md new file mode 100644 index 000000000000..23a0452ed7a6 --- /dev/null +++ b/localization/es/module/README.md @@ -0,0 +1,165 @@ +--- +title: Module +shortTitle: Module +category: Structural +language: es +tag: + - Decoupling +--- + +## Propósito +El patrón de módulos se utiliza para implementar el concepto de módulos de software, definido por la programación modular, en un lenguaje de programación con soporte directo incompleto para el concepto. + +## Explicación + +Ejemplo real + +> En una bulliciosa ciudad del software, distintos componentes de software, como la base de datos, la interfaz de usuario y la API, a menudo necesitan colaborar. En lugar de que cada componente hable directamente con los demás, confían en el gestor de módulos. Este gestor de módulos actúa como un mercado central, donde cada componente registra sus servicios y solicitudes para los demás. Esto garantiza que los componentes permanezcan desacoplados y que los cambios en uno de ellos no afecten a todo el sistema. + + +> Imagina un smartphone moderno. Tiene distintas aplicaciones, como mensajería, cámara y reproductor de música. Aunque cada una funciona de forma independiente, a veces necesitan compartir recursos como el acceso a los contactos o el almacenamiento. En lugar de que cada aplicación tenga su propia forma de acceder a estos recursos, utilizan los módulos integrados del teléfono, como el módulo de contactos o el de almacenamiento. Esto garantiza una experiencia coherente para el usuario y evita posibles conflictos entre aplicaciones. + +En pocas palabras + +> El patrón Módulo encapsula funciones y datos relacionados en una sola unidad, lo que permite tener componentes de software organizados y manejables. + +Wikipedia dice + +> En ingeniería de software, el patrón módulo es un patrón de diseño utilizado para implementar el concepto de módulos de software, definido por la programación modular, en un lenguaje de programación con soporte directo incompleto para el concepto. + +> Este patrón se puede implementar de varias maneras dependiendo del lenguaje de programación anfitrión, como el patrón de diseño singleton, miembros estáticos orientados a objetos en una clase y funciones globales de procedimiento. En Python, el patrón está integrado en el lenguaje, y cada archivo .py es automáticamente un módulo. Lo mismo ocurre en Ada, donde el paquete puede considerarse un módulo (similar a una clase estática). + +**Ejemplo programático** + +```java +//Define Logger abstract class +abstract class Logger { + protected String output; + protected String error; + + public abstract void prepare(); + public abstract void unprepare(); + public abstract void printString(String message); + public abstract void printErrorString(String errorMessage); +} + +//File log module +class FileLoggerModule extends Logger { + private static final String OUTPUT_FILE = "output.log"; + private static final String ERROR_FILE = "error.log"; + + private static FileLoggerModule instance; + + private FileLoggerModule() { + this.output = OUTPUT_FILE; + this.error = ERROR_FILE; + } + + public static FileLoggerModule getSingleton() { + if (instance == null) { + instance = new FileLoggerModule(); + } + return instance; + } + + @Override + public void prepare() { + // For example, open file operation + // add the action you want + } + + @Override + public void unprepare() { + // For example, close file operation + // add the action you want + } + + @Override + public void printString(String message) { + System.out.println("Writing to " + output + ": " + message); + } + + @Override + public void printErrorString(String errorMessage) { + System.out.println("Writing to " + error + ": " + errorMessage); + } +} + +//Console log module +class ConsoleLoggerModule extends Logger { + private static ConsoleLoggerModule instance; + + private ConsoleLoggerModule() {} + + public static ConsoleLoggerModule getSingleton() { + if (instance == null) { + instance = new ConsoleLoggerModule(); + } + return instance; + } + + @Override + public void prepare() { + //Initialize console operation + } + + @Override + public void unprepare() { + //End console operation + } + + @Override + public void printString(String message) { + System.out.println("Console Output: " + message); + } + + @Override + public void printErrorString(String errorMessage) { + System.err.println("Console Error: " + errorMessage); + } +} + + +public class App { + public void prepare() { + FileLoggerModule.getSingleton().prepare(); + ConsoleLoggerModule.getSingleton().prepare(); + } + + public void unprepare() { + FileLoggerModule.getSingleton().unprepare(); + ConsoleLoggerModule.getSingleton().unprepare(); + } + + public void execute(String message) { + FileLoggerModule.getSingleton().printString(message); + ConsoleLoggerModule.getSingleton().printString(message); + } + + public static void main(String[] args) { + App app = new App(); + app.prepare(); + app.execute("Hello, Module Pattern!"); + app.unprepare(); + } +} +``` + +Resultados del programa: + +``` +Writing to output.log: Hello, Module Pattern! +Console Output: Hello, Module Pattern! +``` + +## Diagrama de clases +![alt text](./etc/module.png "Module") + +## Aplicabilidad +El patrón Módulo puede considerarse un patrón de creación y un patrón estructural. Gestiona la creación y organización de otros elementos, y los agrupa como lo hace el patrón estructural. + +Un objeto que aplica este patrón puede proporcionar el equivalente de un espacio de nombres, proporcionando el proceso de inicialización y finalización de una clase estática o de una clase con miembros estáticos con una sintaxis y una semántica más limpias y concisas. + +## Créditos + +* [Module](https://en.wikipedia.org/wiki/Module_pattern) diff --git a/module/etc/module.png b/localization/es/module/etc/module.png similarity index 100% rename from module/etc/module.png rename to localization/es/module/etc/module.png diff --git a/localization/es/monostate/README.md b/localization/es/monostate/README.md new file mode 100644 index 000000000000..17a32b8beb51 --- /dev/null +++ b/localization/es/monostate/README.md @@ -0,0 +1,34 @@ +--- +title: MonoState +shortTitle: MonoState +category: Creational +language: es +tag: + - Instantiation +--- + +## También conocido como +Borg + +## Propósito +Impone un comportamiento como compartir el mismo estado entre todas las instancias. + +## Diagrama de Clases +![alt text](./etc/monostate.png "MonoState") + +## Applicability +Utilice el patrón Monostate cuando + +* El mismo estado debe ser compartido por todas las instancias de una clase. +* Típicamente, este patrón puede ser usado en cualquier lugar donde un Singleton pueda ser usado. Sin embargo, el uso de Singleton no es transparente, el uso de Monostate sí lo es. +* Monostate tiene una gran ventaja sobre Singleton. Las subclases pueden decorar el estado compartido como deseen y, por lo tanto, pueden proporcionar dinámicamente un comportamiento diferente de la clase base. + +## Casos de uso típicos + +* La clase de registro +* Gestión de una conexión a una base de datos +* Gestor de archivos + +## Ejemplos del mundo real + +Aún no lo he visto. diff --git a/localization/es/monostate/etc/monostate.png b/localization/es/monostate/etc/monostate.png new file mode 100644 index 000000000000..273fa95459d4 Binary files /dev/null and b/localization/es/monostate/etc/monostate.png differ diff --git a/localization/es/multiton/README.md b/localization/es/multiton/README.md new file mode 100644 index 000000000000..032075cb9bb2 --- /dev/null +++ b/localization/es/multiton/README.md @@ -0,0 +1,141 @@ +--- +title: Multiton +shortTitle: Multiton +category: Creational +language: es +tag: + - Instantiation +--- + +## También conocido como + +Registry + +## Propósito + +Asegúrese de que una clase solo tiene un número limitado de instancias y proporcione un punto de acceso global a las +mismas. + +## Explicación + +Ejemplo del mundo real + +> Los Nazgûl, también llamados espectros del anillo o los Nueve Jinetes, son los sirvientes más terribles de Sauron. Por +> definición, siempre hay nueve de ellos. + +En palabras simples + +> El patrón Multiton asegura que hay una cantidad predefinida de instancias disponibles globalmente. + +Wikipedia dice + +> En ingeniería de software, el patrón multiton es un patrón de diseño que generaliza el patrón singleton. Mientras que +> el singleton permite que solo se cree una instancia de una clase, el patrón multiton permite la creación controlada de +> múltiples instancias, las cuales gestiona mediante el uso de un mapa. + +**Ejemplo Programático** + +`Nazgul` es la clase multiton. + +```java +public enum NazgulName { + + KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA +} + +public final class Nazgul { + + private static final Map nazguls; + + private final NazgulName name; + + static { + nazguls = new ConcurrentHashMap<>(); + nazguls.put(NazgulName.KHAMUL, new Nazgul(NazgulName.KHAMUL)); + nazguls.put(NazgulName.MURAZOR, new Nazgul(NazgulName.MURAZOR)); + nazguls.put(NazgulName.DWAR, new Nazgul(NazgulName.DWAR)); + nazguls.put(NazgulName.JI_INDUR, new Nazgul(NazgulName.JI_INDUR)); + nazguls.put(NazgulName.AKHORAHIL, new Nazgul(NazgulName.AKHORAHIL)); + nazguls.put(NazgulName.HOARMURATH, new Nazgul(NazgulName.HOARMURATH)); + nazguls.put(NazgulName.ADUNAPHEL, new Nazgul(NazgulName.ADUNAPHEL)); + nazguls.put(NazgulName.REN, new Nazgul(NazgulName.REN)); + nazguls.put(NazgulName.UVATHA, new Nazgul(NazgulName.UVATHA)); + } + + private Nazgul(NazgulName name) { + this.name = name; + } + + public static Nazgul getInstance(NazgulName name) { + return nazguls.get(name); + } + + public NazgulName getName() { + return name; + } +} +``` + +Y así es como accedemos a las instancias `Nazgul`. + +```java +// eagerly initialized multiton +LOGGER.info("Printing out eagerly initialized multiton contents"); +LOGGER.info("KHAMUL={}", Nazgul.getInstance(NazgulName.KHAMUL)); +LOGGER.info("MURAZOR={}", Nazgul.getInstance(NazgulName.MURAZOR)); +LOGGER.info("DWAR={}", Nazgul.getInstance(NazgulName.DWAR)); +LOGGER.info("JI_INDUR={}", Nazgul.getInstance(NazgulName.JI_INDUR)); +LOGGER.info("AKHORAHIL={}", Nazgul.getInstance(NazgulName.AKHORAHIL)); +LOGGER.info("HOARMURATH={}", Nazgul.getInstance(NazgulName.HOARMURATH)); +LOGGER.info("ADUNAPHEL={}", Nazgul.getInstance(NazgulName.ADUNAPHEL)); +LOGGER.info("REN={}", Nazgul.getInstance(NazgulName.REN)); +LOGGER.info("UVATHA={}", Nazgul.getInstance(NazgulName.UVATHA)); + +// enum multiton +LOGGER.info("Printing out enum-based multiton contents"); +LOGGER.info("KHAMUL={}", NazgulEnum.KHAMUL); +LOGGER.info("MURAZOR={}", NazgulEnum.MURAZOR); +LOGGER.info("DWAR={}", NazgulEnum.DWAR); +LOGGER.info("JI_INDUR={}", NazgulEnum.JI_INDUR); +LOGGER.info("AKHORAHIL={}", NazgulEnum.AKHORAHIL); +LOGGER.info("HOARMURATH={}", NazgulEnum.HOARMURATH); +LOGGER.info("ADUNAPHEL={}", NazgulEnum.ADUNAPHEL); +LOGGER.info("REN={}", NazgulEnum.REN); +LOGGER.info("UVATHA={}", NazgulEnum.UVATHA); +``` + +Salida del programa: + +``` +20:35:07.413 [main] INFO com.iluwatar.multiton.App - Printing out eagerly initialized multiton contents +20:35:07.417 [main] INFO com.iluwatar.multiton.App - KHAMUL=com.iluwatar.multiton.Nazgul@48cf768c +20:35:07.419 [main] INFO com.iluwatar.multiton.App - MURAZOR=com.iluwatar.multiton.Nazgul@7960847b +20:35:07.419 [main] INFO com.iluwatar.multiton.App - DWAR=com.iluwatar.multiton.Nazgul@6a6824be +20:35:07.419 [main] INFO com.iluwatar.multiton.App - JI_INDUR=com.iluwatar.multiton.Nazgul@5c8da962 +20:35:07.419 [main] INFO com.iluwatar.multiton.App - AKHORAHIL=com.iluwatar.multiton.Nazgul@512ddf17 +20:35:07.419 [main] INFO com.iluwatar.multiton.App - HOARMURATH=com.iluwatar.multiton.Nazgul@2c13da15 +20:35:07.419 [main] INFO com.iluwatar.multiton.App - ADUNAPHEL=com.iluwatar.multiton.Nazgul@77556fd +20:35:07.419 [main] INFO com.iluwatar.multiton.App - REN=com.iluwatar.multiton.Nazgul@368239c8 +20:35:07.420 [main] INFO com.iluwatar.multiton.App - UVATHA=com.iluwatar.multiton.Nazgul@9e89d68 +20:35:07.420 [main] INFO com.iluwatar.multiton.App - Printing out enum-based multiton contents +20:35:07.420 [main] INFO com.iluwatar.multiton.App - KHAMUL=KHAMUL +20:35:07.420 [main] INFO com.iluwatar.multiton.App - MURAZOR=MURAZOR +20:35:07.420 [main] INFO com.iluwatar.multiton.App - DWAR=DWAR +20:35:07.420 [main] INFO com.iluwatar.multiton.App - JI_INDUR=JI_INDUR +20:35:07.421 [main] INFO com.iluwatar.multiton.App - AKHORAHIL=AKHORAHIL +20:35:07.421 [main] INFO com.iluwatar.multiton.App - HOARMURATH=HOARMURATH +20:35:07.421 [main] INFO com.iluwatar.multiton.App - ADUNAPHEL=ADUNAPHEL +20:35:07.421 [main] INFO com.iluwatar.multiton.App - REN=REN +20:35:07.421 [main] INFO com.iluwatar.multiton.App - UVATHA=UVATHA +``` + +## Diagrama de Clases + +![alt text](./etc/multiton.png "Multiton") + +## Aplicabilidad + +Utilice el patrón Multiton cuando + +* Debe haber un número determinado de instancias de una clase, y deben ser accesibles a los clientes desde un punto de + acceso conocido. diff --git a/localization/es/multiton/etc/multiton.png b/localization/es/multiton/etc/multiton.png new file mode 100644 index 000000000000..91106463d2b2 Binary files /dev/null and b/localization/es/multiton/etc/multiton.png differ diff --git a/localization/es/null-object/README.md b/localization/es/null-object/README.md new file mode 100644 index 000000000000..10196f8763a3 --- /dev/null +++ b/localization/es/null-object/README.md @@ -0,0 +1,175 @@ +--- +title: Null Object +shortTitle: Null Object +category: Behavioral +language: es +tag: + - Extensibility +--- + +## Propósito + +En la mayoría de los lenguajes orientados a objetos, como Java o C#, las referencias pueden ser nulas. Estas referencias deben comprobarse para asegurarse de que no son nulas antes de invocar cualquier método, porque normalmente los métodos no pueden invocarse sobre referencias nulas. En lugar de utilizar una referencia nula para indicar la ausencia de un objeto (por ejemplo, un cliente inexistente), se utiliza un objeto que implementa la interfaz esperada, pero cuyo cuerpo de método está vacío. La ventaja de este enfoque sobre una implementación por defecto es que un objeto nulo es muy predecible y no tiene efectos secundarios: no hace nada. + +## Explicación + +Ejemplo del mundo real + +> Estamos construyendo un árbol binario a partir de nodos. Hay nodos normales y nodos "vacíos". Recorrer el árbol normalmente no debería causar errores, por lo que utilizamos el patrón de objetos nulos cuando es necesario. + +En palabras sencillas + +> El patrón de objetos nulos maneja los objetos "vacíos" con elegancia. + +Wikipedia dice + +> En programación informática orientada a objetos, un objeto nulo es un objeto sin valor referenciado o con un comportamiento neutro ("nulo") definido. El patrón de diseño de objetos nulos describe los usos de tales objetos y su comportamiento (o la falta del mismo). + +**Ejemplo programático** + +Esta es la definición de la interfaz `Node`. + +```java +public interface Node { + + String getName(); + + int getTreeSize(); + + Node getLeft(); + + Node getRight(); + + void walk(); +} +``` + +Tenemos dos implementaciones de `Node`. La implementación normal `NodeImpl` y `NullNode` para nodos vacíos. + +```java +@Slf4j +public class NodeImpl implements Node { + + private final String name; + private final Node left; + private final Node right; + + /** + * Constructor. + */ + public NodeImpl(String name, Node left, Node right) { + this.name = name; + this.left = left; + this.right = right; + } + + @Override + public int getTreeSize() { + return 1 + left.getTreeSize() + right.getTreeSize(); + } + + @Override + public Node getLeft() { + return left; + } + + @Override + public Node getRight() { + return right; + } + + @Override + public String getName() { + return name; + } + + @Override + public void walk() { + LOGGER.info(name); + if (left.getTreeSize() > 0) { + left.walk(); + } + if (right.getTreeSize() > 0) { + right.walk(); + } + } +} + +public final class NullNode implements Node { + + private static final NullNode instance = new NullNode(); + + private NullNode() { + } + + public static NullNode getInstance() { + return instance; + } + + @Override + public int getTreeSize() { + return 0; + } + + @Override + public Node getLeft() { + return null; + } + + @Override + public Node getRight() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public void walk() { + // Do nothing + } +} +``` + +Entonces podemos construir y recorrer el árbol binario sin errores de la siguiente manera. + +```java + var root = new NodeImpl("1", + new NodeImpl("11", + new NodeImpl("111", NullNode.getInstance(), NullNode.getInstance()), + NullNode.getInstance() + ), + new NodeImpl("12", + NullNode.getInstance(), + new NodeImpl("122", NullNode.getInstance(), NullNode.getInstance()) + ) + ); + root.walk(); +``` + +Salida del programa: + +``` +1 +11 +111 +12 +122 +``` + +## Diagrama de clases + +![alt text](./etc/null-object.png "Null Object") + +## Aplicabilidad + +Utilice el patrón Objeto nulo cuando + +* Desea evitar la comprobación explícita de nulos y mantener el algoritmo elegante y fácil de leer. + +## Créditos + +* [Pattern Languages of Program Design 3](https://www.amazon.com/gp/product/0201310112/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201310112&linkCode=as2&tag=javadesignpat-20&linkId=7372ffb8a4e39a3bb10f199b89aef921) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/null-object/etc/null-object.png b/localization/es/null-object/etc/null-object.png new file mode 100644 index 000000000000..cb0a5409c735 Binary files /dev/null and b/localization/es/null-object/etc/null-object.png differ diff --git a/localization/es/object-mother/README.md b/localization/es/object-mother/README.md new file mode 100644 index 000000000000..f9bdf69f998b --- /dev/null +++ b/localization/es/object-mother/README.md @@ -0,0 +1,115 @@ +--- +title: Object Mother +shortTitle: Object Mother +category: Creational +language: es +tag: + - Instantiation +--- + +## Propósito + +Se utiliza para definir una fábrica de contenido inmutable con interfaces de constructor y fábrica separadas. + +## Diagrama de Clases + +![alt text](./etc/object-mother.png "Object Mother") + +## Aplicabilidad + +Utilice el patrón Object Mother cuando + +* Quieres objetos consistentes a lo largo de varias pruebas +* Desea reducir el código para la creación de objetos en las pruebas. +* Cada prueba debe ejecutarse con datos nuevos + +## Comprender el patrón madre objeto (Object Mother) + +### Escenario real + +Imagine que está desarrollando una aplicación Java para una agencia de viajes. En su sistema, hay diferentes tipos de +viajeros, como turistas, viajeros de negocios y agentes de viajes, cada uno con atributos y comportamientos específicos. +Para realizar pruebas exhaustivas, necesita crear y manipular estos objetos viajeros en varios contextos. El patrón +Object Mother puede ayudarle a generar objetos viajeros coherentes y predefinidos para las pruebas, garantizando que +estas se basen en datos conocidos y fiables. + +### En palabras simples + +El Patrón Objeto Madre (Object Mother) es un patrón de diseño utilizado en Java para simplificar la creación de objetos +con configuraciones específicas, especialmente para pruebas. En lugar de construir manualmente objetos con propiedades +variables para cada caso de prueba, se crea una clase o método "Objeto Madre" dedicado que produce estos objetos con +configuraciones predefinidas. De este modo se garantiza la coherencia y previsibilidad de los datos de las pruebas, lo +que las hace más fiables y fáciles de gestionar. + +### Visión general desde el punto de vista de las pruebas + +El patrón Objeto Madre (Object Mother) es un patrón de diseño relacionado con las pruebas que ayuda a mantener un +entorno de pruebas coherente y fiable. Permite definir y crear objetos con atributos específicos, lo que ayuda a +garantizar que las pruebas produzcan resultados coherentes y predecibles, lo que facilita la detección de problemas y el +mantenimiento del conjunto de pruebas. + +### Uso práctico en pruebas + +En las pruebas de software, sobre todo en las unitarias, el Patrón Objeto Madre tiene un valor incalculable. Ayuda a +asegurar que sus pruebas no están influenciadas por datos impredecibles, haciendo así sus pruebas más robustas y +repetibles. Al centralizar la creación de objetos de prueba en un Objeto Madre, puede adaptar fácilmente sus datos de +prueba a diferentes escenarios. + +### Ejemplo en Java + +He aquí un ejemplo ilustrativo en Java del Patrón Objeto Madre (Object Mother) en el contexto de una aplicación de +agencia de viajes: + +```java +class Traveler { + private String name; + private int age; + private boolean isBusinessTraveler; + + // Constructor and methods for the traveler + // ... + + // Getter and setter methods + // ... +} + +class TravelerMother { + public static Traveler createTourist(String name, int age) { + Traveler traveler = new Traveler(); + traveler.setName(name); + traveler.setAge(age); + traveler.setBusinessTraveler(false); + return traveler; + } + + public static Traveler createBusinessTraveler(String name, int age) { + Traveler traveler = new Traveler(); + traveler.setName(name); + traveler.setAge(age); + traveler.setBusinessTraveler(true); + return traveler; + } +} + +public class TravelAgency { + public static void main(String[] args) { + // Using the Object Mother to create traveler objects for testing + Traveler tourist = TravelerMother.createTourist("Alice", 28); + Traveler businessTraveler = TravelerMother.createBusinessTraveler("Bob", 35); + + // Now you have consistent traveler objects for testing. + } +} + +``` + +En este ejemplo, TravelerMother es la clase Object Mother responsable de generar objetos Traveler predefinidos con +configuraciones específicas. Este enfoque garantiza que disponga de datos de prueba coherentes para diversos escenarios +en una aplicación de agencia de viajes, lo que mejora la fiabilidad y la eficacia de sus esfuerzos de prueba. + +## Credits + +* [Answer by David Brown](http://stackoverflow.com/questions/923319/what-is-an-objectmother) a la pregunta de + stackoverflow: [What is an ObjectMother?](http://stackoverflow.com/questions/923319/what-is-an-objectmother) +* [c2wiki - Object Mother](http://c2.com/cgi/wiki?ObjectMother) +* [Nat Pryce - Test Data Builders: an alternative to the Object Mother pattern](http://www.natpryce.com/articles/000714.html) diff --git a/localization/es/object-mother/etc/object-mother.png b/localization/es/object-mother/etc/object-mother.png new file mode 100644 index 000000000000..807343d9f9e4 Binary files /dev/null and b/localization/es/object-mother/etc/object-mother.png differ diff --git a/localization/es/object-pool/README.md b/localization/es/object-pool/README.md new file mode 100644 index 000000000000..dfcb02b1b6af --- /dev/null +++ b/localization/es/object-pool/README.md @@ -0,0 +1,148 @@ +--- +title: Object Pool +shortTitle: Object Pool +category: Creational +language: es +tag: + - Game programming + - Performance +--- + +## También conocido como + +Resource Pool + +## Propósito + +Cuando los objetos son costosos de crear y solo se necesitan durante cortos períodos de tiempo, es ventajoso utilizar el +patrón de Object Pool. El Object Pool proporciona una caché para objetos instanciados, rastreando cuáles están en uso y +cuáles están disponibles. + +## Explicación + +Ejemplo del mundo real + +> En nuestro juego de guerra necesitamos usar olifantes, bestias masivas y míticas, pero el problema es que son +> extremadamente costosos de crear. La solución es crear un grupo de ellos, rastrear cuáles están en uso y, en lugar de +> desecharlos, reutilizar las instancias. + +En palabras simples + +> Object Pool gestiona un conjunto de instancias en lugar de crearlas y destruirlas bajo demanda. + +Wikipedia dice + +> El patrón de object pool es un patrón de diseño de creación de software que utiliza un conjunto de objetos +> inicializados listos para usar, un "pool", en lugar de asignar y destruirlos a demanda. + +**Ejemplo Programático** + +Aquí está la clase básica olifante `Oliphaunt`. Estos gigantes son muy caros de crear. + +```java +public class Oliphaunt { + + private static final AtomicInteger counter = new AtomicInteger(0); + + private final int id; + + public Oliphaunt() { + id = counter.incrementAndGet(); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public int getId() { + return id; + } + + @Override + public String toString() { + return String.format("Oliphaunt id=%d", id); + } +} +``` + +A continuación se muestra el `ObjectPool` y más concretamente el `OliphauntPool`. + +```java +public abstract class ObjectPool { + + private final Set available = new HashSet<>(); + private final Set inUse = new HashSet<>(); + + protected abstract T create(); + + public synchronized T checkOut() { + if (available.isEmpty()) { + available.add(create()); + } + var instance = available.iterator().next(); + available.remove(instance); + inUse.add(instance); + return instance; + } + + public synchronized void checkIn(T instance) { + inUse.remove(instance); + available.add(instance); + } + + @Override + public synchronized String toString() { + return String.format("Pool available=%d inUse=%d", available.size(), inUse.size()); + } +} + +public class OliphauntPool extends ObjectPool { + + @Override + protected Oliphaunt create() { + return new Oliphaunt(); + } +} +``` + +Por último, así es como utilizamos la piscina. + +```java + var pool = new OliphauntPool(); + var oliphaunt1 = pool.checkOut(); + var oliphaunt2 = pool.checkOut(); + var oliphaunt3 = pool.checkOut(); + pool.checkIn(oliphaunt1); + pool.checkIn(oliphaunt2); + var oliphaunt4 = pool.checkOut(); + var oliphaunt5 = pool.checkOut(); +``` + +Salida del programa: + +``` +Pool available=0 inUse=0 +Checked out Oliphaunt id=1 +Pool available=0 inUse=1 +Checked out Oliphaunt id=2 +Checked out Oliphaunt id=3 +Pool available=0 inUse=3 +Checking in Oliphaunt id=1 +Checking in Oliphaunt id=2 +Pool available=2 inUse=1 +Checked out Oliphaunt id=2 +Checked out Oliphaunt id=1 +Pool available=0 inUse=3 +``` + +## Diagrama de Clases + +![alt text](./etc/object-pool.png "Object Pool") + +## Aplicabilidad + +Utilice el patrón Object Pool cuando + +* Los objetos son caros de crear (coste de asignación). +* Necesitas un gran número de objetos de vida corta (fragmentación de memoria). diff --git a/localization/es/object-pool/etc/object-pool.png b/localization/es/object-pool/etc/object-pool.png new file mode 100644 index 000000000000..b8ede36c5a47 Binary files /dev/null and b/localization/es/object-pool/etc/object-pool.png differ diff --git a/localization/es/observer/README.md b/localization/es/observer/README.md new file mode 100644 index 000000000000..2c4d09c213f6 --- /dev/null +++ b/localization/es/observer/README.md @@ -0,0 +1,156 @@ +--- +title: Observer +shortTitle: Observer +category: Behavioral +language: en +tag: + - Gang Of Four + - Reactive +--- + +## También conocido como + +Dependents, Publish-Subscribe + +## Propósito + +Defina una dependencia de uno a muchos entre objetos para que cuando un objeto cambie de estado, todos sus dependientes sean notificados y actualizados automáticamente. + +## Explicación + +Ejemplo real + +> En una tierra muy lejana viven las razas de los hobbits y los orcos. Ambos viven principalmente al aire libre, por lo que siguen de cerca los cambios meteorológicos. Se podría decir que observan constantemente el tiempo. + +En palabras simples + +> Se registran como observadores para recibir los cambios de estado del objeto. + +Wikipedia dice + +> El patrón observador es un patrón de diseño de software en el que un objeto, llamado sujeto, mantiene una lista de sus dependientes, llamados observadores, y les notifica automáticamente cualquier cambio de estado, normalmente llamando a uno de sus métodos. + +**Ejemplo programático** + +Presentemos primero la interfaz `WeatherObserver` y nuestras razas, `Orcs` y `Hobbits`. + +```java +public interface WeatherObserver { + + void update(WeatherType currentWeather); +} + +@Slf4j +public class Orcs implements WeatherObserver { + + @Override + public void update(WeatherType currentWeather) { + LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now"); + } +} + +@Slf4j +public class Hobbits implements WeatherObserver { + + @Override + public void update(WeatherType currentWeather) { + switch (currentWeather) { + LOGGER.info("The hobbits are facing " + currentWeather.getDescription() + " weather now"); + } + } +} +``` + +Luego está el clima `Weather`, que cambia constantemente. + +```java +@Slf4j +public class Weather { + + private WeatherType currentWeather; + private final List observers; + + public Weather() { + observers = new ArrayList<>(); + currentWeather = WeatherType.SUNNY; + } + + public void addObserver(WeatherObserver obs) { + observers.add(obs); + } + + public void removeObserver(WeatherObserver obs) { + observers.remove(obs); + } + + /** + * Makes time pass for weather. + */ + public void timePasses() { + var enumValues = WeatherType.values(); + currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; + LOGGER.info("The weather changed to {}.", currentWeather); + notifyObservers(); + } + + private void notifyObservers() { + for (var obs : observers) { + obs.update(currentWeather); + } + } +} +``` +Aquí está el ejemplo completo en acción. + +```java + var weather = new Weather(); + weather.addObserver(new Orcs()); + weather.addObserver(new Hobbits()); + weather.timePasses(); + weather.timePasses(); + weather.timePasses(); + weather.timePasses(); +``` + +Salida del programa: + +``` +The weather changed to rainy. +The orcs are facing rainy weather now +The hobbits are facing rainy weather now +The weather changed to windy. +The orcs are facing windy weather now +The hobbits are facing windy weather now +The weather changed to cold. +The orcs are facing cold weather now +The hobbits are facing cold weather now +The weather changed to sunny. +The orcs are facing sunny weather now +The hobbits are facing sunny weather now +``` + +## Diagrama de clases + +![alt text](./etc/observer.png "Observer") + +## Aplicabilidad + +Utilice el patrón Observador en cualquiera de las siguientes situaciones: + +* Cuando una abstracción tiene dos aspectos, uno dependiente del otro. Encapsular estos aspectos en objetos separados te permite variarlos y reutilizarlos independientemente. +* Cuando un cambio en un objeto requiere cambiar otros, y no sabes cuántos objetos necesitan ser cambiados. +* Cuando un objeto debe ser capaz de notificar a otros objetos sin hacer suposiciones sobre quiénes son estos objetos. En otras palabras, no quieres que estos objetos estén estrechamente acoplados. + +## Usos conocidos + +* [java.util.Observer](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html) +* [java.util.EventListener](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html) +* [javax.servlet.http.HttpSessionBindingListener](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html) +* [RxJava](https://github.com/ReactiveX/RxJava) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Java Generics and Collections](https://www.amazon.com/gp/product/0596527756/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596527756&linkCode=as2&tag=javadesignpat-20&linkId=246e5e2c26fe1c3ada6a70b15afcb195) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/observer/etc/observer.png b/localization/es/observer/etc/observer.png new file mode 100644 index 000000000000..f2ab0edfeb21 Binary files /dev/null and b/localization/es/observer/etc/observer.png differ diff --git a/localization/es/page-controller/README.md b/localization/es/page-controller/README.md new file mode 100644 index 000000000000..1464c3dfc9ba --- /dev/null +++ b/localization/es/page-controller/README.md @@ -0,0 +1,163 @@ +--- +title: Page Controller +shortTitle: Page Controller +category: Structural +language: es +tags: +- Decoupling +--- + +## Nombre / clasificación + +Page Controller + +## Propósito + +Se trata de un enfoque de una página que conduce a un archivo lógico que gestiona acciones o peticiones en un sitio web. + +## Explicación + +Un ejemplo real + +> En un sitio web de compras, hay una página de registro para dar de alta un perfil de usuario. Una vez finalizado el registro, la página de registro se redirigirá a una página de usuario para mostrar la información registrada del usuario. + +En pocas palabras + +> El controlador de página gestiona las peticiones HTTP y los datos en una página específica usando la idea MVC. +> La idea es que una página contiene un controlador que maneja el modelo y la vista. + +**Ejemplo programático** + +Aquí está el controlador Signup cuando un usuario registra su información para un sitio web. + +```java +@Slf4j +@Controller +@Component +public class SignupController { + SignupView view = new SignupView(); + /** + * Signup Controller can handle http request and decide which model and view use. + */ + SignupController() { + } + + /** + * Handle http GET request. + */ + @GetMapping("/signup") + public String getSignup() { + return view.display(); + } + + /** + * Handle http POST request and access model and view. + */ + @PostMapping("/signup") + public String create(SignupModel form, RedirectAttributes redirectAttributes) { + LOGGER.info(form.getName()); + LOGGER.info(form.getEmail()); + redirectAttributes.addAttribute("name", form.getName()); + redirectAttributes.addAttribute("email", form.getEmail()); + redirectAttributes.addFlashAttribute("userInfo", form); + return view.redirect(form); + } +} +``` +Aquí está el modelo y la vista de Signup que son manejados por el controlador de Signup. + +```java +@Component +@Getter +@Setter +public class SignupModel { + private String name; + private String email; + private String password; + + public SignupModel() { + } +} +``` + +```java +@Slf4j +public class SignupView { + public SignupView() { + } + + public String display() { + LOGGER.info("display signup front page"); + return "/signup"; + } + + /** + * redirect to user page. + */ + public String redirect(SignupModel form) { + LOGGER.info("Redirect to user page with " + "name " + form.getName() + " email " + form.getEmail()); + return "redirect:/user"; + } +} +``` + +Este es el Controlador de Usuario para manejar la petición Get en una página de usuario. + +```java +@Slf4j +@Controller +public class UserController { + UserView view = new UserView(); + + public UserController() {} + + /** + * Handle http GET request and access view and model. + */ + @GetMapping("/user") + public String getUserPath(SignupModel form, Model model) { + model.addAttribute("name", form.getName()); + model.addAttribute("email", form.getEmail()); + return view.display(form); + } +} +``` + +Aquí están el Modelo de Usuario y la Vista que son manejados por el controlador de Usuario. + +```java +@Getter +@Setter +public class UserModel { + private String name; + private String email; + + public UserModel() {} +} +``` + +```java +@Slf4j +public class UserView { + /** + * displaying command to generate html. + * @param user model content. + */ + public String display(SignupModel user) { + LOGGER.info("display user html" + " name " + user.getName() + " email " + user.getEmail()); + return "/user"; + } +} +``` + +## Diagrama de clases +![alt text](./etc/page-controller.urm.png) + +## Aplicabilidad +Utilice el patrón Page Controller cuando +- implementas un sitio donde la mayor parte de la lógica del controlador es simple +- implementa un sitio en el que determinadas acciones se gestionan con una página de servidor concreta + +## Créditos +- [Page Controller](https://www.martinfowler.com/eaaCatalog/pageController.html) +- [Pattern of Enterprise Application Architecture](https://www.martinfowler.com/books/eaa.html) \ No newline at end of file diff --git a/localization/es/page-controller/etc/page-controller.urm.png b/localization/es/page-controller/etc/page-controller.urm.png new file mode 100644 index 000000000000..d46bb018755b Binary files /dev/null and b/localization/es/page-controller/etc/page-controller.urm.png differ diff --git a/localization/es/page-object/README.md b/localization/es/page-object/README.md new file mode 100644 index 000000000000..d945bfb1f3bf --- /dev/null +++ b/localization/es/page-object/README.md @@ -0,0 +1,87 @@ +--- +title: Page Object +shortTitle: Page Object +category: Structural +language: es +tag: +- Decoupling +--- + +# Patrón de objetos de página en Java + +## Ejemplo del mundo real + +Considera un escenario de automatización web donde necesitas interactuar con una página web usando un framework de pruebas como Selenium. El patrón Page Object puede aplicarse para modelar cada página web como una clase Java. Cada clase encapsula la estructura y el comportamiento de la página web correspondiente, facilitando la gestión y actualización del código de automatización. + +## Intención + +Page Object encapsula la interfaz de usuario, ocultando el widget de interfaz de usuario subyacente de una aplicación (normalmente una aplicación web) y proporcionando una API específica de la aplicación para permitir la manipulación de los componentes de interfaz de usuario necesarios para las pruebas. De este modo, permite a la clase de prueba centrarse en la lógica de la prueba. + +## En pocas palabras + +El patrón Page Object en Java es un patrón de diseño utilizado en la automatización de pruebas para representar páginas web como clases Java. Cada clase corresponde a una página web específica y contiene métodos para interactuar con los elementos de esa página. Este patrón mejora el mantenimiento y la legibilidad del código en las pruebas automatizadas. + +## Wikipedia dice + +Aunque no hay una entrada específica en Wikipedia para el patrón Page Object, se utiliza ampliamente en las pruebas de software, en particular en el contexto de la automatización de la interfaz de usuario. El patrón Page Object ayuda a abstraer los detalles de una página web, proporcionando una forma más limpia y fácil de mantener para interactuar con elementos web en pruebas automatizadas. + +## Ejemplo programático + +Vamos a crear un ejemplo programático simple del patrón Page Object para una página de login utilizando Selenium en Java: + +```java +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; + +public class LoginPage { + private final WebDriver driver; + + // Web elements on the login page + private final By usernameInput = By.id("username"); + private final By passwordInput = By.id("password"); + private final By loginButton = By.id("login-button"); + + public LoginPage(WebDriver driver) { + this.driver = driver; + } + + // Methods to interact with the login page + + public void enterUsername(String username) { + WebElement usernameElement = driver.findElement(usernameInput); + usernameElement.sendKeys(username); + } + + public void enterPassword(String password) { + WebElement passwordElement = driver.findElement(passwordInput); + passwordElement.sendKeys(password); + } + + public void clickLoginButton() { + WebElement loginButtonElement = driver.findElement(loginButton); + loginButtonElement.click(); + } + + // Other methods specific to the login page if needed +} +``` + +En este ejemplo, la clase `LoginPage` representa la página de login de una aplicación web. Encapsula los elementos web de la página y proporciona métodos para interactuar con esos elementos. La instancia real de Selenium WebDriver se pasa al constructor, permitiendo a los métodos realizar acciones en la página web. + +Este objeto de página se puede utilizar en scripts de prueba para interactuar con la página de inicio de sesión sin exponer los detalles de la estructura de la página en el código de prueba, lo que favorece el mantenimiento y la reutilización. + +## Aplicabilidad + +Utilice el patrón Page Object cuando + +* Estás escribiendo pruebas automatizadas para tu aplicación web y quieres separar la manipulación de la interfaz de usuario necesaria para las pruebas de la lógica de prueba real. +* Haga sus pruebas menos frágiles, y más legibles y robustas. + +## Otro ejemplo con diagrama de clases +![alt text](./etc/page-object.png "Page Object") + +## Créditos + +* [Martin Fowler - PageObject](http://martinfowler.com/bliki/PageObject.html) +* [Selenium - Page Objects](https://github.com/SeleniumHQ/selenium/wiki/PageObjects) diff --git a/localization/es/page-object/etc/page-object.png b/localization/es/page-object/etc/page-object.png new file mode 100644 index 000000000000..4240b438efbb Binary files /dev/null and b/localization/es/page-object/etc/page-object.png differ diff --git a/localization/es/parameter-object/README.md b/localization/es/parameter-object/README.md new file mode 100644 index 000000000000..73092e90b705 --- /dev/null +++ b/localization/es/parameter-object/README.md @@ -0,0 +1,125 @@ +--- +title: Parameter Object +shortTitle: Parameter Object +category: Behavioral +language: es +tag: + - Extensibility +--- + +## Propósito + +La sintaxis del lenguaje Java no permite declarar un método con un valor predefinido para un parámetro. Probablemente la mejor opción para conseguir parámetros de método predefinidos en Java es utilizar la sobrecarga de métodos. La sobrecarga de métodos permite declarar varios métodos con el mismo nombre pero con un número diferente de parámetros. Pero el principal problema con la sobrecarga de métodos como solución para los valores de los parámetros por defecto se revela cuando un método acepta múltiples parámetros. Crear un método sobrecargado para cada posible combinación de parámetros puede resultar engorroso. Para solucionar este problema, se utiliza el patrón Objeto Parámetro. + +## Explicación + +El Objeto Parámetro (Parameter Object) es simplemente un objeto envoltorio para todos los parámetros de un método. No es más que un POJO normal. La ventaja del Objeto Parámetro sobre una lista regular de parámetros de método es el hecho de que los campos de clase pueden tener valores por defecto. Una vez creada la clase envoltorio para la lista de parámetros del método, se crea también una clase constructora correspondiente. Normalmente es una clase estática interna. El paso final es utilizar el constructor para construir un nuevo objeto parámetro. Para aquellos parámetros que se omitan, se utilizarán sus valores por defecto. + + +**Ejemplo programático** + +Aquí está la simple clase `SearchService` donde se utiliza la sobrecarga de métodos para los valores por defecto aquí. Para utilizar la sobrecarga de métodos, el número de argumentos o el tipo de argumento tiene que ser diferente. + +```java +public class SearchService { + //Method Overloading example. SortOrder is defaulted in this method + public String search(String type, String sortBy) { + return getQuerySummary(type, sortBy, SortOrder.DESC); + } + + /* Method Overloading example. SortBy is defaulted in this method. Note that the type has to be + different here to overload the method */ + public String search(String type, SortOrder sortOrder) { + return getQuerySummary(type, "price", sortOrder); + } + + private String getQuerySummary(String type, String sortBy, SortOrder sortOrder) { + return "Requesting shoes of type \"" + type + "\" sorted by \"" + sortBy + "\" in \"" + + sortOrder.getValue() + "ending\" order..."; + } +} + +``` + +A continuación presentamos el `SearchService` con `ParameterObject` creado con el patrón Builder. + +```java +public class SearchService { + + /* Parameter Object example. Default values are abstracted into the Parameter Object + at the time of Object creation */ + public String search(ParameterObject parameterObject) { + return getQuerySummary(parameterObject.getType(), parameterObject.getSortBy(), + parameterObject.getSortOrder()); + } + + private String getQuerySummary(String type, String sortBy, SortOrder sortOrder) { + return "Requesting shoes of type \"" + type + "\" sorted by \"" + sortBy + "\" in \"" + + sortOrder.getValue() + "ending\" order..."; + } +} + +public class ParameterObject { + public static final String DEFAULT_SORT_BY = "price"; + public static final SortOrder DEFAULT_SORT_ORDER = SortOrder.ASC; + + private String type; + private String sortBy = DEFAULT_SORT_BY; + private SortOrder sortOrder = DEFAULT_SORT_ORDER; + + private ParameterObject(Builder builder) { + type = builder.type; + sortBy = builder.sortBy != null && !builder.sortBy.isBlank() ? builder.sortBy : sortBy; + sortOrder = builder.sortOrder != null ? builder.sortOrder : sortOrder; + } + + public static Builder newBuilder() { + return new Builder(); + } + + //Getters and Setters... + + public static final class Builder { + + private String type; + private String sortBy; + private SortOrder sortOrder; + + private Builder() { + } + + public Builder withType(String type) { + this.type = type; + return this; + } + + public Builder sortBy(String sortBy) { + this.sortBy = sortBy; + return this; + } + + public Builder sortOrder(SortOrder sortOrder) { + this.sortOrder = sortOrder; + return this; + } + + public ParameterObject build() { + return new ParameterObject(this); + } + } +} + + +``` + +## Diagrama de clases + +![alt text](./etc/parameter-object.png "Parameter Object") + +## Aplicabilidad + +Este patrón nos muestra la forma de tener parámetros por defecto para un método en Java ya que el lenguaje no tiene la característica de parámetros por defecto fuera de la caja. + +## Créditos + +- [Does Java have default parameters?](http://dolszewski.com/java/java-default-parameters) diff --git a/localization/es/parameter-object/etc/parameter-object.png b/localization/es/parameter-object/etc/parameter-object.png new file mode 100644 index 000000000000..661c3488ac49 Binary files /dev/null and b/localization/es/parameter-object/etc/parameter-object.png differ diff --git a/localization/es/partial-response/README.md b/localization/es/partial-response/README.md new file mode 100644 index 000000000000..78cd9ce6d400 --- /dev/null +++ b/localization/es/partial-response/README.md @@ -0,0 +1,24 @@ +--- +title: Partial Response +shortTitle: Partial Response +category: Behavioral +language: es +tag: + - Decoupling +--- + +## Propósito +Enviar una respuesta parcial del servidor al cliente en función de sus necesidades. El cliente especificará los campos que necesita al servidor, en lugar de servir todos los detalles del recurso. + +## Diagrama de clases +![alt text](./etc/partial-response.urm.png "Partial Response") + +## Aplicabilidad +Utilice el patrón de respuesta parcial cuando + +* El cliente sólo necesita un subconjunto de datos del recurso. +* Para evitar demasiada transferencia de datos por cable + +## Créditos + +* [Common Design Patterns](https://cloud.google.com/apis/design/design_patterns) diff --git a/localization/es/partial-response/etc/partial-response.urm.png b/localization/es/partial-response/etc/partial-response.urm.png new file mode 100644 index 000000000000..17dbd5f1b60d Binary files /dev/null and b/localization/es/partial-response/etc/partial-response.urm.png differ diff --git a/localization/es/pipeline/README.md b/localization/es/pipeline/README.md new file mode 100644 index 000000000000..f50a9ab1c5c9 --- /dev/null +++ b/localization/es/pipeline/README.md @@ -0,0 +1,111 @@ +--- +title: Pipeline +shortTitle: Pipeline +category: Behavioral +language: es +tag: + - Decoupling +--- + +## Propósito + +Permite procesar los datos en una serie de etapas, introduciendo una entrada inicial y pasando la salida procesada para que la utilicen las etapas siguientes. + +## Explicación + +El patrón Pipeline utiliza etapas ordenadas para procesar una secuencia de valores de entrada. Cada tarea implementada está representada por una etapa de la tubería. Puede pensar en las canalizaciones como algo similar a las líneas de ensamblaje de una fábrica, donde cada elemento de la línea de ensamblaje se construye por etapas. El artículo parcialmente ensamblado pasa de una etapa de ensamblaje a otra. Las salidas de la cadena de montaje se producen en el mismo orden que las entradas. + +Ejemplo del mundo real + +> Supongamos que queremos pasar una cadena a una serie de etapas de filtrado y convertirla como una matriz char en la última etapa. + +En palabras sencillas + +> El patrón pipeline es una cadena de montaje donde los resultados parciales pasan de una etapa a otra. + +Wikipedia dice + +> En ingeniería de software, un pipeline consiste en una cadena de elementos de procesamiento (procesos, hilos, coroutines, funciones, etc.), dispuestos de forma que la salida de cada elemento es la entrada del siguiente; el nombre es por analogía a un pipeline físico. + +**Ejemplo programático** + +Las etapas de nuestro pipeline se llaman `Handler`s. +```java +interface Handler { + O process(I input); +} +``` + +En nuestro ejemplo de procesamiento de cadenas tenemos 3 `Handler`s concretos diferentes. + +```java +class RemoveAlphabetsHandler implements Handler { + ... +} + +class RemoveDigitsHandler implements Handler { + ... +} + +class ConvertToCharArrayHandler implements Handler { + ... +} +``` + +Aquí está el `Pipeline` que recogerá y ejecutará los handlers uno a uno. + +```java +class Pipeline { + + private final Handler currentHandler; + + Pipeline(Handler currentHandler) { + this.currentHandler = currentHandler; + } + + Pipeline addHandler(Handler newHandler) { + return new Pipeline<>(input -> newHandler.process(currentHandler.process(input))); + } + + O execute(I input) { + return currentHandler.process(input); + } +} +``` + +Y aquí está la `Pipeline` en acción procesando la cadena. + +```java + var filters = new Pipeline<>(new RemoveAlphabetsHandler()) + .addHandler(new RemoveDigitsHandler()) + .addHandler(new ConvertToCharArrayHandler()); + filters.execute("GoYankees123!"); +``` + +## Diagrama de clases + +![alt text](./etc/pipeline.urm.png "Diagrama de clases del patrón Pipeline ") + +## Aplicabilidad + +Utilice el patrón Pipeline cuando desee + +* Ejecutar etapas individuales que produzcan un valor final. +* Añadir legibilidad a secuencias complejas de operaciones proporcionando un constructor fluido como interfaz. +* Mejorar la comprobabilidad del código, ya que las etapas probablemente harán una sola cosa, cumpliendo con el [Principio de Responsabilidad Única (SRP)](https://java-design-patterns.com/principles/#single-responsibility-principle) + +## Usos conocidos + +* [java.util.Stream](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html) +* [Maven Build Lifecycle](http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html) +* [Functional Java](https://github.com/functionaljava/functionaljava) + +## Patrones relacionados + +* [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/) + +## Créditos + +* [The Pipeline Pattern — for fun and profit](https://medium.com/@aaronweatherall/the-pipeline-pattern-for-fun-and-profit-9b5f43a98130) +* [The Pipeline design pattern (in Java)](https://medium.com/@deepakbapat/the-pipeline-design-pattern-in-java-831d9ce2fe21) +* [Pipelines | Microsoft Docs](https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ff963548(v=pandp.10)) diff --git a/localization/es/pipeline/etc/pipeline.urm.png b/localization/es/pipeline/etc/pipeline.urm.png new file mode 100644 index 000000000000..4110f1624665 Binary files /dev/null and b/localization/es/pipeline/etc/pipeline.urm.png differ diff --git a/localization/es/poison-pill/README.md b/localization/es/poison-pill/README.md new file mode 100644 index 000000000000..6a71cb6705d1 --- /dev/null +++ b/localization/es/poison-pill/README.md @@ -0,0 +1,217 @@ +--- +title: Poison Pill +shortTitle: Poison Pill +category: Behavioral +language: es +tag: + - Cloud distributed + - Reactive +--- + +## Propósito + +La píldora venenosa es un elemento de datos predefinido conocido que permite proporcionar un cierre graceful para un proceso de consumo distribuido independiente. + +## Explicación + +Ejemplo del mundo real + +> Pensemos en una cola de mensajes con un productor y un consumidor. El productor sigue introduciendo nuevos mensajes en la cola y el consumidor sigue leyéndolos. Finalmente, cuando llega el momento de cerrar la cola, el productor envía el mensaje de píldora venenosa. + +En pocas palabras + +> Poison Pill es una estructura de mensaje conocida que pone fin al intercambio de mensajes. + +**Ejemplo programático** + +Definamos primero la estructura del mensaje. Hay una interfaz `Message` y una implementación `SimpleMessage`. + +```java +public interface Message { + + ... + + enum Headers { + DATE, SENDER + } + + void addHeader(Headers header, String value); + + String getHeader(Headers header); + + Map getHeaders(); + + void setBody(String body); + + String getBody(); +} + +public class SimpleMessage implements Message { + + private final Map headers = new HashMap<>(); + private String body; + + @Override + public void addHeader(Headers header, String value) { + headers.put(header, value); + } + + @Override + public String getHeader(Headers header) { + return headers.get(header); + } + + @Override + public Map getHeaders() { + return Collections.unmodifiableMap(headers); + } + + @Override + public void setBody(String body) { + this.body = body; + } + + @Override + public String getBody() { + return body; + } +} +``` + +Para pasar mensajes utilizamos colas de mensajes. Aquí definimos los tipos relacionados con la cola de mensajes: `MqPublishPoint`, `MqSubscribePoint` y `MessageQueue`. `SimpleMessageQueue` implementa todas estas interfaces. + +```java +public interface MqPublishPoint { + + void put(Message msg) throws InterruptedException; +} + +public interface MqSubscribePoint { + + Message take() throws InterruptedException; +} + +public interface MessageQueue extends MqPublishPoint, MqSubscribePoint { +} + +public class SimpleMessageQueue implements MessageQueue { + + private final BlockingQueue queue; + + public SimpleMessageQueue(int bound) { + queue = new ArrayBlockingQueue<>(bound); + } + + @Override + public void put(Message msg) throws InterruptedException { + queue.put(msg); + } + + @Override + public Message take() throws InterruptedException { + return queue.take(); + } +} +``` + +A continuación necesitamos los mensajes `Producer` y `Consumer`. Internamente utilizan las colas de mensajes de arriba. Es importante notar que cuando `Producer` se detiene, envía la píldora venenosa para informar a `Consumer` que la mensajería ha terminado. + +```java +public class Producer { + + ... + + public void send(String body) { + if (isStopped) { + throw new IllegalStateException(String.format( + "Producer %s was stopped and fail to deliver requested message [%s].", body, name)); + } + var msg = new SimpleMessage(); + msg.addHeader(Headers.DATE, new Date().toString()); + msg.addHeader(Headers.SENDER, name); + msg.setBody(body); + + try { + queue.put(msg); + } catch (InterruptedException e) { + // allow thread to exit + LOGGER.error("Exception caught.", e); + } + } + + public void stop() { + isStopped = true; + try { + queue.put(Message.POISON_PILL); + } catch (InterruptedException e) { + // allow thread to exit + LOGGER.error("Exception caught.", e); + } + } +} + +public class Consumer { + + ... + + public void consume() { + while (true) { + try { + var msg = queue.take(); + if (Message.POISON_PILL.equals(msg)) { + LOGGER.info("Consumer {} receive request to terminate.", name); + break; + } + var sender = msg.getHeader(Headers.SENDER); + var body = msg.getBody(); + LOGGER.info("Message [{}] from [{}] received by [{}]", body, sender, name); + } catch (InterruptedException e) { + // allow thread to exit + LOGGER.error("Exception caught.", e); + return; + } + } + } +} +``` + +Por último, estamos listos para presentar todo el ejemplo en acción. + +```java + var queue = new SimpleMessageQueue(10000); + + final var producer = new Producer("PRODUCER_1", queue); + final var consumer = new Consumer("CONSUMER_1", queue); + + new Thread(consumer::consume).start(); + + new Thread(() -> { + producer.send("hand shake"); + producer.send("some very important information"); + producer.send("bye!"); + producer.stop(); + }).start(); +``` + +Salida del programa: + +``` +Message [hand shake] from [PRODUCER_1] received by [CONSUMER_1] +Message [some very important information] from [PRODUCER_1] received by [CONSUMER_1] +Message [bye!] from [PRODUCER_1] received by [CONSUMER_1] +Consumer CONSUMER_1 receive request to terminate. +``` + +## Diagrama de clases + +![alt text](./etc/poison-pill.png "Poison Pill") + +## Aplicabilidad + +Utiliza la expresión "píldora envenenada" (Poison pill) cuando: + +* Hay una necesidad de enviar una señal de un hilo/proceso a otro para terminar. + +## Ejemplos del mundo real + +* [akka.actor.PoisonPill](http://doc.akka.io/docs/akka/2.1.4/java/untyped-actors.html) diff --git a/localization/es/poison-pill/etc/poison-pill.png b/localization/es/poison-pill/etc/poison-pill.png new file mode 100644 index 000000000000..bfca5848e082 Binary files /dev/null and b/localization/es/poison-pill/etc/poison-pill.png differ diff --git a/localization/es/presentation-model/README.md b/localization/es/presentation-model/README.md new file mode 100644 index 000000000000..fd88a8662f06 --- /dev/null +++ b/localization/es/presentation-model/README.md @@ -0,0 +1,193 @@ +--- +title: Presentation Model +shortTitle: Presentation Model +category: Behavioral +language: es +tag: + - Decoupling +--- + +## También conocido como +Application Model + +## Propósito +El modelo de presentación extrae el estado y el comportamiento de la vista a una clase modelo que forma parte de la presentación. + +## Explicación + +Ejemplo del mundo real + +> Cuando necesitamos escribir un programa con GUI, no es necesario que pongamos todo el comportamiento de la presentación en la clase view. Porque será más difícil de probar. Así que podemos utilizar Presentation Model Pattern para separar el comportamiento y la vista. La vista solo necesita cargar los datos y estados de otra clase y mostrar estos datos en la pantalla de acuerdo a los estados. + +En palabras simples + +> un patrón que divide la presentación y el control. + +Ejemplo de código + +La clase `view` es la GUI de los álbumes. Los métodos `saveToPMod` y `loadFromPMod` se utilizan para lograr la sincronización. + +```java +public class View { + /** + * the model that controls this view. + */ + private final PresentationModel model; + + private TextField txtTitle; + private TextField txtArtist; + private JCheckBox chkClassical; + private TextField txtComposer; + private JList albumList; + private JButton apply; + private JButton cancel; + + public View() { + model = new PresentationModel(PresentationModel.albumDataSet()); + } + + /** + * save the data to PresentationModel. + */ + public void saveToPMod() { + LOGGER.info("Save data to PresentationModel"); + model.setArtist(txtArtist.getText()); + model.setTitle(txtTitle.getText()); + model.setIsClassical(chkClassical.isSelected()); + model.setComposer(txtComposer.getText()); + } + + /** + * load the data from PresentationModel. + */ + public void loadFromPMod() { + LOGGER.info("Load data from PresentationModel"); + txtArtist.setText(model.getArtist()); + txtTitle.setText(model.getTitle()); + chkClassical.setSelected(model.getIsClassical()); + txtComposer.setEditable(model.getIsClassical()); + txtComposer.setText(model.getComposer()); + } + + public void createView() { + // the detail of GUI information like size, listenser and so on. + } +} +``` + +La clase `Album` sirve para almacenar información de un álbum. + +```java +public class Album { + + private String title; + private String artist; + private boolean isClassical; + /** + * only when the album is classical, + * composer can have content. + */ + private String composer; +} + +``` + +La clase `DisplatedAlbums` almacena la información de todos los álbumes que se mostrarán en la GUI. + +```java +public class DisplayedAlbums { + private final List albums; + + public DisplayedAlbums() { + this.albums = new ArrayList<>(); + } + + public void addAlbums(final String title, + final String artist, final boolean isClassical, + final String composer) { + if (isClassical) { + this.albums.add(new Album(title, artist, true, composer)); + } else { + this.albums.add(new Album(title, artist, false, "")); + } + } +} +``` + +Clase `PresentationMod` se utiliza para controlar toda la acción de GUI. + +```java +public class PresentationModel { + private final DisplayedAlbums data; + + private int selectedAlbumNumber; + private Album selectedAlbum; + + public PresentationModel(final DisplayedAlbums dataOfAlbums) { + this.data = dataOfAlbums; + this.selectedAlbumNumber = 1; + this.selectedAlbum = this.data.getAlbums().get(0); + } + + /** + * Changes the value of selectedAlbumNumber. + * + * @param albumNumber the number of album which is shown on the view. + */ + public void setSelectedAlbumNumber(final int albumNumber) { + LOGGER.info("Change select number from {} to {}", + this.selectedAlbumNumber, albumNumber); + this.selectedAlbumNumber = albumNumber; + this.selectedAlbum = data.getAlbums().get(this.selectedAlbumNumber - 1); + } + + public String getTitle() { + return selectedAlbum.getTitle(); + } + // other get methods are like this, which are used to get information of selected album. + + public void setTitle(final String value) { + LOGGER.info("Change album title from {} to {}", + selectedAlbum.getTitle(), value); + selectedAlbum.setTitle(value); + } + // other set methods are like this, which are used to get information of selected album. + + /** + * Gets a list of albums. + * + * @return the names of all the albums. + */ + public String[] getAlbumList() { + var result = new String[data.getAlbums().size()]; + for (var i = 0; i < result.length; i++) { + result[i] = data.getAlbums().get(i).getTitle(); + } + return result; + } +} +``` + +Podemos ejecutar la clase `App` para iniciar esta demo. la casilla de verificación es el álbum clásico; el primer campo de texto es el nombre del artista del álbum; el segundo es el nombre del título del álbum; el último es el nombre del compositor: + +![](./etc/result.png) + + +## Diagrama de clases +![](./etc/presentation-model.urm.png "presentation model") + +## Aplicabilidad +Utilice el patrón de modelo de presentación cuando + +* Probar una presentación a través de una ventana GUI es a menudo incómodo, y en algunos casos imposible. +* No determine qué GUI se utilizará. + +## Patrones relacionados + +- [Supervising Controller](https://martinfowler.com/eaaDev/SupervisingPresenter.html) +- [Passive View](https://martinfowler.com/eaaDev/PassiveScreen.html) + +## Créditos + +* [Presentation Model Patterns](https://martinfowler.com/eaaDev/PresentationModel.html) + diff --git a/localization/es/presentation-model/etc/presentation-model.urm.png b/localization/es/presentation-model/etc/presentation-model.urm.png new file mode 100644 index 000000000000..46690641cb82 Binary files /dev/null and b/localization/es/presentation-model/etc/presentation-model.urm.png differ diff --git a/localization/es/presentation-model/etc/result.png b/localization/es/presentation-model/etc/result.png new file mode 100644 index 000000000000..6b104968f302 Binary files /dev/null and b/localization/es/presentation-model/etc/result.png differ diff --git a/localization/es/priority-queue/README.md b/localization/es/priority-queue/README.md new file mode 100644 index 000000000000..125f2a0abece --- /dev/null +++ b/localization/es/priority-queue/README.md @@ -0,0 +1,196 @@ +--- +title: Priority Queue Pattern +shortTitle: Priority Queue Pattern +category: Behavioral +language: es +tag: + - Decoupling + - Cloud distributed +--- + +## Propósito +Priorizar las peticiones enviadas a los servicios de forma que las peticiones con mayor prioridad se reciban y procesen más rápidamente que las de menor prioridad. Este patrón es útil en aplicaciones que ofrecen diferentes garantías de nivel de servicio a clientes individuales. + +## Explicación + +Las aplicaciones pueden delegar tareas específicas en otros servicios; por ejemplo, para realizar procesamientos en segundo plano o para integrarse con otras aplicaciones o servicios. En la nube, se suele utilizar una cola de mensajes para delegar tareas al procesamiento en segundo plano. En muchos casos, el orden en que un servicio recibe las solicitudes no es importante. Sin embargo, en algunos casos puede ser necesario priorizar peticiones específicas. Estas peticiones deben ser procesadas antes que otras de menor prioridad que puedan haber sido enviadas previamente por la aplicación. + +Ejemplo real + +> Imagine un servicio de procesamiento de vídeo con clientes gratuitos y premium. Las solicitudes procedentes de los clientes premium de pago deben tener prioridad sobre las demás. + +En pocas palabras + +> La cola prioritaria permite procesar primero los mensajes de alta prioridad, independientemente del tamaño de la cola o de la antigüedad del mensaje. + +Wikipedia dice + +> En informática, una cola prioritaria es un tipo de datos abstracto similar a una cola normal o a una estructura de datos de pila en la que cada elemento tiene además una "prioridad" asociada. En una cola de prioridad, un elemento con prioridad alta se sirve antes que un elemento con prioridad baja. + +**Ejemplo programático** + +Si observamos el ejemplo anterior de procesamiento de vídeo, veamos primero la estructura `Message`. + +```java +public class Message implements Comparable { + + private final String message; + private final int priority; // define message priority in queue + + public Message(String message, int priority) { + this.message = message; + this.priority = priority; + } + + @Override + public int compareTo(Message o) { + return priority - o.priority; + } + ... +} +``` + +Aquí está `PriorityMessageQueue` que se encarga de almacenar los mensajes y servirlos en orden de prioridad. + +```java +public class PriorityMessageQueue { + + ... + + public T remove() { + if (isEmpty()) { + return null; + } + + final var root = queue[0]; + queue[0] = queue[size - 1]; + size--; + maxHeapifyDown(); + return root; + } + + public void add(T t) { + ensureCapacity(); + queue[size] = t; + size++; + maxHeapifyUp(); + } + + ... +} +``` + +El `QueueManager` tiene una `PriorityMessageQueue` y facilita la publicación de mensajes `publishMessage` y la recepción de mensajes `receiveMessage`. + +```java +public class QueueManager { + + private final PriorityMessageQueue messagePriorityMessageQueue; + + public QueueManager(int initialCapacity) { + messagePriorityMessageQueue = new PriorityMessageQueue<>(new Message[initialCapacity]); + } + + public void publishMessage(Message message) { + messagePriorityMessageQueue.add(message); + } + + public Message receiveMessage() { + if (messagePriorityMessageQueue.isEmpty()) { + return null; + } + return messagePriorityMessageQueue.remove(); + } +} +``` + +El `Worker` sondea constantemente el `QueueManager` en busca del mensaje de mayor prioridad y lo procesa. + +```java +@Slf4j +public class Worker { + + private final QueueManager queueManager; + + public Worker(QueueManager queueManager) { + this.queueManager = queueManager; + } + + public void run() throws Exception { + while (true) { + var message = queueManager.receiveMessage(); + if (message == null) { + LOGGER.info("No Message ... waiting"); + Thread.sleep(200); + } else { + processMessage(message); + } + } + } + + private void processMessage(Message message) { + LOGGER.info(message.toString()); + } +} +``` + +Aquí está el ejemplo completo de cómo creamos una instancia de `QueueManager` y procesamos mensajes usando `Worker`. + +```java + var queueManager = new QueueManager(100); + + for (var i = 0; i < 100; i++) { + queueManager.publishMessage(new Message("Low Message Priority", 0)); + } + + for (var i = 0; i < 100; i++) { + queueManager.publishMessage(new Message("High Message Priority", 1)); + } + + var worker = new Worker(queueManager); + worker.run(); +``` + +Salida del programa: + +``` +Message{message='High Message Priority', priority=1} +Message{message='High Message Priority', priority=1} +Message{message='High Message Priority', priority=1} +Message{message='High Message Priority', priority=1} +Message{message='High Message Priority', priority=1} +Message{message='High Message Priority', priority=1} +Message{message='High Message Priority', priority=1} +Message{message='High Message Priority', priority=1} +Message{message='High Message Priority', priority=1} +Message{message='High Message Priority', priority=1} +Message{message='Low Message Priority', priority=0} +Message{message='Low Message Priority', priority=0} +Message{message='Low Message Priority', priority=0} +Message{message='Low Message Priority', priority=0} +Message{message='Low Message Priority', priority=0} +Message{message='Low Message Priority', priority=0} +Message{message='Low Message Priority', priority=0} +Message{message='Low Message Priority', priority=0} +Message{message='Low Message Priority', priority=0} +Message{message='Low Message Priority', priority=0} +No Message ... waiting +No Message ... waiting +No Message ... waiting +``` + + +## Diagrama de clases + +![alt text](./etc/priority-queue.urm.png "Priority Queue pattern class diagram") + +## Aplicabilidad + +Utilice el patrón de Cola Prioritaria cuando: + +* El sistema debe manejar múltiples tareas que pueden tener diferentes prioridades. +* Diferentes usuarios o inquilinos deben ser atendidos con diferente prioridad. + +## Créditos + +* [Priority Queue pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/priority-queue) diff --git a/localization/es/priority-queue/etc/priority-queue.urm.png b/localization/es/priority-queue/etc/priority-queue.urm.png new file mode 100644 index 000000000000..e0b4295a5986 Binary files /dev/null and b/localization/es/priority-queue/etc/priority-queue.urm.png differ diff --git a/localization/es/property/README.md b/localization/es/property/README.md new file mode 100644 index 000000000000..9c0d461d5599 --- /dev/null +++ b/localization/es/property/README.md @@ -0,0 +1,145 @@ +--- +title: Property +shortTitle: Property +category: Creational +language: es +tag: + - Instantiation +--- + +## Propósito + +Crear jerarquía de objetos y nuevos objetos utilizando objetos existentes como padres. + +## Explicación + +Ejemplo del mundo real + +> En la mística tierra de _"Elandria"_, los aventureros pueden aprovechar el poder de las reliquias antiguas para +> personalizar sus habilidades. Cada reliquia representa una propiedad o habilidad única. A medida que los aventureros +> exploran, descubren e integran nuevas reliquias, mejorando dinámicamente sus habilidades en función de las reliquias +> que +> poseen. + +> Considera un software moderno utilizado en el diseño y personalización de teléfonos inteligentes. Los diseñadores +> pueden elegir entre una variedad de componentes como el tipo de procesador, las especificaciones de la cámara, la +> capacidad de la batería y más. Cada componente representa una propiedad del teléfono inteligente. A medida que la +> tecnología evoluciona y se disponen de nuevos componentes, los diseñadores pueden agregar o reemplazar propiedades sin +> problemas para crear una configuración de teléfono inteligente única sin redefinir la estructura de diseño central. + +En palabras simples + +> Define y gestiona un conjunto dinámico de propiedades para un objeto, permitiendo la personalización sin alterar su +> estructura. + +**Ejemplo Programático** + +```java +import java.util.HashMap; +import java.util.Map; + +// Enumeration for possible properties or statistics a character can have +enum Stats { + AGILITY, ATTACK_POWER, ARMOR, INTELLECT, SPIRIT, FURY, RAGE; +} + +// Enumeration for different types or classes of characters +enum Type { + WARRIOR, MAGE, ROGUE; +} + +// Interface defining prototype operations on a character +interface Prototype { + Integer get(Stats stat); + boolean has(Stats stat); + void set(Stats stat, Integer value); + void remove(Stats stat); +} + +// Implementation of the Character class +class Character implements Prototype { + private String name; + private Type type; + private Map properties = new HashMap<>(); + + public Character() {} + + public Character(Type type, Prototype prototype) { + this.type = type; + for (Stats stat : Stats.values()) { + if (prototype.has(stat)) { + this.set(stat, prototype.get(stat)); + } + } + } + + public Character(String name, Type type) { + this.name = name; + this.type = type; + } + + @Override + public Integer get(Stats stat) { + return properties.get(stat); + } + + @Override + public boolean has(Stats stat) { + return properties.containsKey(stat); + } + + @Override + public void set(Stats stat, Integer value) { + properties.put(stat, value); + } + + @Override + public void remove(Stats stat) { + properties.remove(stat); + } + + @Override + public String toString() { + return "Character{name='" + name + "', type=" + type + ", properties=" + properties + '}'; + } +} + +// Main class to demonstrate the pattern +public class PropertyPatternDemo { + public static void main(String[] args) { + // Create a prototype character + Character prototypeWarrior = new Character("Proto Warrior", Type.WARRIOR); + prototypeWarrior.set(Stats.ATTACK_POWER, 10); + prototypeWarrior.set(Stats.ARMOR, 15); + + // Create a new character using the prototype + Character newWarrior = new Character(Type.WARRIOR, prototypeWarrior); + newWarrior.set(Stats.AGILITY, 5); + + System.out.println(prototypeWarrior); + System.out.println(newWarrior); + } +} +``` + +Salida del programa: + +``` +Character{name='Proto Warrior', type=WARRIOR, properties={ARMOR=15, ATTACK_POWER=10}} +Character{name='null', type=WARRIOR, properties={ARMOR=15, AGILITY=5, ATTACK_POWER=10}} +``` + +## Diagrama de Clases + +![alt text](./etc/property.png "Property") + +## Aplicabilidad + +Utilice el patrón Property cuando + +* Cuando desee tener objetos con un conjunto dinámico de campos y herencia de prototipos + +## Ejemplo del mundo real + +* [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) prototipo + herencia diff --git a/localization/es/property/etc/property.png b/localization/es/property/etc/property.png new file mode 100644 index 000000000000..98c0cbe3720c Binary files /dev/null and b/localization/es/property/etc/property.png differ diff --git a/localization/es/prototype/README.md b/localization/es/prototype/README.md new file mode 100644 index 000000000000..c5d11d290601 --- /dev/null +++ b/localization/es/prototype/README.md @@ -0,0 +1,181 @@ +--- +title: Prototype +shortTitle: Prototype +category: Creational +language: es +tag: + - Gang Of Four + - Instantiation +--- + +## Propósito + +Especificar los tipos de objetos a crear utilizando una instancia prototípica, y crear nuevos objetos copiando este +prototipo + +## Explicación + +Primero, debe notarse que el patrón Prototype no se utiliza para obtener beneficios de rendimiento. Solo se utiliza para +crear nuevos objetos a partir de instancias prototipo. + +Ejemplo del mundo real + +> ¿Recuerdas a Dolly? ¡La oveja que fue clonada! No entremos en detalles, pero el punto clave aquí es que todo se trata +> de clonación. + +En palabras simples + +> Crea un objeto basado en un objeto existente a través de la clonación. + +Wikipedia dice + +> El patrón de prototipo es un patrón de diseño de creación en el desarrollo de software. Se utiliza cuando el tipo de +> objetos a crear está determinado por una instancia prototípica, que se clona para producir nuevos objetos. + +En resumen, te permite crear una copia de un objeto existente y modificarla según tus necesidades, en lugar de pasar por +el problema de crear un objeto desde cero y configurarlo. + +**Ejemplo Programático** + +En Java, se recomienda implementar el patrón prototipo de la siguiente manera. En primer lugar, cree una interfaz con un +método para clonar objetos. En este ejemplo, la interfaz `Prototype` logra esto con su método `copy`. + +```java +public abstract class Prototype implements Cloneable { + @SneakyThrows + public T copy() { + return (T) super.clone(); + } +} +``` + +Nuestro ejemplo contiene una jerarquía de diferentes criaturas. Por ejemplo, veamos las clases `Beast` y `OrcBeast`. + +```java +@EqualsAndHashCode(callSuper = false) +@NoArgsConstructor +public abstract class Beast extends Prototype { + + public Beast(Beast source) { + } + +} + +@EqualsAndHashCode(callSuper = false) +@RequiredArgsConstructor +public class OrcBeast extends Beast { + + private final String weapon; + + public OrcBeast(OrcBeast orcBeast) { + super(orcBeast); + this.weapon = orcBeast.weapon; + } + + @Override + public String toString() { + return "Orcish wolf attacks with " + weapon; + } + +} +``` + +No queremos entrar en demasiados detalles, pero el ejemplo completo contiene también las clases base `Mage` y `Warlord` +y hay implementaciones especializadas para los elfos además de para los orcos. + +Para aprovechar al máximo el patrón prototipo, creamos las clases `HeroFactory` y `HeroFactoryImpl` para producir +diferentes tipos de criaturas a partir de prototipos. + +```java +public interface HeroFactory { + + Mage createMage(); + Warlord createWarlord(); + Beast createBeast(); +} + +@RequiredArgsConstructor +public class HeroFactoryImpl implements HeroFactory { + + private final Mage mage; + private final Warlord warlord; + private final Beast beast; + + public Mage createMage() { + return mage.copy(); + } + + public Warlord createWarlord() { + return warlord.copy(); + } + + public Beast createBeast() { + return beast.copy(); + } +} +``` + +Ahora, somos capaces de mostrar el patrón prototipo completo en acción produciendo nuevas criaturas clonando instancias +existentes. + +```java + var factory = new HeroFactoryImpl( + new ElfMage("cooking"), + new ElfWarlord("cleaning"), + new ElfBeast("protecting") + ); + var mage = factory.createMage(); + var warlord = factory.createWarlord(); + var beast = factory.createBeast(); + LOGGER.info(mage.toString()); + LOGGER.info(warlord.toString()); + LOGGER.info(beast.toString()); + + factory = new HeroFactoryImpl( + new OrcMage("axe"), + new OrcWarlord("sword"), + new OrcBeast("laser") + ); + mage = factory.createMage(); + warlord = factory.createWarlord(); + beast = factory.createBeast(); + LOGGER.info(mage.toString()); + LOGGER.info(warlord.toString()); + LOGGER.info(beast.toString()); +``` + +Esta es la salida de la consola al ejecutar el ejemplo. + +``` +Elven mage helps in cooking +Elven warlord helps in cleaning +Elven eagle helps in protecting +Orcish mage attacks with axe +Orcish warlord attacks with sword +Orcish wolf attacks with laser +``` + +## Diagrama de Clases + +![alt text](./etc/prototype.urm.png "Prototype pattern class diagram") + +## Aplicabilidad + +Utilice el patrón Prototipo cuando un sistema deba ser independiente de cómo se crean, componen, representan sus +productos y + +* Cuando las clases a instanciar se especifican en tiempo de ejecución, por ejemplo, mediante carga dinámica. +* Para evitar construir una jerarquía de clases de fábricas paralela a la jerarquía de clases de productos. +* Cuando las instancias de una clase solo pueden tener una de unas pocas combinaciones diferentes de estado. Puede ser + más conveniente instalar un número correspondiente de prototipos y clonarlos en lugar de instanciar la clase + manualmente, cada vez con el estado apropiado. +* Cuando la creación de objetos es costosa en comparación con la clonación. + +## Usos conocidos + +* [java.lang.Object#clone()](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/es/prototype/etc/prototype.urm.png b/localization/es/prototype/etc/prototype.urm.png new file mode 100644 index 000000000000..b23c6d1cfb85 Binary files /dev/null and b/localization/es/prototype/etc/prototype.urm.png differ diff --git a/localization/es/proxy/README.md b/localization/es/proxy/README.md new file mode 100644 index 000000000000..1435a3732432 --- /dev/null +++ b/localization/es/proxy/README.md @@ -0,0 +1,162 @@ +--- +title: Proxy +shortTitle: Proxy +category: Structural +language: es +tag: + - Gang Of Four + - Decoupling +--- + +## También conocido como + +Surrogate + +## Propósito + +Proporcionar un sustituto o marcador de posición de otro objeto para controlar el acceso al mismo. + +## Explicación + +Ejemplo real + +> Imagina una torre donde los magos locales van a estudiar sus hechizos. A la torre de marfil sólo se puede acceder a través de un proxy que asegura que sólo los tres primeros magos pueden entrar. Aquí el proxy representa la funcionalidad de la torre y le añade control de acceso. + +En palabras sencillas + +> Usando el patrón proxy, una clase representa la funcionalidad de otra clase. + +Wikipedia dice + +> Un proxy, en su forma más general, es una clase que funciona como interfaz de otra cosa. Un proxy es una envoltura o un objeto agente que está siendo llamado por el cliente para acceder al objeto real de servicio detrás de las escenas. El uso del proxy puede ser simplemente el reenvío al objeto real, o puede proporcionar lógica adicional. En el proxy se puede proporcionar funcionalidad adicional, por ejemplo, almacenamiento en caché cuando las operaciones en el objeto real consumen muchos recursos, o comprobación de condiciones previas antes de invocar operaciones en el objeto real. + +**Ejemplo programático** + +Tomando el ejemplo anterior de nuestra torre de asistentes. En primer lugar tenemos la interfaz `WizardTower` y la clase `IvoryTower`. + +```java +public interface WizardTower { + + void enter(Wizard wizard); +} + +@Slf4j +public class IvoryTower implements WizardTower { + + public void enter(Wizard wizard) { + LOGGER.info("{} enters the tower.", wizard); + } + +} +``` + +A continuación, una simple clase `Wizard`. + +```java +public class Wizard { + + private final String name; + + public Wizard(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} +``` + +Luego tenemos el `WizardTowerProxy` para añadir control de acceso a `WizardTower`. + +```java +@Slf4j +public class WizardTowerProxy implements WizardTower { + + private static final int NUM_WIZARDS_ALLOWED = 3; + + private int numWizards; + + private final WizardTower tower; + + public WizardTowerProxy(WizardTower tower) { + this.tower = tower; + } + + @Override + public void enter(Wizard wizard) { + if (numWizards < NUM_WIZARDS_ALLOWED) { + tower.enter(wizard); + numWizards++; + } else { + LOGGER.info("{} is not allowed to enter!", wizard); + } + } +} +``` + +Y aquí está el escenario de entrada a la torre. + +```java +var proxy = new WizardTowerProxy(new IvoryTower()); +proxy.enter(new Wizard("Red wizard")); +proxy.enter(new Wizard("White wizard")); +proxy.enter(new Wizard("Black wizard")); +proxy.enter(new Wizard("Green wizard")); +proxy.enter(new Wizard("Brown wizard")); +``` + +Salida del programa: + +``` +Red wizard enters the tower. +White wizard enters the tower. +Black wizard enters the tower. +Green wizard is not allowed to enter! +Brown wizard is not allowed to enter! +``` + +## Diagrama de clases + +![alt text](./etc/proxy.urm.png "Proxy pattern class diagram") + +## Aplicabilidad + +El proxy es aplicable siempre que se necesite una referencia a un objeto más versátil o sofisticada que un simple puntero. +que un simple puntero. He aquí varias situaciones comunes en las que el patrón Proxy es +aplicable. + +* Un proxy remoto proporciona un representante local para un objeto en un espacio de direcciones diferente. +* El proxy virtual crea objetos caros bajo demanda. +* Un proxy de protección controla el acceso al objeto original. Los proxies de protección son útiles cuando + objetos deben tener diferentes derechos de acceso. + +Típicamente, el patrón proxy se utiliza para + +* Controlar el acceso a otro objeto +* Inicialización perezosa +* Implementar el registro +* Facilitar la conexión de red +* Contar referencias a un objeto + +## Tutoriales + +* [Controlling Access With Proxy Pattern](http://java-design-patterns.com/blog/controlling-access-with-proxy-pattern/) + +## Usos conocidos + +* [java.lang.reflect.Proxy](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html) +* [Apache Commons Proxy](https://commons.apache.org/proper/commons-proxy/) +* Mocking frameworks [Mockito](https://site.mockito.org/), +[Powermock](https://powermock.github.io/), [EasyMock](https://easymock.org/) +* [UIAppearance](https://developer.apple.com/documentation/uikit/uiappearance) + +## Patrones relacionados + +* [Ambassador](https://java-design-patterns.com/patterns/ambassador/) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/es/proxy/etc/proxy.urm.png b/localization/es/proxy/etc/proxy.urm.png new file mode 100644 index 000000000000..a0c94fc7c717 Binary files /dev/null and b/localization/es/proxy/etc/proxy.urm.png differ diff --git a/localization/es/registry/README.md b/localization/es/registry/README.md new file mode 100644 index 000000000000..2af1eb143d1b --- /dev/null +++ b/localization/es/registry/README.md @@ -0,0 +1,93 @@ +--- +title: Registry +shortTitle: Registry +category: Creational +language: es +tag: + - Instantiation +--- + +## Propósito + +Almacena los objetos de una única clase y proporciona un punto de acceso global a los mismos. +Similar al patrón Multiton, la única diferencia es que en un registro no hay restricción en el número de objetos. + +## Explicación + +En pocas palabras + +> El registro es un objeto bien conocido que otros objetos pueden utilizar para encontrar objetos y servicios comunes. + +**Ejemplo Programático** +A continuación se muestra una clase `Cliente + +```java +public class Customer { + + private final String id; + private final String name; + + public Customer(String id, String name) { + this.id = id; + this.name = name; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + +} +``` + +Este registro de los objetos `Customer` es `CustomerRegistry`. + +```java +public final class CustomerRegistry { + + private static final CustomerRegistry instance = new CustomerRegistry(); + + public static CustomerRegistry getInstance() { + return instance; + } + + private final Map customerMap; + + private CustomerRegistry() { + customerMap = new ConcurrentHashMap<>(); + } + + public Customer addCustomer(Customer customer) { + return customerMap.put(customer.getId(), customer); + } + + public Customer getCustomer(String id) { + return customerMap.get(id); + } + +} +``` + +## Diagrama de Clases + +![Registry](./etc/registry.png "Registry pattern diagrama de clases") + +## Aplicabilidad + +Usar el patrón Registry cuando + +* El cliente quiere una referencia de algún objeto, por lo que el cliente puede buscar ese objeto en el registro del + objeto. + +## Consecuencias + +Un gran número de objetos voluminosos añadidos al registro daría lugar a un gran consumo de memoria, ya que los objetos +del registro no se recogen de la basura. + +## Créditos + +* https://www.martinfowler.com/eaaCatalog/registry.html +* https://wiki.c2.com/?RegistryPattern diff --git a/localization/es/registry/etc/registry.png b/localization/es/registry/etc/registry.png new file mode 100644 index 000000000000..6c1c5b986d72 Binary files /dev/null and b/localization/es/registry/etc/registry.png differ diff --git a/localization/es/retry/README.md b/localization/es/retry/README.md new file mode 100644 index 000000000000..ddb4b39d1175 --- /dev/null +++ b/localization/es/retry/README.md @@ -0,0 +1,121 @@ +--- +title: Retry +shortTitle: Retry +category: Behavioral +language: es +tag: + - Performance + - Cloud distributed +--- + +## Propósito + +Reintentar de forma transparente determinadas operaciones que implican la comunicación con recursos externos, en particular a través de la red, aislando el código de llamada de los detalles de implementación del reintento. + +## Explicación + +El patrón de reintento consiste en reintentar operaciones sobre recursos remotos a través de la red un número determinado de veces. Depende estrechamente de los requisitos empresariales y técnicos: ¿Cuánto tiempo permitirá la empresa que espere el usuario final hasta que finalice la operación? ¿Cuáles son las características de rendimiento del recurso remoto durante los picos de carga, así como de nuestra aplicación a medida que más hilos esperan la disponibilidad del recurso remoto? Entre los errores devueltos por el servicio remoto, ¿cuáles pueden ignorarse con seguridad para volver a intentarlo? ¿Es la operación [idempotent](https://en.wikipedia.org/wiki/Idempotence)? + +Otra preocupación es el impacto en el código de llamada al implementar el mecanismo de reintento. Idealmente, la mecánica de reintento debería ser completamente transparente para el código de llamada (la interfaz del servicio permanece inalterada). Existen dos enfoques generales para este problema: desde el punto de vista de la arquitectura empresarial (estratégico) y desde el punto de vista de la biblioteca compartida (táctico). + +Desde un punto de vista estratégico, esto se resolvería redirigiendo las peticiones a un sistema intermediario separado, tradicionalmente un [ESB](https://en.wikipedia.org/wiki/Enterprise_service_bus), pero más recientemente un [Service Mesh](https://medium.com/microservices-in-practice/service-mesh-for-microservices-2953109a3c9a). + +Desde un punto de vista táctico, esto se resolvería reutilizando bibliotecas compartidas como [Hystrix](https://github.com/Netflix/Hystrix) (nótese que Hystrix es una implementación completa del patrón [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/), del que el patrón Retry puede considerarse un subconjunto). Este es el tipo de solución que se muestra en el sencillo ejemplo que acompaña a este `README.md`. + +Ejemplo real + +> Nuestra aplicación utiliza un servicio que proporciona información sobre clientes. De vez en cuando el servicio parece fallar y puede devolver errores o a veces simplemente se desconecta. Para evitar estos problemas aplicamos el patrón retry. + +En palabras simples + +> El patrón de reintento reintenta de forma transparente las operaciones fallidas a través de la red. + +[Documentación de Microsoft](https://docs.microsoft.com/en-us/azure/architecture/patterns/retry) dice + +> Permite a una aplicación manejar fallos transitorios cuando intenta conectarse a un servicio o recurso de red, reintentando de forma transparente una operación fallida. Esto puede mejorar la estabilidad de la aplicación. + +**Ejemplo programático** + +En nuestra aplicación hipotética, tenemos una interfaz genérica para todas las operaciones sobre interfaces remotas. + +```java +public interface BusinessOperation { + T perform() throws BusinessException; +} +``` + +Y tenemos una implementación de esta interfaz que encuentra a nuestros clientes buscando en una base de datos. + +```java +public final class FindCustomer implements BusinessOperation { + @Override + public String perform() throws BusinessException { + ... + } +} +``` + +Nuestra implementación de `FindCustomer` puede configurarse para lanzar `BusinessException`s antes de devolver el ID del cliente, simulando así un servicio defectuoso que falla intermitentemente. Algunas excepciones, como la `CustomerNotFoundException`, se consideran recuperables tras un hipotético análisis porque la causa raíz del error proviene de "algún problema de bloqueo de la base de datos". Sin embargo, la `DatabaseNotAvailableException` se considera definitivamente un showtopper - la aplicación no debe intentar recuperarse de este error. + +Podemos modelar un escenario recuperable instanciando `FindCustomer` así: + +```java +final var op = new FindCustomer( + "12345", + new CustomerNotFoundException("not found"), + new CustomerNotFoundException("still not found"), + new CustomerNotFoundException("don't give up yet!") +); +``` + +En esta configuración, `FindCustomer` lanzará `CustomerNotFoundException` tres veces, tras lo cual devolverá sistemáticamente el ID del cliente (`12345`). + +En nuestro escenario hipotético, nuestros analistas indican que esta operación suele fallar entre 2 y 4 veces para una entrada determinada durante las horas punta, y que cada hilo de trabajo del subsistema de base de datos suele necesitar 50 ms para "recuperarse de un error". Aplicando estas políticas se obtendría algo así: + +```java +final var op = new Retry<>( + new FindCustomer( + "1235", + new CustomerNotFoundException("not found"), + new CustomerNotFoundException("still not found"), + new CustomerNotFoundException("don't give up yet!") + ), + 5, + 100, + e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) +); +``` + +Ejecutando `op` una vez se lanzarían automáticamente como máximo 5 intentos de reintento, con un retardo de 100 milisegundos entre intentos, ignorando cualquier `CustomerNotFoundException` lanzada durante el intento. En este escenario en particular, debido a la configuración de `FindCustomer`, habrá 1 intento inicial y 3 reintentos adicionales antes de devolver finalmente el resultado deseado `12345`. + +Si nuestra operación `FindCustomer` lanzara una fatal `DatabaseNotFoundException`, la cual se nos instruyó no ignorar, pero más importante aún, no instruimos a nuestro `Retry` ignorar, entonces la operación habría fallado inmediatamente al recibir el error, sin importar cuantos intentos quedaran. + +## Diagrama de clases + +![alt text](./etc/retry.png "Retry") + +## Aplicabilidad + +Siempre que una aplicación necesite comunicarse con un recurso externo, especialmente en un entorno de nube, y si los requisitos empresariales lo permiten. + +## Consecuencias + +**Pros:** + +* Resistencia +* Proporciona datos concretos sobre fallos externos + +**Desventajas** + +* Complejidad +* Mantenimiento de operaciones + +## Patrones relacionados + + +* [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/) + +## Créditos + +* [Retry pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/retry) +* [Cloud Design Patterns: Prescriptive Architecture Guidance for Cloud Applications](https://www.amazon.com/gp/product/1621140369/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=1621140369&linkId=3e3f686af5e60a7a453b48adb286797b) diff --git a/localization/es/retry/etc/retry.png b/localization/es/retry/etc/retry.png new file mode 100644 index 000000000000..3ef6d3800ee5 Binary files /dev/null and b/localization/es/retry/etc/retry.png differ diff --git a/localization/es/role-object/README.md b/localization/es/role-object/README.md new file mode 100644 index 000000000000..81f1f85a6410 --- /dev/null +++ b/localization/es/role-object/README.md @@ -0,0 +1,33 @@ +--- +title: Role Object +shortTitle: Role Object +category: Structural +language: es +tag: + - Extensibility +--- + +## También conocido como +Patrón Post, Patrón Extension Object + +## Propósito +Adaptar un objeto a las necesidades de diferentes clientes mediante objetos de rol adjuntos de forma transparente, cada uno de los cuales representa un papel +que el objeto debe desempeñar en el contexto de ese cliente. El objeto gestiona su conjunto de roles de forma dinámica. Al representar los roles como +objetos individuales, los distintos contextos se mantienen separados y se simplifica la configuración del sistema. + +## Diagrama de clases +![alt text](./etc/role-object.urm.png "Role Object pattern class diagram") + +## Aplicabilidad +Utiliza el patrón Objeto Rol, si: + +- Quieres manejar una abstracción clave en diferentes contextos y no quieres poner las interfaces específicas de contexto resultantes en la misma interfaz de clase. +- Quieres manejar los roles disponibles dinámicamente para que puedan ser adjuntados y removidos bajo demanda, es decir en tiempo de ejecución, en lugar de fijarlos estáticamente en tiempo de compilación. +- Quiere tratar las extensiones de forma transparente y necesita preservar la identidad lógica del objeto del conglomerado de objetos resultante. +- Desea mantener los pares rol/cliente independientes entre sí, de modo que los cambios en un rol no afecten a los clientes que no estén interesados en ese rol. + +## Créditos + +- [Hillside - Role object pattern](https://hillside.net/plop/plop97/Proceedings/riehle.pdf) +- [Role object](http://wiki.c2.com/?RoleObject) +- [Fowler - Dealing with roles](https://martinfowler.com/apsupp/roles.pdf) diff --git a/localization/es/role-object/etc/role-object.urm.png b/localization/es/role-object/etc/role-object.urm.png new file mode 100644 index 000000000000..65201c68aff4 Binary files /dev/null and b/localization/es/role-object/etc/role-object.urm.png differ diff --git a/localization/es/separated-interface/README.md b/localization/es/separated-interface/README.md new file mode 100644 index 000000000000..ca692c766da0 --- /dev/null +++ b/localization/es/separated-interface/README.md @@ -0,0 +1,134 @@ +--- +title: Separated Interface +shortTitle: Separated Interface +category: Structural +language: es +tag: + - Decoupling +--- + + +## Propósito + +Separe la definición de la interfaz y su implementación en paquetes diferentes. Esto permite al cliente desconozca por completo la implementación. + +## Explicación + +Ejemplo del mundo real + +> Se puede crear un generador de facturas con capacidad para utilizar diferentes calculadoras de impuestos que se pueden añadir en la factura en función del tipo de compra, región, etc. + +En pocas palabras + +> El patrón de interfaz separada anima a mantener las implementaciones de una interfaz desacopladas del cliente y su definición, para que el cliente no dependa de la implementación. + +Un código cliente puede abstraer algunas funcionalidades específicas a una interfaz, y definir la definición de +la interfaz como una SPI ([Service Programming Interface](https://en.wikipedia.org/wiki/Service_provider_interface) +es una API pensada y abierta para ser implementada o ampliada por terceros). Otro paquete puede +implementar esta definición de interfaz con una lógica concreta, que se inyectará en el código del cliente en tiempo de ejecución (con un tercero). +cliente en tiempo de ejecución (con una tercera clase, inyectando la implementación en el cliente) o en tiempo de compilación +(utilizando el patrón Plugin con algún archivo configurable). + +**Ejemplo programático** + +**Cliente** + +La clase `InvoiceGenerator` acepta el coste del producto y calcula el importe total a pagar, impuestos incluidos. +total a pagar, impuestos incluidos. + +```java +public class InvoiceGenerator { + + private final TaxCalculator taxCalculator; + + private final double amount; + + public InvoiceGenerator(double amount, TaxCalculator taxCalculator) { + this.amount = amount; + this.taxCalculator = taxCalculator; + } + + public double getAmountWithTax() { + return amount + taxCalculator.calculate(amount); + } + +} +``` + +La lógica de cálculo de impuestos se delega en la interfaz `TaxCalculator`. + +```java +public interface TaxCalculator { + + double calculate(double amount); + +} +``` + +**Paquete de aplicación** + +En otro paquete (que el cliente desconoce por completo) existen múltiples implementaciones +de la interfaz `TaxCalculator`. Una de ellas es `ForeignTaxCalculator`, que aplica un impuesto del 60 +para los productos internacionales. + +```java +public class ForeignTaxCalculator implements TaxCalculator { + + public static final double TAX_PERCENTAGE = 60; + + @Override + public double calculate(double amount) { + return amount * TAX_PERCENTAGE / 100.0; + } + +} +``` + +Otra es `DomesticTaxCalculator`, que grava con un 20% los productos internacionales. + +```java +public class DomesticTaxCalculator implements TaxCalculator { + + public static final double TAX_PERCENTAGE = 20; + + @Override + public double calculate(double amount) { + return amount * TAX_PERCENTAGE / 100.0; + } + +} +``` + +Estas dos implementaciones son instanciadas e inyectadas en la clase cliente por la clase `App.java`. +en la clase cliente. + +```java + var internationalProductInvoice = new InvoiceGenerator(PRODUCT_COST, new ForeignTaxCalculator()); + + LOGGER.info("Foreign Tax applied: {}", "" + internationalProductInvoice.getAmountWithTax()); + + var domesticProductInvoice = new InvoiceGenerator(PRODUCT_COST, new DomesticTaxCalculator()); + + LOGGER.info("Domestic Tax applied: {}", "" + domesticProductInvoice.getAmountWithTax()); +``` + +## Diagrama de clases + +![alt text](./etc/class_diagram.png "Separated Interface") + +## Aplicabilidad + +Utilice el patrón de interfaz separada cuando + +* Estás desarrollando un paquete de framework, y tu framework necesita llamar a algún código de aplicación a través de interfaces. +* Tienes paquetes separados que implementan las funcionalidades que pueden ser conectadas a tu código cliente en tiempo de ejecución o de compilación. +* Su código reside en una capa a la que no se le permite llamar a la capa de implementación de la interfaz por norma. Por ejemplo, una capa de dominio necesita llamar a un mapeador de datos. + +## Tutoriales + +* [Separated Interface Tutorial](https://www.youtube.com/watch?v=d3k-hOA7k2Y) + +## Créditos + +* [Martin Fowler](https://www.martinfowler.com/eaaCatalog/separatedInterface.html) +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321127420&linkId=e08dfb7f2cf6153542ef1b5a00b10abc) diff --git a/localization/es/separated-interface/etc/class_diagram.png b/localization/es/separated-interface/etc/class_diagram.png new file mode 100644 index 000000000000..10d509801f79 Binary files /dev/null and b/localization/es/separated-interface/etc/class_diagram.png differ diff --git a/localization/es/servant/README.md b/localization/es/servant/README.md new file mode 100644 index 000000000000..76b4026a28c0 --- /dev/null +++ b/localization/es/servant/README.md @@ -0,0 +1,236 @@ +--- +title: Servant +shortTitle: Servant +category: Behavioral +language: es +tag: +- Decoupling +--- + +## Propósito +Servant se utiliza para proporcionar algún comportamiento a un grupo de clases. +En lugar de definir ese comportamiento en cada clase - o cuando no podemos factorizar +este comportamiento en la clase padre común - se define una vez en el Servant. + +## Explicación + +Ejemplo del mundo real + +> El Rey, la Reina y otros miembros reales de palacio necesitan sirvientes que les den de comer, +> organizar bebidas, etc. + +En otras palabras + +> Garantiza que un objeto servidor preste determinados servicios a un grupo de clases atendidas. + +Wikipedia dice + +> En ingeniería de software, el patrón Servant define un objeto utilizado para ofrecer alguna funcionalidad +> a un grupo de clases sin definir esa funcionalidad en cada una de ellas. Un Servant es una clase +> cuya instancia (o incluso sólo clase) proporciona métodos que se encargan de un servicio deseado, mientras que +> los objetos para los que (o con los que) el Servant hace algo, se toman como parámetros. + +**Ejemplo programático** + +La clase Servant puede prestar servicios a otros miembros reales de palacio. + +```java +/** + * Servant. + */ +public class Servant { + + public String name; + + /** + * Constructor. + */ + public Servant(String name) { + this.name = name; + } + + public void feed(Royalty r) { + r.getFed(); + } + + public void giveWine(Royalty r) { + r.getDrink(); + } + + public void giveCompliments(Royalty r) { + r.receiveCompliments(); + } + + /** + * Check if we will be hanged. + */ + public boolean checkIfYouWillBeHanged(List tableGuests) { + return tableGuests.stream().allMatch(Royalty::getMood); + } +} +``` + +Royalty es una interfaz. Es implementada por las clases King, y Queen para obtener servicios de servant. + +```java +interface Royalty { + + void getFed(); + + void getDrink(); + + void changeMood(); + + void receiveCompliments(); + + boolean getMood(); +} +``` +La clase King implementa la interfaz Royalty. +```java +public class King implements Royalty { + + private boolean isDrunk; + private boolean isHungry = true; + private boolean isHappy; + private boolean complimentReceived; + + @Override + public void getFed() { + isHungry = false; + } + + @Override + public void getDrink() { + isDrunk = true; + } + + public void receiveCompliments() { + complimentReceived = true; + } + + @Override + public void changeMood() { + if (!isHungry && isDrunk) { + isHappy = true; + } + if (complimentReceived) { + isHappy = false; + } + } + + @Override + public boolean getMood() { + return isHappy; + } +} +``` +La clase Queen implementa la interfaz Royalty. +```java +public class Queen implements Royalty { + + private boolean isDrunk = true; + private boolean isHungry; + private boolean isHappy; + private boolean isFlirty = true; + private boolean complimentReceived; + + @Override + public void getFed() { + isHungry = false; + } + + @Override + public void getDrink() { + isDrunk = true; + } + + public void receiveCompliments() { + complimentReceived = true; + } + + @Override + public void changeMood() { + if (complimentReceived && isFlirty && isDrunk && !isHungry) { + isHappy = true; + } + } + + @Override + public boolean getMood() { + return isHappy; + } + + public void setFlirtiness(boolean f) { + this.isFlirty = f; + } + +} +``` + +Luego: + +```java +public class App { + + private static final Servant jenkins = new Servant("Jenkins"); + private static final Servant travis = new Servant("Travis"); + + /** + * Program entry point. + */ + public static void main(String[] args) { + scenario(jenkins, 1); + scenario(travis, 0); + } + + /** + * Can add a List with enum Actions for variable scenarios. + */ + public static void scenario(Servant servant, int compliment) { + var k = new King(); + var q = new Queen(); + + var guests = List.of(k, q); + + // feed + servant.feed(k); + servant.feed(q); + // serve drinks + servant.giveWine(k); + servant.giveWine(q); + // compliment + servant.giveCompliments(guests.get(compliment)); + + // outcome of the night + guests.forEach(Royalty::changeMood); + + // check your luck + if (servant.checkIfYouWillBeHanged(guests)) { + LOGGER.info("{} will live another day", servant.name); + } else { + LOGGER.info("Poor {}. His days are numbered", servant.name); + } + } +} +``` + +La salida de la consola + +``` +Jenkins will live another day +Poor Travis. His days are numbered +``` + + +## Diagrama de clases +![alt text](./etc/servant-pattern.png "Servant") + +## Aplicabilidad +Utiliza el patrón Servant cuando + +* Cuando queremos que algunos objetos realicen una acción común y no queremos definir esta acción como un método en cada clase. + +## Créditos + +* [Let's Modify the Objects-First Approach into Design-Patterns-First](http://edu.pecinovsky.cz/papers/2006_ITiCSE_Design_Patterns_First.pdf) diff --git a/localization/es/servant/etc/servant-pattern.png b/localization/es/servant/etc/servant-pattern.png new file mode 100644 index 000000000000..a8237775e332 Binary files /dev/null and b/localization/es/servant/etc/servant-pattern.png differ diff --git a/localization/es/sharding/README.md b/localization/es/sharding/README.md new file mode 100644 index 000000000000..7a7235f6418c --- /dev/null +++ b/localization/es/sharding/README.md @@ -0,0 +1,28 @@ +--- +title: Sharding +shortTitle: Sharding +category: Behavioral +language: es +tag: + - Performance + - Cloud distributed +--- + +## Propósito +El patrón sharding significa dividir el almacén de datos en particiones horizontales o shards. Cada fragmento tiene el mismo esquema, pero contiene su propio subconjunto de datos. +Un fragmento es un almacén de datos en sí mismo (puede contener los datos de muchas entidades de diferentes tipos), que se ejecuta en un servidor que actúa como nodo de almacenamiento. + +## Diagrama de clases +![alt text](./etc/sharding.urm.png "Sharding pattern class diagram") + +## Aplicabilidad +Este patrón ofrece las siguientes ventajas: + +- Se puede ampliar el sistema añadiendo más fragmentos que se ejecuten en nodos de almacenamiento adicionales. +- El sistema puede utilizar hardware comercial en lugar de ordenadores especializados (y caros) para cada nodo de almacenamiento. +- Se puede reducir la contención y mejorar el rendimiento equilibrando la carga de trabajo entre los shards. +- En la nube, los shards pueden ubicarse físicamente cerca de los usuarios que accederán a los datos. + +## Créditos + +* [Sharding pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/sharding) \ No newline at end of file diff --git a/localization/es/sharding/etc/sharding.urm.png b/localization/es/sharding/etc/sharding.urm.png new file mode 100644 index 000000000000..e7f412af3f01 Binary files /dev/null and b/localization/es/sharding/etc/sharding.urm.png differ diff --git a/localization/es/single-table-inheritance/README.md b/localization/es/single-table-inheritance/README.md new file mode 100644 index 000000000000..7e9ea9f60c1b --- /dev/null +++ b/localization/es/single-table-inheritance/README.md @@ -0,0 +1,147 @@ +--- +title: Single Table Inheritance Pattern +shortTitle: Single Table Inheritance Pattern +category: Structural +language: es +tag: + - Data access +--- + +## Single Table Inheritance(STI) + +## Propósito + +Representa una jerarquía hereditaria de clases como una única tabla que tiene columnas para todos los campos de las distintas clases. + +## Explicación + +Un ejemplo real + +> Puede haber muchos tipos diferentes de vehículos en este mundo pero todos ellos se engloban bajo el único paraguas de Vehículo + +En palabras sencillas + +> Mapea cada instancia de clase de un árbol de herencia en una única tabla. + +Wikipedia dice + +> La herencia de tabla única es una forma de emular la herencia orientada a objetos en una base de datos relacional. Al mapear desde una tabla de la base de datos a un objeto en un lenguaje orientado a objetos, un campo de la base de datos identifica a qué clase de la jerarquía pertenece el objeto. Todos los campos de todas las clases se almacenan en la misma tabla, de ahí el nombre de "herencia de tabla única". + +**Ejemplo programático** + +Baeldung - Herencia de Hibernate + +> Podemos definir la estrategia que queremos utilizar añadiendo la anotación @Inheritance a la superclase: + +```java +@Entity +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +public class MyProduct { + @Id + private long productId; + private String name; + + // constructor, getters, setters +} +``` + +El identificador de las entidades también se define en la superclase. + +A continuación, podemos añadir las entidades de la subclase: + +```java +@Entity +public class Book extends MyProduct { + private String author; +} +``` + +```java +@Entity +public class Pen extends MyProduct { + private String color; +} +``` +Valores del discriminador + +- Dado que los registros de todas las entidades estarán en la misma tabla, Hibernate necesita una forma de diferenciarlos. + +- Por defecto, esto se hace a través de una columna discriminadora llamada DTYPE que tiene como valor el nombre de la entidad. + +- Para personalizar la columna discriminadora, podemos utilizar la anotación @DiscriminatorColumn: + +```java +@Entity(name="products") +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name="product_type", + discriminatorType = DiscriminatorType.INTEGER) +public class MyProduct { + // ... +} +``` +- Aquí hemos optado por diferenciar las entidades de la subclase MyProduct mediante una columna entera llamada product_type. + +- A continuación, tenemos que indicar a Hibernate qué valor tendrá cada registro de subclase para la columna product_type: + +```java +@Entity +@DiscriminatorValue("1") +public class Book extends MyProduct { + // ... +} +``` +```java +@Entity +@DiscriminatorValue("2") +public class Pen extends MyProduct { + // ... +} +``` + +- Hibernate añade otros dos valores predefinidos que puede tomar la anotación: null y not null: + + - @DiscriminatorValue("null") significa que cualquier fila sin valor discriminador se asignará a la clase de entidad con esta anotación; esto puede aplicarse a la clase raíz de la jerarquía. + - @DiscriminatorValue("not null"): cualquier fila con un valor discriminador que no coincida con ninguno de los asociados a las definiciones de entidad se asignará a la clase con esta anotación. + +## Diagrama de clases + +![alt text](./etc/single-table-inheritance.urm.png "Singleton pattern class diagram") + +## Aplicabilidad + +Utilice el patrón Singleton cuando + +## Use STI Cuando Las Subclases Tienen Los Mismos Campos/Columnas Pero Diferente Comportamiento +- Una buena indicación de que STI es correcto es cuando las diferentes subclases tienen los mismos campos/columnas pero diferentes métodos. En el ejemplo de cuentas anterior, esperamos que todas las columnas de la base de datos sean utilizadas por cada subclase. De lo contrario, habrá muchas columnas nulas en la base de datos. +

    +* Utilizar STI cuando esperamos realizar consultas en todas las subclases + - Otra buena indicación de que STI es correcto es si esperamos realizar consultas a través de todas las clases. Por ejemplo, si queremos encontrar las 10 cuentas con los saldos más altos en todas las clases, STI nos permite utilizar sólo una consulta, mientras que MTI requerirá manipulación en memoria. + +### Tutoriales + +- Cerebros de Java - Herencia de tabla única + +## Consecuencias + +* Los campos a veces son relevantes y a veces no, lo que puede confundir a la gente que usa las tablas directamente. +* Las columnas utilizadas sólo por algunas subclases hacen que se desperdicie espacio en la base de datos. + Hasta qué punto esto es realmente un problema depende de las características + específicas de los datos y de lo bien que la base de datos comprima las columnas vacías. + Oracle, por ejemplo, es muy eficiente en el recorte de espacio desperdiciado, particularmente columnas opcionales a la derecha de la tabla de la base de datos. + Cada base de datos tiene sus propios trucos para esto. +* La tabla única puede acabar siendo demasiado grande, con muchos índices y frecuentes, lo que puede perjudicar el rendimiento. Puede evitar esto teniendo + tablas de índices separadas que o bien enumeran claves de filas que tienen una determinada propiedad o que copien un subconjunto de campos relevantes para un índice. +* Sólo se dispone de un único espacio de nombres para los campos, por lo que hay que asegurarse de que + de no utilizar el mismo nombre para diferentes campos. Los nombres compuestos con el nombre de la clase como prefijo o sufijo. + +## Patrones relacionados + +* MappedSuperclass +* Single Table +* Joined Table +* Table per Class + +## Créditos + +* [Single Table Inheritance - martinFowler.com](https://www.martinfowler.com/eaaCatalog/singleTableInheritance.html) +* [Patterns of Enterprise Application Architecture](https://books.google.co.in/books?id=vqTfNFDzzdIC&pg=PA278&redir_esc=y#v=onepage&q&f=false) diff --git a/localization/es/single-table-inheritance/etc/single-table-inheritance.urm.png b/localization/es/single-table-inheritance/etc/single-table-inheritance.urm.png new file mode 100644 index 000000000000..f3abe8df6fec Binary files /dev/null and b/localization/es/single-table-inheritance/etc/single-table-inheritance.urm.png differ diff --git a/localization/es/singleton/README.md b/localization/es/singleton/README.md new file mode 100644 index 000000000000..0ef6c558d64b --- /dev/null +++ b/localization/es/singleton/README.md @@ -0,0 +1,96 @@ +--- +title: Singleton +shortTitle: Singleton +category: Creational +language: es +tag: + - Gang of Four +--- + +## Propósito + +Asegurar que una clase solo tenga una instancia y proporcionar un punto de acceso global a ella. + +## Explicación + +Ejemplo del mundo real + +> Solo puede haber una torre de marfil donde los magos estudian su magia. La misma torre de marfil encantada +> siempre es utilizada por los magos. La torre de marfil aquí es un singleton. + +En otras palabras + +> Asegura que solo se cree un objeto de una clase en particular. + +Wikipedia dice + +> En ingeniería de software, el patrón singleton es un patrón de diseño de software que limita la +> instanciación de una clase a un solo objeto. Esto es útil cuando se necesita exactamente un objeto para +> coordinar acciones en todo el sistema. + + +**Ejemplo programático** + +Joshua Bloch, Effective Java 2nd Edition p.18 + +> Un enum type con un solo elemento es la mejor forma de implementar un singleton + +```java +public enum EnumIvoryTower { + INSTANCE +} +``` + +Luego, + +```java + var enumIvoryTower1 = EnumIvoryTower.INSTANCE; + var enumIvoryTower2 = EnumIvoryTower.INSTANCE; + LOGGER.info("enumIvoryTower1={}", enumIvoryTower1); + LOGGER.info("enumIvoryTower2={}", enumIvoryTower2); +``` + +La salida de la consola + +``` +enumIvoryTower1=com.iluwatar.singleton.EnumIvoryTower@1221555852 +enumIvoryTower2=com.iluwatar.singleton.EnumIvoryTower@1221555852 +``` + +## Diagrama de clases + +![alt text](./etc/singleton.urm.png "Singleton pattern class diagram") + +## Aplicabilidad + +Utilice el patrón Singleton cuando: + +* Debe haber exactamente una instancia de una clase, y debe ser accesible para los clientes desde un punto de acceso conocido +* Cuando la única instancia debe ser extensible mediante herencia, y los clientes deben poder usar una instancia extendida sin modificar su código + +Algunos casos típicos para Singleton: + +* La clase logging +* Gestionar una conexión a una base de datos +* Gestor de archivos + +## Usos conocidos + +* [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29) +* [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--) +* [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--) + + +## Consecuencias + +* Viola el Principio de Responsabilidad Única (Single Responsibility Principle - SRP) al controlar su creación y ciclo de vida. +* Fomenta el uso de una instancia compartida globalmente, lo que impide que un objeto y los recursos utilizados por este objeto se liberen. +* Crea un código fuertemente acoplado. Los clientes del Singleton se vuelven difíciles de probar. +* Hace casi imposible hacer subclases de un Singleton. + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/singleton/etc/singleton.urm.png b/localization/es/singleton/etc/singleton.urm.png new file mode 100644 index 000000000000..46584af40039 Binary files /dev/null and b/localization/es/singleton/etc/singleton.urm.png differ diff --git a/localization/es/spatial-partition/README.md b/localization/es/spatial-partition/README.md new file mode 100644 index 000000000000..85fcb1dda1ce --- /dev/null +++ b/localization/es/spatial-partition/README.md @@ -0,0 +1,74 @@ +--- +title: Spatial Partition +shortTitle: Spatial Partition +category: Behavioral +language: es +tag: + - Performance + - Game programming +--- + +## Propósito + +Como se explica en el libro [Game Programming Patterns](http://gameprogrammingpatterns.com/spatial-partition.html) +por Bob Nystrom, spatial partition pattern ayuda a localizar eficazmente los objetos almacenándolos en una +estructura de datos organizada por sus posiciones. + +## Explicación + +Digamos que usted está construyendo un juego de guerra con cientos, o incluso miles de jugadores, que se enfrentan en el campo de batalla. +La posición de cada jugador se actualiza en cada fotograma. La forma más sencilla de manejar +todas las interacciones que tienen lugar en el campo es comprobar la posición de cada jugador con la de todos los demás. +posición de cada jugador: + +```java +public void handleMeLee(Unit units[], int numUnits) { + for (var a = 0; a < numUnits - 1; a++) + { + for (var b = a + 1; b < numUnits; b++) + { + if (units[a].position() == units[b].position()) + { + handleAttack(units[a], units[b]); + } + } + } +} +``` + +Esto incluirá un montón de controles innecesarios entre jugadores que están demasiado alejados como para tener alguna +influencia entre ellos. Los bucles anidados dan a esta operación una complejidad O(n^2), que tiene que ser +cada fotograma, ya que muchos de los objetos del campo pueden moverse en cada fotograma. La idea +detrás del patrón de diseño de Partición Espacial es permitir una rápida localización de los objetos utilizando una estructura de datos que está organizada por sus posiciones. +que está organizada por sus posiciones, de modo que cuando se realiza una operación como la anterior, +no es necesario cotejar la posición de cada objeto con la de todos los demás. La estructura de datos +puede utilizarse para almacenar objetos en movimiento y estáticos, aunque para seguir la pista de los objetos en movimiento, +sus posiciones tendrán que restablecerse cada vez que se muevan. Esto significaría tener que crear una nueva +instancia de la estructura de datos cada vez que un objeto se mueva, lo que consumiría memoria adicional. La dirección +estructuras de datos comunes utilizadas para este patrón de diseño son: + +* Grid +* Árbol Quad +* Árbol K-d +* BSP +* Jerarquía de volúmenes límite + +En nuestra implementación, utilizamos la estructura de datos Quadtree que reducirá la complejidad temporal de +O(n^2) a O(nlogn), lo que reduce significativamente los cálculos necesarios en el caso de un gran número de objetos. +significativamente en el caso de un gran número de objetos. + +## Diagrama de clases + +![alt text](./etc/spatial-partition.urm.png "Spatial Partition pattern class diagram") + +## Aplicabilidad + +Utilice el patrón Spatial Partition cuando: + +* Cuando se necesita mantener un registro de un gran número de posiciones de objetos, que se actualizan cada fotograma. +* Cuando es aceptable cambiar memoria por velocidad, ya que la creación y actualización de la estructura de datos consumirá memoria extra. + +## Créditos + +* [Game Programming Patterns/Spatial Partition](http://gameprogrammingpatterns.com/spatial-partition.html) por Bob Nystrom +* [Quadtree tutorial](https://www.youtube.com/watch?v=OJxEcs0w_kE) por Daniel Schiffman diff --git a/localization/es/spatial-partition/etc/spatial-partition.urm.png b/localization/es/spatial-partition/etc/spatial-partition.urm.png new file mode 100644 index 000000000000..5172bdb36a79 Binary files /dev/null and b/localization/es/spatial-partition/etc/spatial-partition.urm.png differ diff --git a/localization/es/special-case/README.md b/localization/es/special-case/README.md new file mode 100644 index 000000000000..94ffe6ba5738 --- /dev/null +++ b/localization/es/special-case/README.md @@ -0,0 +1,367 @@ +--- +title: Special Case +shortTitle: Special Case +category: Behavioral +language: es +tag: + - Extensibility +--- + +## Propósito + +Define algunos casos especiales, y los encapsula en subclases que proporcionan diferentes comportamientos especiales. + +## Explicación + +Ejemplo del mundo real + +> En un sistema de comercio electrónico, la capa de presentación espera que la capa de aplicación produzca cierto modelo de vista. +> Tenemos un escenario de éxito, en el que el modelo de vista de recibo contiene datos reales de la compra, +> y un par de escenarios de fracaso. + +En otras palabras + +> El patrón Special Case permite devolver objetos reales no nulos que realizan comportamientos especiales. + +En [Patterns of Enterprise Application Architecture](https://martinfowler.com/books/eaa.html) se dice +la diferencia con el Patrón de Objeto Nulo + +> Si me perdonas el juego de palabras irresistible, yo veo el Objeto Nulo como un caso especial de Caso Especial. + +**Ejemplo programático** + +Para centrarnos en el patrón en sí, implementamos la BD y el bloqueo de mantenimiento del sistema de comercio electrónico mediante la instancia singleton. + +```java +public class Db { + private static Db instance; + private Map userName2User; + private Map user2Account; + private Map itemName2Product; + + public static Db getInstance() { + if (instance == null) { + synchronized (Db.class) { + if (instance == null) { + instance = new Db(); + instance.userName2User = new HashMap<>(); + instance.user2Account = new HashMap<>(); + instance.itemName2Product = new HashMap<>(); + } + } + } + return instance; + } + + public void seedUser(String userName, Double amount) { + User user = new User(userName); + instance.userName2User.put(userName, user); + Account account = new Account(amount); + instance.user2Account.put(user, account); + } + + public void seedItem(String itemName, Double price) { + Product item = new Product(price); + itemName2Product.put(itemName, item); + } + + public User findUserByUserName(String userName) { + if (!userName2User.containsKey(userName)) { + return null; + } + return userName2User.get(userName); + } + + public Account findAccountByUser(User user) { + if (!user2Account.containsKey(user)) { + return null; + } + return user2Account.get(user); + } + + public Product findProductByItemName(String itemName) { + if (!itemName2Product.containsKey(itemName)) { + return null; + } + return itemName2Product.get(itemName); + } + + public class User { + private String userName; + + public User(String userName) { + this.userName = userName; + } + + public String getUserName() { + return userName; + } + + public ReceiptDto purchase(Product item) { + return new ReceiptDto(item.getPrice()); + } + } + + public class Account { + private Double amount; + + public Account(Double amount) { + this.amount = amount; + } + + public MoneyTransaction withdraw(Double price) { + if (price > amount) { + return null; + } + return new MoneyTransaction(amount, price); + } + + public Double getAmount() { + return amount; + } + } + + public class Product { + private Double price; + + public Product(Double price) { + this.price = price; + } + + public Double getPrice() { + return price; + } + } +} + +public class MaintenanceLock { + private static final Logger LOGGER = LoggerFactory.getLogger(MaintenanceLock.class); + + private static MaintenanceLock instance; + private boolean lock = true; + + public static MaintenanceLock getInstance() { + if (instance == null) { + synchronized (MaintenanceLock.class) { + if (instance == null) { + instance = new MaintenanceLock(); + } + } + } + return instance; + } + + public boolean isLock() { + return lock; + } + + public void setLock(boolean lock) { + this.lock = lock; + LOGGER.info("Maintenance lock is set to: " + lock); + } +} +``` + +Primero presentaremos la capa de presentación, la interfaz del modelo de vista de recibo y su implementación de un escenario exitoso. + +```java +public interface ReceiptViewModel { + void show(); +} + +public class ReceiptDto implements ReceiptViewModel { + + private static final Logger LOGGER = LoggerFactory.getLogger(ReceiptDto.class); + + private Double price; + + public ReceiptDto(Double price) { + this.price = price; + } + + public Double getPrice() { + return price; + } + + @Override + public void show() { + LOGGER.info("Receipt: " + price + " paid"); + } +} +``` + +Y aquí están las implementaciones de los escenarios de fracaso, que son los casos especiales. + +```java +public class DownForMaintenance implements ReceiptViewModel { + private static final Logger LOGGER = LoggerFactory.getLogger(DownForMaintenance.class); + + @Override + public void show() { + LOGGER.info("Down for maintenance"); + } +} + +public class InvalidUser implements ReceiptViewModel { + private static final Logger LOGGER = LoggerFactory.getLogger(InvalidUser.class); + + private final String userName; + + public InvalidUser(String userName) { + this.userName = userName; + } + + @Override + public void show() { + LOGGER.info("Invalid user: " + userName); + } +} + +public class OutOfStock implements ReceiptViewModel { + + private static final Logger LOGGER = LoggerFactory.getLogger(OutOfStock.class); + + private String userName; + private String itemName; + + public OutOfStock(String userName, String itemName) { + this.userName = userName; + this.itemName = itemName; + } + + @Override + public void show() { + LOGGER.info("Out of stock: " + itemName + " for user = " + userName + " to buy"); + } +} + +public class InsufficientFunds implements ReceiptViewModel { + private static final Logger LOGGER = LoggerFactory.getLogger(InsufficientFunds.class); + + private String userName; + private Double amount; + private String itemName; + + public InsufficientFunds(String userName, Double amount, String itemName) { + this.userName = userName; + this.amount = amount; + this.itemName = itemName; + } + + @Override + public void show() { + LOGGER.info("Insufficient funds: " + amount + " of user: " + userName + + " for buying item: " + itemName); + } +} +``` + +En segundo lugar, está la capa de aplicación, la implementación de los servicios de aplicación y la implementación de los servicios de dominio. + +```java +public class ApplicationServicesImpl implements ApplicationServices { + private DomainServicesImpl domain = new DomainServicesImpl(); + + @Override + public ReceiptViewModel loggedInUserPurchase(String userName, String itemName) { + if (isDownForMaintenance()) { + return new DownForMaintenance(); + } + return this.domain.purchase(userName, itemName); + } + + private boolean isDownForMaintenance() { + return MaintenanceLock.getInstance().isLock(); + } +} + +public class DomainServicesImpl implements DomainServices { + public ReceiptViewModel purchase(String userName, String itemName) { + Db.User user = Db.getInstance().findUserByUserName(userName); + if (user == null) { + return new InvalidUser(userName); + } + + Db.Account account = Db.getInstance().findAccountByUser(user); + return purchase(user, account, itemName); + } + + private ReceiptViewModel purchase(Db.User user, Db.Account account, String itemName) { + Db.Product item = Db.getInstance().findProductByItemName(itemName); + if (item == null) { + return new OutOfStock(user.getUserName(), itemName); + } + + ReceiptDto receipt = user.purchase(item); + MoneyTransaction transaction = account.withdraw(receipt.getPrice()); + if (transaction == null) { + return new InsufficientFunds(user.getUserName(), account.getAmount(), itemName); + } + + return receipt; + } +} +``` + +Por último, el cliente envía solicitudes a los servicios de la aplicación para obtener la vista de la presentación. + +```java + // DB seeding + LOGGER.info("Db seeding: " + "1 user: {\"ignite1771\", amount = 1000.0}, " + + "2 products: {\"computer\": price = 800.0, \"car\": price = 20000.0}"); + Db.getInstance().seedUser("ignite1771", 1000.0); + Db.getInstance().seedItem("computer", 800.0); + Db.getInstance().seedItem("car", 20000.0); + + var applicationServices = new ApplicationServicesImpl(); + ReceiptViewModel receipt; + + LOGGER.info("[REQUEST] User: " + "abc123" + " buy product: " + "tv"); + receipt = applicationServices.loggedInUserPurchase("abc123", "tv"); + receipt.show(); + MaintenanceLock.getInstance().setLock(false); + LOGGER.info("[REQUEST] User: " + "abc123" + " buy product: " + "tv"); + receipt = applicationServices.loggedInUserPurchase("abc123", "tv"); + receipt.show(); + LOGGER.info("[REQUEST] User: " + "ignite1771" + " buy product: " + "tv"); + receipt = applicationServices.loggedInUserPurchase("ignite1771", "tv"); + receipt.show(); + LOGGER.info("[REQUEST] User: " + "ignite1771" + " buy product: " + "car"); + receipt = applicationServices.loggedInUserPurchase("ignite1771", "car"); + receipt.show(); + LOGGER.info("[REQUEST] User: " + "ignite1771" + " buy product: " + "computer"); + receipt = applicationServices.loggedInUserPurchase("ignite1771", "computer"); + receipt.show(); +``` + +Salida del programa de cada solicitud: + +``` + Down for maintenance + Invalid user: abc123 + Out of stock: tv for user = ignite1771 to buy + Insufficient funds: 1000.0 of user: ignite1771 for buying item: car + Receipt: 800.0 paid +``` + +## Diagrama de clases + +![alt text](./etc/special_case_urm.png "Special Case") + +## Aplicabilidad + +Utilice el patrón Special Case cuando: + +* Tienes varios lugares en el sistema que tienen el mismo comportamiento después de una comprobación condicional + para una instancia de clase en particular, o el mismo comportamiento después de una comprobación nula. +* Devuelve un objeto real que realiza el comportamiento real, en lugar de un objeto nulo que no realiza nada. + +## Tutorial + +* [Special Case Tutorial](https://www.codinghelmet.com/articles/reduce-cyclomatic-complexity-special-case) + +## Créditos + +* [How to Reduce Cyclomatic Complexity Part 2: Special Case Pattern](https://www.codinghelmet.com/articles/reduce-cyclomatic-complexity-special-case) +* [Patterns of Enterprise Application Architecture](https://martinfowler.com/books/eaa.html) +* [Special Case](https://www.martinfowler.com/eaaCatalog/specialCase.html) \ No newline at end of file diff --git a/localization/es/special-case/etc/special_case_urm.png b/localization/es/special-case/etc/special_case_urm.png new file mode 100644 index 000000000000..03ca646f3816 Binary files /dev/null and b/localization/es/special-case/etc/special_case_urm.png differ diff --git a/localization/es/specification/README.md b/localization/es/specification/README.md new file mode 100644 index 000000000000..6a5bf7fd7238 --- /dev/null +++ b/localization/es/specification/README.md @@ -0,0 +1,214 @@ +--- +title: Specification +shortTitle: Specification +category: Behavioral +language: es +tag: + - Data access +--- + +## También conocido como + +Filter, Criteria + +## Propósito + +El patrón de Specification separa la declaración de cómo emparejar un candidato, del objeto candidato +con el que se compara. Además de su utilidad en la selección, también es valioso para la +validación y para la construcción por encargo. + +## Explicación + +Ejemplo del mundo real + +> Hay un conjunto de criaturas diferentes y a menudo necesitamos seleccionar algún subconjunto de ellas. Podemos +> escribir nuestra especificación de búsqueda como "criaturas que puedan volar", "criaturas de más de 500 +> kilogramos", o como una combinación de otras especificaciones de búsqueda. +> que realizará el filtrado. + +En palabras sencillas + +> El patrón de especificación nos permite separar los criterios de búsqueda del objeto que realiza la +> búsqueda. + +Wikipedia dice + +> En programación informática, el patrón de especificación es un patrón particular de diseño de software, +> por el cual las reglas de negocio pueden ser recombinadas encadenando las reglas de negocio usando lógica booleana +> lógica booleana. + +**Ejemplo programático** + +Si nos fijamos en nuestro ejemplo anterior, tenemos un conjunto de criaturas con ciertas propiedades. +propiedades. Esas propiedades pueden formar parte de un conjunto predefinido y limitado (representado aquí por los +enums Tamaño, Movimiento y Color); pero también pueden ser valores continuos (por ejemplo, la masa de una +criatura). En este caso, es más apropiado utilizar lo que llamamos "especificación parametrizada", +en la que el valor de la propiedad puede darse como argumento al instanciar la criatura, lo que permite +mayor flexibilidad. Una tercera opción es combinar propiedades predefinidas y/o parametrizadas utilizando +lógica booleana, lo que permite posibilidades de selección casi ilimitadas (esto se denomina "especificación compuesta", véase más adelante). +especificación compuesta", véase más adelante). Los pros y los contras de cada enfoque se detallan en la tabla al final de este documento. +de este documento. + +```java +public interface Creature { + String getName(); + Size getSize(); + Movement getMovement(); + Color getColor(); + Mass getMass(); +} +``` + +Y la implementación de `Dragon` tiene este aspecto. + +```java +public class Dragon extends AbstractCreature { + + public Dragon() { + super("Dragon", Size.LARGE, Movement.FLYING, Color.RED, new Mass(39300.0)); + } +} +``` + +Ahora que queremos seleccionar algún subconjunto de ellos, utilizamos selectores. Para seleccionar criaturas que vuelan +debemos usar `MovementSelector`. + +```java +public class MovementSelector extends AbstractSelector { + + private final Movement movement; + + public MovementSelector(Movement m) { + this.movement = m; + } + + @Override + public boolean test(Creature t) { + return t.getMovement().equals(movement); + } +} +``` + +Por otro lado, cuando seleccionamos criaturas más pesadas que una cantidad elegida, usamos +`MassGreaterThanSelector`. + +```java +public class MassGreaterThanSelector extends AbstractSelector { + + private final Mass mass; + + public MassGreaterThanSelector(double mass) { + this.mass = new Mass(mass); + } + + @Override + public boolean test(Creature t) { + return t.getMass().greaterThan(mass); + } +} +``` + +Con estos elementos en su lugar, podemos realizar una búsqueda de criaturas rojas de la siguiente manera: + +```java + var redCreatures = creatures.stream().filter(new ColorSelector(Color.RED)) + .collect(Collectors.toList()); +``` + +Pero también podríamos usar nuestro selector parametrizado así: + +```java + var heavyCreatures = creatures.stream().filter(new MassGreaterThanSelector(500.0) + .collect(Collectors.toList()); +``` + +Nuestra tercera opción es combinar varios selectores. La búsqueda de criaturas especiales +(definidas como rojas, voladoras y no pequeñas) podría hacerse de la siguiente manera: + +```java + var specialCreaturesSelector = + new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)).and(new SizeSelector(Size.SMALL).not()); + + var specialCreatures = creatures.stream().filter(specialCreaturesSelector) + .collect(Collectors.toList()); +``` + +**Más información sobre las especificaciones de los compuestos** + +En Composite Specification, crearemos instancias personalizadas de `AbstractSelector` combinando +otros selectores (llamados "hojas") utilizando los tres operadores lógicos básicos. Éstos se implementan en +ConjunctionSelector`, `DisjunctionSelector` y `NegationSelector`. + +```java +public abstract class AbstractSelector implements Predicate { + + public AbstractSelector and(AbstractSelector other) { + return new ConjunctionSelector<>(this, other); + } + + public AbstractSelector or(AbstractSelector other) { + return new DisjunctionSelector<>(this, other); + } + + public AbstractSelector not() { + return new NegationSelector<>(this); + } +} +``` + +```java +public class ConjunctionSelector extends AbstractSelector { + + private final List> leafComponents; + + @SafeVarargs + ConjunctionSelector(AbstractSelector... selectors) { + this.leafComponents = List.of(selectors); + } + + /** + * Tests if *all* selectors pass the test. + */ + @Override + public boolean test(T t) { + return leafComponents.stream().allMatch(comp -> (comp.test(t))); + } +} +``` + +Todo lo que queda por hacer ahora es crear selectores de hoja (ya sean de código duro o parametrizados) que +sean lo más genéricos posible, y podremos instanciar la clase ``AbstractSelector`` combinando +cualquier cantidad de selectores, como se ejemplificó anteriormente. Debemos tener cuidado, sin embargo, ya que es fácil +cometer un error al combinar muchos operadores lógicos; en particular, debemos prestar atención a la prioridad de las operaciones. +la prioridad de las operaciones. En general, la especificación compuesta es una gran manera de escribir más +código reutilizable, ya que no es necesario crear una clase Selector para cada operación de filtrado. En su lugar +simplemente creamos una instancia de ``AbstractSelector`` "sobre la marcha", utilizando selectores genéricos de "hoja" y algunos selectores booleanos básicos. +y alguna lógica booleana básica. + +**Comparación de los distintos enfoques** + +| Patrón | Uso | Pros | Contras | +|---|---|---|---| +| Especificación Codificada | Los criterios de selección son pocos y se conocen de antemano | + Fácil de implementar | - Inflexible | +| | | + Expresivo | +| Especificación Parametrizada | Los criterios de selección abarcan un amplio rango de valores (por ejemplo, masa, velocidad,...) | + Alguna flexibilidad | - Aún requiere clases de propósito especial | +| Especificación Compuesta | Hay muchos criterios de selección que se pueden combinar de múltiples maneras, por lo tanto, no es factible crear una clase para cada selector | + Muy flexible, sin requerir muchas clases especializadas | - Algo más difícil de comprender | +| | | + Admite operaciones lógicas | - Todavía necesitas crear las clases base utilizadas como hojas | +## Class diagram + +![alt text](./etc/specification.png "Specification") + +## Diagrama de clases + +Utilice el patrón Specification cuando + +* Necesitas seleccionar un subconjunto de objetos basándote en algún criterio, y refrescar la selección en varios momentos. +* Necesita comprobar que sólo se utilizan objetos adecuados para una determinada función (validación). + +## Patrones relacionados + +* Repository + +## Créditos + +* [Martin Fowler - Specifications](http://martinfowler.com/apsupp/spec.pdf) diff --git a/localization/es/specification/etc/specification.png b/localization/es/specification/etc/specification.png new file mode 100644 index 000000000000..60fb0402d8d3 Binary files /dev/null and b/localization/es/specification/etc/specification.png differ diff --git a/localization/es/state/README.md b/localization/es/state/README.md new file mode 100644 index 000000000000..b366d714ce88 --- /dev/null +++ b/localization/es/state/README.md @@ -0,0 +1,168 @@ +--- +title: State +shortTitle: State +category: Behavioral +language: es +tag: + - Gang of Four +--- + +## También conocido como + +Objects for States + +## Propósito + +Permite que un objeto altere su comportamiento cuando cambia su estado interno. El objeto parecerá +cambiar de clase. + +## Explicación + +Ejemplo del mundo real + +> Al observar un mamut en su hábitat natural parece cambiar su comportamiento en función de la +> situación. Al principio puede parecer tranquilo, pero con el tiempo, cuando detecta una amenaza, se enfada y se vuelve peligroso para su entorno. +> peligroso para su entorno. + +En palabras sencillas + +> El patrón de estado permite a un objeto cambiar su comportamiento. + +Wikipedia dice + +> El patrón de estado es un patrón de diseño de software de comportamiento que permite a un objeto alterar su +> comportamiento cuando cambia su estado interno. Este patrón es cercano al concepto de máquinas de estado finito. +> máquinas de estado finito. El patrón de estado puede ser interpretado como un patrón de estrategia, que es capaz de cambiar una estrategia a través de invocaciones de métodos definidos por el usuario. +> estrategia a través de invocaciones de métodos definidos en la interfaz del patrón. + +**Ejemplo programático** + +Esta es la interfaz de estado y sus implementaciones concretas. + +```java +public interface State { + + void onEnterState(); + + void observe(); +} + +@Slf4j +public class PeacefulState implements State { + + private final Mammoth mammoth; + + public PeacefulState(Mammoth mammoth) { + this.mammoth = mammoth; + } + + @Override + public void observe() { + LOGGER.info("{} is calm and peaceful.", mammoth); + } + + @Override + public void onEnterState() { + LOGGER.info("{} calms down.", mammoth); + } +} + +@Slf4j +public class AngryState implements State { + + private final Mammoth mammoth; + + public AngryState(Mammoth mammoth) { + this.mammoth = mammoth; + } + + @Override + public void observe() { + LOGGER.info("{} is furious!", mammoth); + } + + @Override + public void onEnterState() { + LOGGER.info("{} gets angry!", mammoth); + } +} +``` + +Y aquí está el mammoth que contiene el Estado. + +```java +public class Mammoth { + + private State state; + + public Mammoth() { + state = new PeacefulState(this); + } + + public void timePasses() { + if (state.getClass().equals(PeacefulState.class)) { + changeStateTo(new AngryState(this)); + } else { + changeStateTo(new PeacefulState(this)); + } + } + + private void changeStateTo(State newState) { + this.state = newState; + this.state.onEnterState(); + } + + @Override + public String toString() { + return "The mammoth"; + } + + public void observe() { + this.state.observe(); + } +} +``` + +He aquí el ejemplo completo de cómo se comporta el mammoth a lo largo del tiempo. + +```java + var mammoth = new Mammoth(); + mammoth.observe(); + mammoth.timePasses(); + mammoth.observe(); + mammoth.timePasses(); + mammoth.observe(); +``` + +Salida del programa: + +```java + The mammoth gets angry! + The mammoth is furious! + The mammoth calms down. + The mammoth is calm and peaceful. +``` + +## Diagrama de clases + +![alt text](./etc/state_urm.png "State") + +## Aplicabilidad + +Utiliza el patrón State en cualquiera de los siguientes casos: + +* El comportamiento de un objeto depende de su estado, y debe cambiar su comportamiento en tiempo de ejecución dependiendo de ese estado. +* Las operaciones tienen grandes sentencias condicionales multiparte que dependen del estado del objeto. Este estado suele estar representado por una o más constantes enumeradas. A menudo, varias operaciones contendrán esta misma estructura condicional. El patrón State coloca cada rama de la condicional en una clase separada. Esto permite tratar el estado del objeto como un objeto en sí mismo que puede variar independientemente de otros objetos. + +Traducción realizada con la versión gratuita del traductor www.DeepL.com/Translator + +## Usos conocidos + +* [javax.faces.lifecycle.Lifecycle#execute()](http://docs.oracle.com/javaee/7/api/javax/faces/lifecycle/Lifecycle.html#execute-javax.faces.context.FacesContext-) controlled by [FacesServlet](http://docs.oracle.com/javaee/7/api/javax/faces/webapp/FacesServlet.html), the behavior is dependent on current phase of lifecycle. +* [JDiameter - Diameter State Machine](https://github.com/npathai/jdiameter/blob/master/core/jdiameter/api/src/main/java/org/jdiameter/api/app/State.java) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/state/etc/state_urm.png b/localization/es/state/etc/state_urm.png new file mode 100644 index 000000000000..c2cf9f562943 Binary files /dev/null and b/localization/es/state/etc/state_urm.png differ diff --git a/localization/es/step-builder/README.md b/localization/es/step-builder/README.md new file mode 100644 index 000000000000..0b844713d0a3 --- /dev/null +++ b/localization/es/step-builder/README.md @@ -0,0 +1,124 @@ +--- +title: Step Builder +shortTitle: Step Builder +category: Creational +language: es +tag: + - Instantiation +--- + +# Step Builder Pattern + +## Explicación + +El patrón Step Builder es un patrón de diseño de creación utilizado para construir un objeto complejo paso a paso. +Proporciona una interfaz fluida para crear un objeto con un gran número de configuraciones posibles, haciendo el código +más legible y reduciendo la necesidad de múltiples constructores o métodos setter. + +## Propósito + +Una extensión del patrón Builder que guía completamente al usuario a través de la creación del objeto sin posibilidades +de confusión. +La experiencia del usuario será mucho más mejorada por el hecho de que solo verá los métodos del siguiente paso +disponibles, NINGÚN método constructor hasta que sea el momento adecuado para construir el objeto. + +## Ejemplo del mundo real + +Imagine que está construyendo un objeto de configuración para una conexión a una base de datos. La conexión tiene varios +parámetros opcionales como host, puerto, nombre de usuario, contraseña y otros. Usando el patrón Step Builder, puedes +establecer estos parámetros de una forma limpia y legible: + +```java +DatabaseConnection connection = new DatabaseConnection.Builder() + .setHost("localhost") + .setPort(3306) + .setUsername("user") + .setPassword("password") + .setSSL(true) + .build(); +``` + +## En pocas palabras + +El patrón Step Builder permite construir objetos complejos dividiendo el proceso de construcción en una serie de pasos. +Cada paso corresponde a la configuración de un atributo particular u opción de configuración del objeto. Esto resulta en +un código más legible y mantenible, especialmente cuando se trata de objetos que tienen numerosas opciones de +configuración. + +## Wikipedia dice + +Según Wikipedia, el patrón Step Builder es un patrón de diseño de creación en el que un objeto se construye paso a paso. +Implica una clase 'director' dedicada, que orquesta el proceso de construcción a través de una serie de clases ' +constructoras', cada una responsable de un aspecto específico de la configuración del objeto. Este patrón es +particularmente útil cuando se trata de objetos que tienen un gran número de parámetros opcionales. + +## Ejemplo programático + +Suponiendo que tienes una clase `Producto` con varios atributos configurables, un Step Builder para ella podría tener +este aspecto: + +```java +public class Product { + private String name; + private double price; + private int quantity; + + // private constructor to force the use of the builder + private Product(String name, double price, int quantity) { + + this.name = name; + this.price = price; + this.quantity = quantity; + + } + + public static class Builder { + private String name; + private double price; + private int quantity; + + public Builder setName(String name) { + this.name = name; + return this; + } + + public Builder setPrice(double price) { + this.price = price; + return this; + } + + public Builder setQuantity(int quantity) { + this.quantity = quantity; + return this; + } + + public Product build() { + return new Product(name, price, quantity); + } + } +} + +// Usage +Product product = new Product.Builder() + .setName("Example Product") + .setPrice(29.99) + .setQuantity(100) + .build(); +``` + +Este ejemplo muestra cómo utilizar el patrón Constructor por pasos para crear un objeto `Producto` con un conjunto de +atributos personalizables. Cada método del constructor corresponde a un paso del proceso de construcción. + +## Aplicabilidad + +Utilice el patrón Step Builder cuando el algoritmo para crear un objeto complejo debe ser independiente de las partes +que componen el objeto y de cómo se ensamblan el proceso de construcción debe permitir diferentes representaciones para +el objeto que se construye cuando en el proceso de construcción el orden es importante. + +## Otro ejemplo con diagrama de clases + +![alt text](./etc/step-builder.png "Step Builder pattern") + +## Créditos + +* [Marco Castigliego - Step Builder](http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html) diff --git a/localization/es/step-builder/etc/step-builder.png b/localization/es/step-builder/etc/step-builder.png new file mode 100644 index 000000000000..b7b623657c58 Binary files /dev/null and b/localization/es/step-builder/etc/step-builder.png differ diff --git a/localization/es/strangler/README.md b/localization/es/strangler/README.md new file mode 100644 index 000000000000..89a5520b6fc6 --- /dev/null +++ b/localization/es/strangler/README.md @@ -0,0 +1,29 @@ +--- +title: Strangler +shortTitle: Strangler +category: Structural +language: es +tag: + - Extensibility + - Cloud distributed +--- + +## Propósito +Migrar de forma incremental un sistema heredado sustituyendo gradualmente piezas específicas de funcionalidad +con nuevas aplicaciones y servicios. A medida que se sustituyen las funciones del sistema heredado, el nuevo +sistema acaba cubriendo todas las funciones del sistema antiguo y puede tener sus propias funciones nuevas, con lo que +estrangulando el sistema antiguo y permitiéndole retirarlo del servicio. + +## Diagrama de clases +![alt text](./etc/strangler.png "Strangler") + +## Aplicabilidad +Este patrón estrangulador es una manera segura de eliminar gradualmente una cosa por algo mejor, más barato, o +más expandible. Especialmente cuando se quiere actualizar el sistema heredado con nuevas técnicas y se necesita +desarrollar continuamente nuevas características al mismo tiempo. Tenga en cuenta que este patrón requiere un esfuerzo adicional, +por lo que normalmente se utiliza cuando el sistema no es tan simple. + +## Créditos + +* [Strangler pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/strangler) +* [Legacy Application Strangulation : Case Studies](https://paulhammant.com/2013/07/14/legacy-application-strangulation-case-studies/) diff --git a/localization/es/strangler/etc/strangler.png b/localization/es/strangler/etc/strangler.png new file mode 100644 index 000000000000..c69305e5d510 Binary files /dev/null and b/localization/es/strangler/etc/strangler.png differ diff --git a/localization/es/strategy/README.md b/localization/es/strategy/README.md new file mode 100644 index 000000000000..d211914458e2 --- /dev/null +++ b/localization/es/strategy/README.md @@ -0,0 +1,188 @@ +--- +title: Strategy +shortTitle: Strategy +category: Behavioral +language: es +tag: + - Gang of Four +--- + +## También conocido como + +Policy + +## Propósito + +Definir una familia de algoritmos, encapsular cada uno de ellos y hacerlos intercambiables. La estrategia permite +que el algoritmo varíe independientemente de los clientes que lo utilicen. + +## Explicación + +Ejemplo del mundo real + +> Matar dragones es un trabajo peligroso. Con la experiencia, se hace más fácil. Los veteranos de +> Los matadragones han desarrollado diferentes estrategias de lucha contra distintos tipos de dragones. + +En palabras sencillas + +> El patrón de estrategia permite elegir el algoritmo más adecuado en tiempo de ejecución. + +Wikipedia dice + +> En programación informática, el patrón de estrategia (también conocido como patrón de política) es un patrón de > diseño de software de comportamiento que permite seleccionar un algoritmo en tiempo de ejecución. +> patrón de diseño de software que permite seleccionar un algoritmo en tiempo de ejecución. + +**Ejemplo programático** + +Presentemos primero la interfaz de la estrategia para matar dragones y sus implementaciones. + +```java +@FunctionalInterface +public interface DragonSlayingStrategy { + + void execute(); +} + +@Slf4j +public class MeleeStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("With your Excalibur you sever the dragon's head!"); + } +} + +@Slf4j +public class ProjectileStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!"); + } +} + +@Slf4j +public class SpellStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"); + } +} +``` + +Y aquí está el poderoso cazador de dragones, que puede elegir su estrategia de lucha en función del +oponente. + +```java +public class DragonSlayer { + + private DragonSlayingStrategy strategy; + + public DragonSlayer(DragonSlayingStrategy strategy) { + this.strategy = strategy; + } + + public void changeStrategy(DragonSlayingStrategy strategy) { + this.strategy = strategy; + } + + public void goToBattle() { + strategy.execute(); + } +} +``` + +Por último, aquí está el cazador de dragones en acción. + +```java + LOGGER.info("Green dragon spotted ahead!"); + var dragonSlayer = new DragonSlayer(new MeleeStrategy()); + dragonSlayer.goToBattle(); + LOGGER.info("Red dragon emerges."); + dragonSlayer.changeStrategy(new ProjectileStrategy()); + dragonSlayer.goToBattle(); + LOGGER.info("Black dragon lands before you."); + dragonSlayer.changeStrategy(new SpellStrategy()); + dragonSlayer.goToBattle(); +``` + +Salida del programa: + +``` + Green dragon spotted ahead! + With your Excalibur you sever the dragon's head! + Red dragon emerges. + You shoot the dragon with the magical crossbow and it falls dead on the ground! + Black dragon lands before you. + You cast the spell of disintegration and the dragon vaporizes in a pile of dust! +``` + +Además, las expresiones lambda de Java 8 proporcionan otro enfoque para la implementación: + +```java +public class LambdaStrategy { + + private static final Logger LOGGER = LoggerFactory.getLogger(LambdaStrategy.class); + + public enum Strategy implements DragonSlayingStrategy { + MeleeStrategy(() -> LOGGER.info( + "With your Excalibur you sever the dragon's head!")), + ProjectileStrategy(() -> LOGGER.info( + "You shoot the dragon with the magical crossbow and it falls dead on the ground!")), + SpellStrategy(() -> LOGGER.info( + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); + + private final DragonSlayingStrategy dragonSlayingStrategy; + + Strategy(DragonSlayingStrategy dragonSlayingStrategy) { + this.dragonSlayingStrategy = dragonSlayingStrategy; + } + + @Override + public void execute() { + dragonSlayingStrategy.execute(); + } + } +} +``` + +Y aquí está el cazador de dragones en acción. + +```java + LOGGER.info("Green dragon spotted ahead!"); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy); + dragonSlayer.goToBattle(); + LOGGER.info("Red dragon emerges."); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy); + dragonSlayer.goToBattle(); + LOGGER.info("Black dragon lands before you."); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy); + dragonSlayer.goToBattle(); +``` + +La salida del programa es la misma que la anterior. + +## Diagrama de clases + +![alt text](./etc/strategy_urm.png "Strategy") + +## Aplicabilidad + +Utilice el patrón Strategy cuando + +* Muchas clases relacionadas sólo difieren en su comportamiento. Las estrategias proporcionan una forma de configurar una clase con uno de varios comportamientos +* Necesita diferentes variantes de un algoritmo. Por ejemplo, puede definir algoritmos que reflejen diferentes compensaciones espacio/tiempo. Las estrategias pueden utilizarse cuando estas variantes se implementan como una jerarquía de clases de algoritmos +* Un algoritmo utiliza datos que los clientes no deberían conocer. Utilice el patrón Strategy para evitar exponer estructuras de datos complejas específicas del algoritmo. +* Una clase define muchos comportamientos, y éstos aparecen como múltiples sentencias condicionales en sus operaciones. En lugar de muchas condicionales, mueva las ramas condicionales relacionadas a su propia clase Strategy. + +## Tutorial + +* [Strategy Pattern Tutorial](https://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorial) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/strategy/etc/strategy_urm.png b/localization/es/strategy/etc/strategy_urm.png new file mode 100644 index 000000000000..67d19acae62d Binary files /dev/null and b/localization/es/strategy/etc/strategy_urm.png differ diff --git a/localization/es/subclass-sandbox/README.md b/localization/es/subclass-sandbox/README.md new file mode 100644 index 000000000000..4ad6d802db97 --- /dev/null +++ b/localization/es/subclass-sandbox/README.md @@ -0,0 +1,113 @@ +--- +title: Subclass Sandbox +shortTitle: Subclass Sandbox +category: Behavioral +language: es +tag: + - Game programming +--- + +## Propósito +El patrón Subclass Sandbox describe una idea básica, aunque no tiene una mecánica muy detallada. Necesitarás el patrón cuando tengas varias subclases similares. Si tienes que hacer un pequeño cambio, entonces cambia la clase base, mientras que todas las subclases no deberían tener que ser tocadas. Así que la clase base tiene que ser capaz de proporcionar todas las operaciones que una clase derivada necesita realizar. + +## Explicación +Ejemplo del mundo real +> Consideremos que queremos crear algunos superpoderes en el juego, y necesitan moverse acompañados de un efecto de sonido y desovar partículas. ¿Crear muchas clases que contengan métodos similares o necesitar una clase base para derivarlos? El patrón subclase-base te permite tratar este problema de la segunda manera. + +En palabras sencillas +> El subclass-sandbox consiste en trasladar los métodos solapados en las subclases a una clase base que reduzca la tasa de redundancia en las clases. + +Wikipedia dice +> A base class defines an abstract sandbox method and several provided operations. Marking them protected makes it clear that they are for use by derived classes. Each derived sandboxed subclass implements the sandbox method using the provided operations. + +**Ejemplo programático** +Comenzamos con la clase base `Superpower`. Contiene un método abstracto sandbox `active()` y algunas operaciones proporcionadas. + +``` +public abstract class Superpower { + + protected Logger logger; + + protected abstract void activate(); + + protected void move(double x, double y, double z) { + logger.info("Move to ( " + x + ", " + y + ", " + z + " )"); + } + + protected void playSound(String soundName, int volume) { + logger.info("Play " + soundName + " with volume " + volume); + } + + protected void spawnParticles(String particleType, int count) { + logger.info("Spawn " + count + " particle with type " + particleType); + } +} +``` +A continuación podemos crear una subclase derivada sandboxed que implemente el método sandbox usando las operaciones proporcionadas. Aquí está la primera Superpower: +``` +public class SkyLaunch extends Superpower { + + public SkyLaunch() { + super(); + logger = LoggerFactory.getLogger(SkyLaunch.class); + } + + @Override + protected void activate() { + move(0, 0, 20); + playSound("SKYLAUNCH_SOUND", 1); + spawnParticles("SKYLAUNCH_PARTICLE", 100); + } +} +``` +Aquí está la segunda Superpower. +``` +public class GroundDive extends Superpower { + + public GroundDive() { + super(); + logger = LoggerFactory.getLogger(GroundDive.class); + } + + @Override + protected void activate() { + move(0, 0, -20); + playSound("GROUNDDIVE_SOUND", 5); + spawnParticles("GROUNDDIVE_PARTICLE", 20); + } +} +``` +Por último, aquí están los superpower en activo. +``` + LOGGER.info("Use superpower: sky launch"); + var skyLaunch = new SkyLaunch(); + skyLaunch.activate(); + LOGGER.info("Use superpower: ground dive"); + var groundDive = new GroundDive(); + groundDive.activate(); +``` +Salida del programa: +``` +// Use superpower: sky launch +// Move to ( 0.0, 0.0, 20.0 ) +// Play SKYLAUNCH_SOUND with volume 1 +// Spawn 100 particle with type SKYLAUNCH_PARTICLE +// Use superpower: ground dive +// Move to ( 0.0, 0.0, -20.0 ) +// Play GROUNDDIVE_SOUND with volume 5 +// Spawn 20 particle with type GROUNDDIVE_PARTICLE +``` +## Diagrama de clases +![alt text](./etc/subclass-sandbox.urm.png "Subclass Sandbox pattern class diagram") + +## Aplicabilidad +El patrón Subclass Sandbox es un patrón muy simple y común que se encuentra en muchas bases de código, incluso fuera de los juegos. Si tienes un método protegido no virtual por ahí, probablemente ya estés usando algo como esto. Subclass Sandbox es un buen ajuste cuando: + +- Usted tiene una clase base con un número de clases derivadas. +- La clase base es capaz de proporcionar todas las operaciones que una clase derivada puede necesitar realizar. +- Hay solapamiento de comportamiento en las subclases y desea que sea más fácil compartir código entre ellas. +- Usted quiere minimizar el acoplamiento entre las clases derivadas y el resto del programa + +## Créditos + +* [Game Programming Patterns - Subclass Sandbox](https://gameprogrammingpatterns.com/subclass-sandbox.html) diff --git a/localization/es/subclass-sandbox/etc/subclass-sandbox.urm.png b/localization/es/subclass-sandbox/etc/subclass-sandbox.urm.png new file mode 100644 index 000000000000..db81e12cc815 Binary files /dev/null and b/localization/es/subclass-sandbox/etc/subclass-sandbox.urm.png differ diff --git a/localization/es/table-module/README.md b/localization/es/table-module/README.md new file mode 100644 index 000000000000..a7320e983710 --- /dev/null +++ b/localization/es/table-module/README.md @@ -0,0 +1,134 @@ +--- +title: Table Module +shortTitle: Table Module +category: Structural +language: es +tag: + - Data access +--- + +## Propósito +El módulo de tablas organiza la lógica del dominio con una clase por tabla de la base de datos, y una única instancia de una clase contiene los distintos procedimientos que actuarán sobre los datos. + +## Explicación + +Ejemplo del mundo real + +> Cuando tratamos con un sistema de usuarios, necesitamos algunas operaciones sobre la tabla de usuarios. Podemos utilizar el patrón de módulo de tabla en este escenario. Podemos crear una clase llamada UserTableModule e inicializar una instancia de esa clase para manejar la lógica de negocio para todas las filas de la tabla de usuarios. + +En palabras simples + +> Una única instancia que maneja la lógica de negocio para todas las filas de una tabla o vista de la base de datos. + +**Ejemplo programático** + +En el ejemplo del sistema de usuarios, necesitamos manejar la lógica de dominio del login y registro de usuarios. Podemos utilizar el patrón de módulo de tabla y crear una instancia de la clase `UserTableModule` para manejar la lógica de negocio de todas las filas de la tabla de usuarios. + +Aquí está la entidad básica `User`. + +```java +@Setter +@Getter +@ToString +@EqualsAndHashCode +@AllArgsConstructor +public class User { + private int id; + private String username; + private String password; +} +``` + +Aquí está la clase `UserTableModule`. + +```java +public class UserTableModule { + private final DataSource dataSource; + private Connection connection = null; + private ResultSet resultSet = null; + private PreparedStatement preparedStatement = null; + + public UserTableModule(final DataSource userDataSource) { + this.dataSource = userDataSource; + } + + /** + * Login using username and password. + * + * @param username the username of a user + * @param password the password of a user + * @return the execution result of the method + * @throws SQLException if any error + */ + public int login(final String username, final String password) throws SQLException { + // Method implementation. + + } + + /** + * Register a new user. + * + * @param user a user instance + * @return the execution result of the method + * @throws SQLException if any error + */ + public int registerUser(final User user) throws SQLException { + // Method implementation. + } +} +``` + +En la clase `App`, usamos una instancia del `UserTableModule` para manejar el login y registro de usuarios. + +```java +// Create data source and create the user table. +final var dataSource = createDataSource(); +createSchema(dataSource); +userTableModule = new UserTableModule(dataSource); + +//Initialize two users. +var user1 = new User(1, "123456", "123456"); +var user2 = new User(2, "test", "password"); + +//Login and register using the instance of userTableModule. +userTableModule.registerUser(user1); +userTableModule.login(user1.getUsername(), user1.getPassword()); +userTableModule.login(user2.getUsername(), user2.getPassword()); +userTableModule.registerUser(user2); +userTableModule.login(user2.getUsername(), user2.getPassword()); + +deleteSchema(dataSource); +``` + +La salida del programa: + +```java +12:22:13.095 [main] INFO com.iluwatar.tablemodule.UserTableModule - Register successfully! +12:22:13.117 [main] INFO com.iluwatar.tablemodule.UserTableModule - Login successfully! +12:22:13.128 [main] INFO com.iluwatar.tablemodule.UserTableModule - Fail to login! +12:22:13.136 [main] INFO com.iluwatar.tablemodule.UserTableModule - Register successfully! +12:22:13.144 [main] INFO com.iluwatar.tablemodule.UserTableModule - Login successfully! +``` + +## Diagrama de clases + +![](./etc/table-module.urm.png "table module") + +## Aplicabilidad + +Utilice el patrón de módulo de tabla cuando + +- La lógica del dominio es simple y los datos están en forma tabular. +- La aplicación sólo utiliza unas pocas estructuras de datos comunes compartidas orientadas a tablas. + +## Patrones relacionados + +- [Transaction Script](https://java-design-patterns.com/patterns/transaction-script/) + +- [Domain Model](https://java-design-patterns.com/patterns/domain-model/) + +## Créditos + +* [Table Module Pattern](http://wiki3.cosc.canterbury.ac.nz/index.php/Table_module_pattern) +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321127420&linkId=18acc13ba60d66690009505577c45c04) +* [Architecture patterns: domain model and friends](https://inviqa.com/blog/architecture-patterns-domain-model-and-friends) \ No newline at end of file diff --git a/localization/es/table-module/etc/table-module.urm.png b/localization/es/table-module/etc/table-module.urm.png new file mode 100644 index 000000000000..9c4bc0b189db Binary files /dev/null and b/localization/es/table-module/etc/table-module.urm.png differ diff --git a/localization/es/template-method/README.md b/localization/es/template-method/README.md new file mode 100644 index 000000000000..2797f54a0c98 --- /dev/null +++ b/localization/es/template-method/README.md @@ -0,0 +1,156 @@ +--- +title: Template method +shortTitle: Template method +category: Behavioral +language: es +tag: + - Gang of Four +--- + +## Propósito + +Define el esqueleto de un algoritmo en una operación, difiriendo algunos pasos a subclases. Plantilla +Método que permite a las subclases redefinir ciertos pasos de un algoritmo sin cambiar la estructura del algoritmo. +del algoritmo. + +## Explicación + +Ejemplo del mundo real + +> Los pasos generales para robar un objeto son los mismos. Primero, eliges al objetivo, luego lo confundes... +> y finalmente, robas el objeto. Sin embargo, hay muchas maneras de implementar estos +> pasos. + +En palabras sencillas + +> El patrón Template Method esboza los pasos generales en la clase padre y deja que las implementaciones hijas concretas definan los detalles. + +Wikipedia dice + +> En programación orientada a objetos, el método de plantillas es uno de los patrones de diseño de comportamiento +> identificados por Gamma et al. en el libro Design Patterns. El método de plantilla es un método en una +> superclase, normalmente una superclase abstracta, y define el esqueleto de una operación en términos de +> una serie de pasos de alto nivel. Estos pasos son a su vez implementados por métodos de ayuda adicionales +> en la misma clase que el método de plantilla. + +**Ejemplo programático** + +Presentemos primero la clase de método de plantilla junto con sus implementaciones concretas. +Para asegurarse de que las subclases no sobrescriben el método de plantilla, el método de plantilla (en nuestro caso +método `steal`) debe ser declarado `final`, de lo contrario el esqueleto definido en la clase base podría +ser sobreescrito en subclases. + +```java +@Slf4j +public abstract class StealingMethod { + + protected abstract String pickTarget(); + + protected abstract void confuseTarget(String target); + + protected abstract void stealTheItem(String target); + + public final void steal() { + var target = pickTarget(); + LOGGER.info("The target has been chosen as {}.", target); + confuseTarget(target); + stealTheItem(target); + } +} + +@Slf4j +public class SubtleMethod extends StealingMethod { + + @Override + protected String pickTarget() { + return "shop keeper"; + } + + @Override + protected void confuseTarget(String target) { + LOGGER.info("Approach the {} with tears running and hug him!", target); + } + + @Override + protected void stealTheItem(String target) { + LOGGER.info("While in close contact grab the {}'s wallet.", target); + } +} + +@Slf4j +public class HitAndRunMethod extends StealingMethod { + + @Override + protected String pickTarget() { + return "old goblin woman"; + } + + @Override + protected void confuseTarget(String target) { + LOGGER.info("Approach the {} from behind.", target); + } + + @Override + protected void stealTheItem(String target) { + LOGGER.info("Grab the handbag and run away fast!"); + } +} +``` + +Aquí está la clase ladrón halfling que contiene el método de plantilla. + +```java +public class HalflingThief { + + private StealingMethod method; + + public HalflingThief(StealingMethod method) { + this.method = method; + } + + public void steal() { + method.steal(); + } + + public void changeMethod(StealingMethod method) { + this.method = method; + } +} +``` + +Y por último, mostramos cómo el ladrón halfling utiliza los diferentes métodos de robo. + +```java + var thief = new HalflingThief(new HitAndRunMethod()); + thief.steal(); + thief.changeMethod(new SubtleMethod()); + thief.steal(); +``` + +## Diagrama de clases + +![alt text](./etc/template_method_urm.png "Template Method") + +## Aplicabilidad + +El patrón Template Method debería utilizarse + +* Para implementar las partes invariantes de un algoritmo una vez y dejar que las subclases implementen el comportamiento que puede variar. +* Cuando el comportamiento común entre subclases debe ser factorizado y localizado en una clase común para evitar la duplicación de código. Este es un buen ejemplo de "refactorizar para generalizar", tal y como lo describen Opdyke y Johnson. Primero se identifican las diferencias en el código existente y luego se separan las diferencias en nuevas operaciones. Por último, se sustituye el código diferente por un método de plantilla que llama a una de estas nuevas operaciones +* Para controlar las extensiones de las subclases. Puede definir un método de plantilla que llame a operaciones "gancho" en puntos específicos, permitiendo así extensiones sólo en esos puntos + +## Tutoriales + +* [Template-method Pattern Tutorial](https://www.journaldev.com/1763/template-method-design-pattern-in-java) + +## Usos conocidos + +* [javax.servlet.GenericServlet.init](https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/GenericServlet.html#init--): +El método `GenericServlet.init(ServletConfig config)` llama al método sin parámetros `GenericServlet.init()` que está pensado para ser sobreescrito en subclases. +El método `GenericServlet.init(ServletConfig config)` es el método plantilla en este ejemplo. + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/template-method/etc/template_method_urm.png b/localization/es/template-method/etc/template_method_urm.png new file mode 100644 index 000000000000..b7babccff96d Binary files /dev/null and b/localization/es/template-method/etc/template_method_urm.png differ diff --git a/localization/es/throttling/README.md b/localization/es/throttling/README.md new file mode 100644 index 000000000000..a69039b42a3d --- /dev/null +++ b/localization/es/throttling/README.md @@ -0,0 +1,219 @@ +--- +title: Throttling +shortTitle: Throttling +category: Behavioral +language: es +tag: + - Performance + - Cloud distributed +--- + +## Propósito + +Garantizar que un cliente determinado no pueda acceder a los recursos del servicio más allá del límite asignado. + +## Explicación + +Ejemplo del mundo real + +> Un joven humano y un viejo enano entran en un bar. Empiezan a pedir cervezas al camarero. +> El camarero se da cuenta inmediatamente de que el joven humano no debe consumir demasiadas bebidas demasiado rápido +> y se niega a servir si no ha pasado suficiente tiempo. Para el viejo enano, el ritmo de servicio puede ser mayor. +> ser mayor. + +En palabras sencillas + +> El patrón de Throttling se utiliza para limitar la velocidad de acceso a un recurso. + +[Microsoft documentation](https://docs.microsoft.com/en-us/azure/architecture/patterns/throttling) dice + +> Controlar el consumo de recursos utilizados por una instancia de una aplicación, un tenant individual, +> o un servicio completo. Esto puede permitir que el sistema continúe funcionando y cumpla con los acuerdos de nivel de servicio, incluso cuando un aumento de la demanda impone una carga extrema sobre los recursos. + +**Ejemplo programático** + +La clase `BarCustomer` presenta los clientes de la API `Bartender`. La clase `CallsCount` registra el número de +llamadas por `BarCustomer`. + +```java +public class BarCustomer { + + @Getter + private final String name; + @Getter + private final int allowedCallsPerSecond; + + public BarCustomer(String name, int allowedCallsPerSecond, CallsCount callsCount) { + if (allowedCallsPerSecond < 0) { + throw new InvalidParameterException("Number of calls less than 0 not allowed"); + } + this.name = name; + this.allowedCallsPerSecond = allowedCallsPerSecond; + callsCount.addTenant(name); + } +} + +@Slf4j +public final class CallsCount { + private final Map tenantCallsCount = new ConcurrentHashMap<>(); + + public void addTenant(String tenantName) { + tenantCallsCount.putIfAbsent(tenantName, new AtomicLong(0)); + } + + public void incrementCount(String tenantName) { + tenantCallsCount.get(tenantName).incrementAndGet(); + } + + public long getCount(String tenantName) { + return tenantCallsCount.get(tenantName).get(); + } + + public void reset() { + tenantCallsCount.replaceAll((k, v) -> new AtomicLong(0)); + LOGGER.info("reset counters"); + } +} +``` + +A continuación, se introduce el servicio al que llaman los inquilinos. Para realizar un seguimiento del número de llamadas, se utiliza un temporizador de estrangulamiento. + +```java +public interface Throttler { + + void start(); +} + +public class ThrottleTimerImpl implements Throttler { + + private final int throttlePeriod; + private final CallsCount callsCount; + + public ThrottleTimerImpl(int throttlePeriod, CallsCount callsCount) { + this.throttlePeriod = throttlePeriod; + this.callsCount = callsCount; + } + + @Override + public void start() { + new Timer(true).schedule(new TimerTask() { + @Override + public void run() { + callsCount.reset(); + } + }, 0, throttlePeriod); + } +} +``` + +El `Bartender` ofrece el servicio `orderDrink` a los `BarCustomer`s. Los clientes probablemente no +saben que la tasa de servicio de cerveza está limitada por su apariencia. + +```java +class Bartender { + + private static final Logger LOGGER = LoggerFactory.getLogger(Bartender.class); + private final CallsCount callsCount; + + public Bartender(Throttler timer, CallsCount callsCount) { + this.callsCount = callsCount; + timer.start(); + } + + public int orderDrink(BarCustomer barCustomer) { + var tenantName = barCustomer.getName(); + var count = callsCount.getCount(tenantName); + if (count >= barCustomer.getAllowedCallsPerSecond()) { + LOGGER.error("I'm sorry {}, you've had enough for today!", tenantName); + return -1; + } + callsCount.incrementCount(tenantName); + LOGGER.debug("Serving beer to {} : [{} consumed] ", barCustomer.getName(), count+1); + return getRandomCustomerId(); + } + + private int getRandomCustomerId() { + return ThreadLocalRandom.current().nextInt(1, 10000); + } +} +``` + +Ahora es posible ver el ejemplo completo en acción. BarCustomer` el joven humano está limitado a 2 +llamadas por segundo y el viejo enano a 4. + +```java +public static void main(String[] args) { + var callsCount = new CallsCount(); + var human = new BarCustomer("young human", 2, callsCount); + var dwarf = new BarCustomer("dwarf soldier", 4, callsCount); + + var executorService = Executors.newFixedThreadPool(2); + + executorService.execute(() -> makeServiceCalls(human, callsCount)); + executorService.execute(() -> makeServiceCalls(dwarf, callsCount)); + + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Executor service terminated: {}", e.getMessage()); + } +} + +private static void makeServiceCalls(BarCustomer barCustomer, CallsCount callsCount) { + var timer = new ThrottleTimerImpl(1000, callsCount); + var service = new Bartender(timer, callsCount); + // Sleep is introduced to keep the output in check and easy to view and analyze the results. + IntStream.range(0, 50).forEach(i -> { + service.orderDrink(barCustomer); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + LOGGER.error("Thread interrupted: {}", e.getMessage()); + } + }); +} +``` + +Un extracto de la salida de consola del ejemplo: + +``` +18:46:36.218 [Timer-0] INFO com.iluwatar.throttling.CallsCount - reset counters +18:46:36.218 [Timer-1] INFO com.iluwatar.throttling.CallsCount - reset counters +18:46:36.242 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [1 consumed] +18:46:36.242 [pool-1-thread-1] DEBUG com.iluwatar.throttling.Bartender - Serving beer to young human : [1 consumed] +18:46:36.342 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [2 consumed] +18:46:36.342 [pool-1-thread-1] DEBUG com.iluwatar.throttling.Bartender - Serving beer to young human : [2 consumed] +18:46:36.443 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:36.443 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [3 consumed] +18:46:36.544 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:36.544 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [4 consumed] +18:46:36.645 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +18:46:36.645 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:36.745 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:36.745 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +18:46:36.846 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:36.846 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +18:46:36.947 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +18:46:36.947 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:37.048 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +18:46:37.048 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:37.148 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:37.148 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +``` + +## Diagrama de clases + +![alt text](./etc/throttling_urm.png "Throttling pattern class diagram") + +## Aplicabilidad + +El patrón Throttling debe utilizarse: + +* Cuando se necesita restringir el acceso al servicio para no tener un alto impacto en el rendimiento del mismo. +* Cuando varios clientes consumen los mismos recursos del servicio y la restricción debe hacerse en función del uso por cliente. + +## Créditos + +* [Throttling pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/throttling) +* [Cloud Design Patterns: Prescriptive Architecture Guidance for Cloud Applications (Microsoft patterns & practices)](https://www.amazon.com/gp/product/B00ITGHBBS/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B00ITGHBBS&linkId=12aacdd0cec04f372e7152689525631a) diff --git a/localization/es/throttling/etc/throttling_urm.png b/localization/es/throttling/etc/throttling_urm.png new file mode 100644 index 000000000000..a9824e24b5a4 Binary files /dev/null and b/localization/es/throttling/etc/throttling_urm.png differ diff --git a/localization/es/trampoline/README.md b/localization/es/trampoline/README.md new file mode 100644 index 000000000000..8e4e43ec71e4 --- /dev/null +++ b/localization/es/trampoline/README.md @@ -0,0 +1,150 @@ +--- +title: Trampoline +shortTitle: Trampoline +category: Behavioral +language: es +tag: + - Performance +--- + +## Propósito + +El patrón Trampoline se utiliza para implementar algoritmos recursivamente en Java sin volar la pila +y para intercalar la ejecución de funciones sin codificarlas juntas. + +## Explicación + +La recursión es una técnica frecuentemente adoptada para resolver problemas algorítmicos en un estilo de divide y vencerás. +Por ejemplo, el cálculo de la suma acumulativa de Fibonacci y los factoriales. En este tipo de +problemas, la recursividad es más directa que su homóloga de bucle. Además, la recursividad puede +necesitar menos código y parecer más concisa. Hay un dicho que dice que todo problema de recursión puede resolverse +utilizando un bucle a costa de escribir código más difícil de entender. + +Sin embargo, las soluciones de tipo recursivo tienen una gran advertencia. Para cada llamada recursiva, normalmente se necesita +un valor intermedio almacenado y hay una cantidad limitada de memoria de pila disponible. Quedarse sin +memoria de pila crea un error de desbordamiento de pila y detiene la ejecución del programa. + +Trampoline pattern es un truco que permite definir algoritmos recursivos en Java sin desbordar la +pila. + +Ejemplo del mundo real + +> Un cálculo Fibonacci recursivo sin el problema de desbordamiento de pila utilizando el patrón Trampoline. + +En palabras sencillas + +> El patrón Trampoline permite la recursión sin agotar la memoria de la pila. + +Wikipedia dice + +> En Java, trampoline se refiere al uso de reflection para evitar el uso de clases internas, por ejemplo en +> eventos. La sobrecarga de tiempo de una llamada a reflection se intercambia por la sobrecarga de espacio de una clase interna. +> Trampolines en Java generalmente implican la creación de un GenericListener para pasar eventos a una clase externa. + +**Ejemplo programático** + +Esta es la implementación de `Trampoline` en Java. + +Cuando se llama a `get` sobre el Trampoline devuelto, internamente se itera llamando a `jump` sobre el +siempre que la instancia concreta devuelta sea `Trampoline`, deteniéndose una vez que la instancia +instancia devuelta sea `done`. + +```java +public interface Trampoline { + + T get(); + + default Trampoline jump() { + return this; + } + + default T result() { + return get(); + } + + default boolean complete() { + return true; + } + + static Trampoline done(final T result) { + return () -> result; + } + + static Trampoline more(final Trampoline> trampoline) { + return new Trampoline() { + @Override + public boolean complete() { + return false; + } + + @Override + public Trampoline jump() { + return trampoline.result(); + } + + @Override + public T get() { + return trampoline(this); + } + + T trampoline(final Trampoline trampoline) { + return Stream.iterate(trampoline, Trampoline::jump) + .filter(Trampoline::complete) + .findFirst() + .map(Trampoline::result) + .orElseThrow(); + } + }; + } +} +``` + +Uso del `Trampoline` para obtener valores Fibonacci. + +```java +public static void main(String[] args) { + LOGGER.info("Start calculating war casualties"); + var result = loop(10, 1).result(); + LOGGER.info("The number of orcs perished in the war: {}", result); +} + +public static Trampoline loop(int times, int prod) { + if (times == 0) { + return Trampoline.done(prod); + } else { + return Trampoline.more(() -> loop(times - 1, prod * times)); + } +} +``` + +Salida del programa: + +``` +19:22:24.462 [main] INFO com.iluwatar.trampoline.TrampolineApp - Start calculating war casualties +19:22:24.472 [main] INFO com.iluwatar.trampoline.TrampolineApp - The number of orcs perished in the war: 3628800 +``` + +## Diagrama de clases + +![alt text](./etc/trampoline.urm.png "Trampoline pattern class diagram") + +## Aplicabilidad + +Utilice el patrón Trampoline cuando: + +* Para implementar funciones recursivas de cola. Este patrón permite encender una operación sin pila. +* Para intercalar la ejecución de dos o más funciones en el mismo hilo. + +## Usos conocidos + +* [cyclops-react](https://github.com/aol/cyclops-react) + +## Créditos + +* [Trampolining: a practical guide for awesome Java Developers](https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076) +* [Trampoline in java ](http://mindprod.com/jgloss/trampoline.html) +* [Laziness, trampolines, monoids and other functional amenities: this is not your father's Java](https://www.slideshare.net/mariofusco/lazine) +* [Trampoline implementation](https://github.com/bodar/totallylazy/blob/master/src/com/googlecode/totallylazy/Trampoline.java) +* [What is a trampoline function?](https://stackoverflow.com/questions/189725/what-is-a-trampoline-function) +* [Modern Java in Action: Lambdas, streams, functional and reactive programming](https://www.amazon.com/gp/product/1617293563/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617293563&linkId=ad53ae6f9f7c0982e759c3527bd2595c) +* [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://www.amazon.com/gp/product/1617291994/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617291994&linkId=e3e5665b0732c59c9d884896ffe54f4f) diff --git a/localization/es/trampoline/etc/trampoline.urm.png b/localization/es/trampoline/etc/trampoline.urm.png new file mode 100644 index 000000000000..f2e9c7439a32 Binary files /dev/null and b/localization/es/trampoline/etc/trampoline.urm.png differ diff --git a/localization/es/transaction-script/README.md b/localization/es/transaction-script/README.md new file mode 100644 index 000000000000..1ecb005ff482 --- /dev/null +++ b/localization/es/transaction-script/README.md @@ -0,0 +1,118 @@ +--- +title: Transaction Script +shortTitle: Transaction Script +category: Behavioral +language: es +tag: + - Data access +--- + +## Propósito + +Transaction Script organiza la lógica de negocio por procedimientos donde cada procedimiento maneja una única +solicitud de la presentación. + +## Explicación + +Ejemplo del mundo real + +> Necesitas crear un sistema de reservas de habitaciones de hotel. Dado que los requisitos son bastante simples +> utilizar el patrón Transaction Script. + +En palabras sencillas + +> Transaction Script organiza la lógica de negocio en transacciones que el sistema necesita llevar a cabo. + +Ejemplo programático + +La clase `Hotel` se encarga de reservar y cancelar las reservas de habitaciones. + +```java +@Slf4j +public class Hotel { + + private final HotelDaoImpl hotelDao; + + public Hotel(HotelDaoImpl hotelDao) { + this.hotelDao = hotelDao; + } + + public void bookRoom(int roomNumber) throws Exception { + + Optional room = hotelDao.getById(roomNumber); + + if (room.isEmpty()) { + throw new Exception("Room number: " + roomNumber + " does not exist"); + } else { + if (room.get().isBooked()) { + throw new Exception("Room already booked!"); + } else { + Room updateRoomBooking = room.get(); + updateRoomBooking.setBooked(true); + hotelDao.update(updateRoomBooking); + } + } + } + + public void cancelRoomBooking(int roomNumber) throws Exception { + + Optional room = hotelDao.getById(roomNumber); + + if (room.isEmpty()) { + throw new Exception("Room number: " + roomNumber + " does not exist"); + } else { + if (room.get().isBooked()) { + Room updateRoomBooking = room.get(); + updateRoomBooking.setBooked(false); + int refundAmount = updateRoomBooking.getPrice(); + hotelDao.update(updateRoomBooking); + + LOGGER.info("Booking cancelled for room number: " + roomNumber); + LOGGER.info(refundAmount + " is refunded"); + } else { + throw new Exception("No booking for the room exists"); + } + } + } +} +``` + +La clase `Hotel` tiene dos métodos, uno para reservar y otro para cancelar una habitación respectivamente. Cada uno de ellos +transacción en el sistema, haciendo que `Hotel` implemente el patrón Transaction Script +Transaction Script. + +El método `bookRoom` consolida todos los pasos necesarios como comprobar si la habitación ya está reservada +o no, si no está reservada entonces reserva la habitación y actualiza la base de datos utilizando el DAO. + +El método `cancelRoom` consolida pasos como comprobar si la habitación está reservada o no, +si está reservada, calcula el importe del reembolso y actualiza la base de datos utilizando el DAO. + +## Diagrama de clases + +![alt text](./etc/transaction-script.png "Transaction script model") + +## Aplicabilidad + +Utilice el patrón Transaction Script cuando la aplicación tenga sólo una pequeña cantidad de lógica y esa +lógica no será extendida en el futuro. + +## Consecuencias + +* A medida que la lógica de negocio se complica, + se hace progresivamente más difícil mantener el script de transacción + en un estado bien diseñado. +* Puede ocurrir duplicación de código entre scripts de transacciones. +* Normalmente no es fácil refactorizar el script de transacciones a otros patrones de lógica de dominio. + del dominio. + +## Patrones relacionados + +* Domain Model +* Table Module +* Service Layer + +## Créditos + +* [Transaction Script Pattern](https://dzone.com/articles/transaction-script-pattern#:~:text=Transaction%20Script%20(TS)%20is%20the,need%20big%20architecture%20behind%20them.) +* [Transaction Script](https://www.informit.com/articles/article.aspx?p=1398617) +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321127420&linkId=18acc13ba60d66690009505577c45c04) diff --git a/localization/es/transaction-script/etc/transaction-script.png b/localization/es/transaction-script/etc/transaction-script.png new file mode 100644 index 000000000000..6d0cffb6a551 Binary files /dev/null and b/localization/es/transaction-script/etc/transaction-script.png differ diff --git a/localization/es/twin/README.md b/localization/es/twin/README.md new file mode 100644 index 000000000000..7fa93f8a612f --- /dev/null +++ b/localization/es/twin/README.md @@ -0,0 +1,157 @@ +--- +title: Twin +shortTitle: Twin +category: Structural +language: es +tag: + - Extensibility +--- + +## Propósito +Twin pattern es un patrón de diseño que proporciona una solución estándar para simular herencia múltiple en java + +## Explicación + +Ejemplo real + +> Consideremos un juego con una pelota que necesita características de dos tipos, Game Item, e hilos para funcionar sin problemas en el juego. Podemos utilizar dos objetos, con un objeto compatible con el primer tipo y el otro compatible con el segundo tipo. El par de objetos juntos pueden funcionar como una pelota en el juego. + +En palabras sencillas + +> Proporciona una forma de formar dos subclases estrechamente acopladas que pueden actuar como una clase gemela que tiene dos extremos. + +Wikipedia dice + +> En ingeniería de software, el patrón Gemelo es un patrón de diseño de software que permite a los desarrolladores modelar herencia múltiple en lenguajes de programación que no soportan herencia múltiple. Este patrón evita muchos de los problemas de la herencia múltiple. + +**Ejemplo programático** + +Tomemos nuestro ejemplo anterior de la bola de juego. Consideremos que tenemos un juego en el que la pelota necesita ser tanto un `GameItem` como un `Thread`. +En primer lugar, tenemos la clase `GameItem` dada a continuación y la clase `Thread`. + + +```java + +@Slf4j +public abstract class GameItem { + + public void draw() { + LOGGER.info("draw"); + doDraw(); + } + + public abstract void doDraw(); + + + public abstract void click(); +} + +``` + +A continuación, tenemos las subclases `BallItem` y `BallThread` que las heredan, respectivamente. + +```java + +@Slf4j +public class BallItem extends GameItem { + + private boolean isSuspended; + + @Setter + private BallThread twin; + + @Override + public void doDraw() { + + LOGGER.info("doDraw"); + } + + public void move() { + LOGGER.info("move"); + } + + @Override + public void click() { + + isSuspended = !isSuspended; + + if (isSuspended) { + twin.suspendMe(); + } else { + twin.resumeMe(); + } + } +} + + +@Slf4j +public class BallThread extends Thread { + + @Setter + private BallItem twin; + + private volatile boolean isSuspended; + + private volatile boolean isRunning = true; + + /** + * Run the thread. + */ + public void run() { + + while (isRunning) { + if (!isSuspended) { + twin.draw(); + twin.move(); + } + try { + Thread.sleep(250); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + } + + public void suspendMe() { + isSuspended = true; + LOGGER.info("Begin to suspend BallThread"); + } + + public void resumeMe() { + isSuspended = false; + LOGGER.info("Begin to resume BallThread"); + } + + public void stopMe() { + this.isRunning = false; + this.isSuspended = true; + } +} + +``` + +Ahora, cuando necesitemos la pelota, podemos instanciar objetos tanto del `BallThread` como del `BallItem` como un par y pasarlos a su objeto par para que puedan actuar juntos según convenga. + +```java + +var ballItem = new BallItem(); +var ballThread = new BallThread(); + +ballItem.setTwin(ballThread); +ballThread.setTwin(ballItem); + +``` + + +## Diagrama de clases +![alt text](./etc/twin.png "Twin") + +## Aplicabilidad +Utilice el lenguaje Twin + +* Para simular herencia múltiple en un lenguaje que no soporta esta característica. +* Para evitar ciertos problemas de la herencia múltiple como los choques de nombres. + +## Créditos + +* [Twin – A Design Pattern for Modeling Multiple Inheritance](http://www.ssw.uni-linz.ac.at/Research/Papers/Moe99/Paper.pdf) diff --git a/localization/es/twin/etc/twin.png b/localization/es/twin/etc/twin.png new file mode 100644 index 000000000000..724092525bd6 Binary files /dev/null and b/localization/es/twin/etc/twin.png differ diff --git a/localization/es/typeobjectpattern/README.md b/localization/es/typeobjectpattern/README.md new file mode 100644 index 000000000000..9d59f8c1a69c --- /dev/null +++ b/localization/es/typeobjectpattern/README.md @@ -0,0 +1,210 @@ +--- +title: Type-Object +shortTitle: Type-Object +category: Behavioral +language: es +tag: + - Game programming + - Extensibility +--- + +## Propósito +Como se explica en el libro Game Programming Patterns de Robert Nystrom, el patrón objeto tipo ayuda a + +> Permitir la creación flexible de nuevas "clases" mediante la creación de una única clase, cada instancia de la cual representa un tipo diferente de objeto + +## Explicación +Ejemplo del mundo real +> Estás trabajando en un juego con muchas razas diferentes de monstruos. Cada raza de monstruo tiene diferentes valores para los atributos, como ataque, salud, inteligencia, etc. Quieres crear nuevas razas de monstruos, o modificar los atributos de una raza existente, sin necesidad de modificar el código y recompilar el juego. + +En palabras sencillas +> Definimos una clase de objeto de tipo y una clase de objeto tipado. Damos a cada instancia de objeto de tipo una referencia a un objeto tipado, que contiene la información para ese tipo. + +**Ejemplo programático** + +Supongamos que estamos desarrollando un juego de Candy Crush. Hay muchos tipos de caramelos diferentes, y es posible que queramos editar o crear nuevos con el tiempo a medida que desarrollamos el juego. + +En primer lugar, tenemos un tipo para los caramelos, con un nombre de campo, padre, puntos y Tipo. + +```java +@Getter(AccessLevel.PACKAGE) +public class Candy { + + enum Type { + CRUSHABLE_CANDY, + REWARD_FRUIT + } + + String name; + Candy parent; + String parentName; + + @Setter + private int points; + private final Type type; + + Candy(String name, String parentName, Type type, int points) { + this.name = name; + this.parent = null; + this.type = type; + this.points = points; + this.parentName = parentName; + } + +} +``` + +Los datos de campo de los tipos de caramelos se almacenan en el archivo JSON ``candy.json``. Se pueden añadir nuevos caramelos simplemente añadiéndolos a este archivo. + +```json +{"candies" : [ + { + "name" : "fruit", + "parent" : "null", + "type" : "rewardFruit", + "points" : 20 + }, + { + "name" : "candy", + "parent" : "null", + "type" : "crushableCandy", + "points" : 10 + }, + { + "name" : "cherry", + "parent" : "fruit", + "type" : "rewardFruit", + "points" : 0 + }, + { + "name" : "mango", + "parent" : "fruit", + "type" : "rewardFruit", + "points" : 0 + }, + { + "name" : "purple popsicle", + "parent" : "candy", + "type" : "crushableCandy", + "points" : 0 + }, + { + "name" : "green jellybean", + "parent" : "candy", + "type" : "crushableCandy", + "points" : 0 + }, + { + "name" : "orange gum", + "parent" : "candy", + "type" : "crushableCandy", + "points" : 0 + } + ] +} +``` + +El archivo JSON se analiza, instanciando cada tipo de caramelo y almacenándolo en una tabla hash. El campo ``type`` se compara con el enum ``Type`` definido en la clase Candy. + +```java +public class JsonParser { + Hashtable candies; + + JsonParser() { + this.candies = new Hashtable<>(); + } + + void parse() throws JsonParseException { + var is = this.getClass().getClassLoader().getResourceAsStream("candy.json"); + var reader = new InputStreamReader(is); + var json = (JsonObject) com.google.gson.JsonParser.parseReader(reader); + var array = (JsonArray) json.get("candies"); + for (var item : array) { + var candy = (JsonObject) item; + var name = candy.get("name").getAsString(); + var parentName = candy.get("parent").getAsString(); + var t = candy.get("type").getAsString(); + var type = Type.CRUSHABLE_CANDY; + if (t.equals("rewardFruit")) { + type = Type.REWARD_FRUIT; + } + var points = candy.get("points").getAsInt(); + var c = new Candy(name, parentName, type, points); + this.candies.put(name, c); + } + setParentAndPoints(); + } + + void setParentAndPoints() { + for (var e = this.candies.keys(); e.hasMoreElements(); ) { + var c = this.candies.get(e.nextElement()); + if (c.parentName == null) { + c.parent = null; + } else { + c.parent = this.candies.get(c.parentName); + } + if (c.getPoints() == 0 && c.parent != null) { + c.setPoints(c.parent.getPoints()); + } + } + } +} +``` + +## En palabras sencillas + +El patrón Tipo-Objeto en Java es un método para encapsular propiedades y comportamientos específicos de un tipo dentro de un objeto. Este patrón de diseño facilita la adición de nuevos tipos sin necesidad de realizar cambios en el código existente, mejorando así la expansión y el mantenimiento de la base de código. + +## Wikipedia dice + +Aunque no existe una entrada específica en Wikipedia para el patrón Tipo-Objeto, se trata de una técnica de uso común en la programación orientada a objetos. Este patrón ayuda a gestionar objetos que comparten características similares pero tienen valores diferentes para esas características. Su uso está muy extendido en el desarrollo de juegos, donde numerosos tipos de objetos (como los enemigos) comparten un comportamiento común pero tienen propiedades diferentes. + +## Ejemplo programático + +Consideremos un ejemplo en el que intervienen distintos tipos de enemigos en un juego. Cada tipo de enemigo tiene propiedades distintas, como velocidad, salud y daño. + +```java +public class EnemyType { + private String name; + private int speed; + private int health; + private int damage; + + public EnemyType(String name, int speed, int health, int damage) { + this.name = name; + this.speed = speed; + this.health = health; + this.damage = damage; + } + + // getters and setters +} + +public class Enemy { + private EnemyType type; + + // Encapsulating type information in an object + public Enemy(EnemyType type) { + this.type = type; + } + + // other methods +} +``` + +En el ejemplo anterior, `EnemyType` encapsula propiedades específicas del tipo (nombre, velocidad, salud, daño), y `Enemy` utiliza una instancia de `EnemyType` para definir su tipo. De esta forma, puedes añadir tantos tipos de enemigos como quieras sin modificar la clase "Enemigo". + +## Aplicabilidad +Este patrón puede utilizarse cuando: + +* No sabemos de antemano qué tipos vamos a necesitar. +* Queremos ser capaces de modificar o añadir nuevos tipos sin tener que recompilar o cambiar el código. +* La única diferencia entre los diferentes "tipos" de objetos son los datos, no el comportamiento. + +## Otro ejemplo con diagrama de clases +![alt text](./etc/typeobjectpattern.urm.png "Type-Object pattern class diagram") + +## Créditos + +* [Game Programming Patterns - Type Object](http://gameprogrammingpatterns.com/type-object.html) +* [Types as Objects Pattern](http://www.cs.sjsu.edu/~pearce/modules/patterns/analysis/top.htm) diff --git a/localization/es/typeobjectpattern/etc/typeobjectpattern.urm.png b/localization/es/typeobjectpattern/etc/typeobjectpattern.urm.png new file mode 100644 index 000000000000..477dac5f2a2e Binary files /dev/null and b/localization/es/typeobjectpattern/etc/typeobjectpattern.urm.png differ diff --git a/localization/es/update-method/README.md b/localization/es/update-method/README.md new file mode 100644 index 000000000000..60d48081f238 --- /dev/null +++ b/localization/es/update-method/README.md @@ -0,0 +1,34 @@ +--- +title: Update Method +shortTitle: Update Method +category: Behavioral +language: es +tag: + - Game programming +--- + +## Propósito +El patrón de método de actualización simula una colección de objetos independientes indicando a cada uno que procese un fotograma de comportamiento a la vez. + +## Explicación +El mundo del juego mantiene una colección de objetos. Cada objeto implementa un método de actualización que simula un fotograma del comportamiento del objeto. En cada fotograma, el juego actualiza cada objeto de la colección. + +Para obtener más información sobre cómo se ejecuta el bucle de juego y cuándo se invocan los métodos de actualización, consulte Patrón de bucle de juego. + +## Diagrama de clases +![alt text](./etc/update-method.urm.png "Update Method pattern class diagram") + +## Aplicabilidad +Si el patrón Game Loop es lo mejor desde el pan rebanado, entonces el patrón Update Method es su mantequilla. Una amplia gama de juegos con entidades vivas con las que el jugador interactúa utilizan este patrón de una forma u otra. Si el juego tiene marines espaciales, dragones, marcianos, fantasmas o atletas, es muy probable que utilice este patrón. + +Sin embargo, si el juego es más abstracto y las piezas móviles se parecen menos a actores vivos y más a piezas de un tablero de ajedrez, este patrón no suele encajar. En un juego como el ajedrez, no necesitas simular todas las piezas concurrentemente, y probablemente no necesites decirle a los peones que se actualicen a sí mismos en cada frame. + +Los métodos de actualización funcionan bien cuando: + +- Su juego tiene un número de objetos o sistemas que necesitan ejecutarse simultáneamente. +- El comportamiento de cada objeto es independiente de los demás. +- Los objetos necesitan ser simulados en el tiempo. + +## Créditos + +* [Game Programming Patterns - Update Method](http://gameprogrammingpatterns.com/update-method.html) diff --git a/localization/es/update-method/etc/update-method.urm.png b/localization/es/update-method/etc/update-method.urm.png new file mode 100644 index 000000000000..ddc47b5fe145 Binary files /dev/null and b/localization/es/update-method/etc/update-method.urm.png differ diff --git a/localization/es/value-object/README.md b/localization/es/value-object/README.md new file mode 100644 index 000000000000..6fcc616e6b0e --- /dev/null +++ b/localization/es/value-object/README.md @@ -0,0 +1,95 @@ +--- +title: Value Object +shortTitle: Value Object +category: Creational +language: es +tag: + - Instantiation +--- + +## Propósito + +Proporcionar objetos que siguen la semántica de valor en lugar de la semántica de referencia. Esto significa que la +igualdad de los objetos de valor no se basa en la identidad. Dos objetos de valor son iguales cuando tienen el mismo +valor, no necesariamente siendo el mismo objeto. + +## Explicación + +Ejemplo del mundo real + +> Existe una clase para las estadísticas de héroes en un juego de rol. Las estadísticas contienen atributos como fuerza, +> inteligencia y suerte. Las estadísticas de diferentes héroes deben ser iguales cuando todos los atributos son iguales. + +En palabras simples + +> Los objetos de valor son iguales cuando sus atributos tienen el mismo valor. + +Wikipedia dice + +> En informática, un objeto de valor es un objeto pequeño que representa una entidad simple cuya igualdad no se basa en +> la identidad: es decir, dos objetos de valor son iguales cuando tienen el mismo valor, no necesariamente siendo el mismo +> objeto. + +**Ejemplo Programático** + +Aquí está la clase `HeroStat` que es el objeto valor. Fíjate en el uso de la +anotación [Lombok's `@Value`](https://projectlombok.org/features/Value). + +```java +@Value(staticConstructor = "valueOf") +class HeroStat { + + int strength; + int intelligence; + int luck; +} +``` + +El ejemplo crea tres `HeroStat` diferentes y compara su igualdad. + +```java +var statA = HeroStat.valueOf(10, 5, 0); +var statB = HeroStat.valueOf(10, 5, 0); +var statC = HeroStat.valueOf(5, 1, 8); + +LOGGER.info(statA.toString()); +LOGGER.info(statB.toString()); +LOGGER.info(statC.toString()); + +LOGGER.info("Is statA and statB equal : {}", statA.equals(statB)); +LOGGER.info("Is statA and statC equal : {}", statA.equals(statC)); +``` + +Aquí está la salida de la consola. + +``` +20:11:12.199 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=10, intelligence=5, luck=0) +20:11:12.202 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=10, intelligence=5, luck=0) +20:11:12.202 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=5, intelligence=1, luck=8) +20:11:12.202 [main] INFO com.iluwatar.value.object.App - Is statA and statB equal : true +20:11:12.203 [main] INFO com.iluwatar.value.object.App - Is statA and statC equal : false +``` + +## Diagrama de Clases + +![alt text](./etc/value-object.png "Value Object") + +## Aplicabilidad + +Utilice el objeto Valor cuando + +* La igualdad del objeto debe basarse en su valor. + +## Usos conocidos + +* [java.util.Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html) +* [java.time.LocalDate](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) +* [joda-time, money, beans](http://www.joda.org/) + +## Créditos + +* [Patterns of Enterprise Application Architecture](http://www.martinfowler.com/books/eaa.html) +* [ValueObject](https://martinfowler.com/bliki/ValueObject.html) +* [VALJOs - Value Java Objects : Stephen Colebourne's blog](http://blog.joda.org/2014/03/valjos-value-java-objects.html) +* [Value Object : Wikipedia](https://en.wikipedia.org/wiki/Value_object) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/es/value-object/etc/value-object.png b/localization/es/value-object/etc/value-object.png new file mode 100644 index 000000000000..69a244c80691 Binary files /dev/null and b/localization/es/value-object/etc/value-object.png differ diff --git a/localization/es/visitor/README.md b/localization/es/visitor/README.md new file mode 100644 index 000000000000..e79f21122a41 --- /dev/null +++ b/localization/es/visitor/README.md @@ -0,0 +1,233 @@ +--- +title: Visitor +shortTitle: Visitor +category: Behavioral +language: es +tag: + - Gang of Four +--- + +## Propósito + +Representar una operación a realizar sobre los elementos de una estructura de objetos. Visitante permite +definir una nueva operación sin cambiar las clases de los elementos sobre los que opera. + +## Explicación + +Ejemplo del mundo real + +> Considere una estructura de árbol con unidades del ejército. El comandante tiene dos sargentos bajo él y cada sargento +> tiene tres soldados bajo él. Dado que la jerarquía implementa el patrón visitante, podemos +> crear fácilmente nuevos objetos que interactúen con el comandante, los sargentos, los soldados, o todos ellos. + + +Ejemplo del mundo real + +> El patrón Visitante define las operaciones que se pueden realizar en los nodos de la estructura de datos. + +Wikipedia dice + +> En programación orientada a objetos e ingeniería de software, el patrón de diseño visitante es una forma de +> separar un algoritmo de una estructura de objetos sobre la que opera. Un resultado práctico de esta +> separación es la capacidad de añadir nuevas operaciones a estructuras de objetos existentes sin modificarlas. +> las estructuras. + +**Ejemplo programático** + +Dado el ejemplo anterior de la unidad del ejército, primero tenemos los tipos básicos Unit y UnitVisitor. + +```java +public abstract class Unit { + + private final Unit[] children; + + public Unit(Unit... children) { + this.children = children; + } + + public void accept(UnitVisitor visitor) { + Arrays.stream(children).forEach(child -> child.accept(visitor)); + } +} + +public interface UnitVisitor { + + void visit(Soldier soldier); + + void visit(Sergeant sergeant); + + void visit(Commander commander); +} +``` + +Luego tenemos las unidades de hormigón. + +```java +public class Commander extends Unit { + + public Commander(Unit... children) { + super(children); + } + + @Override + public void accept(UnitVisitor visitor) { + visitor.visit(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "commander"; + } +} + +public class Sergeant extends Unit { + + public Sergeant(Unit... children) { + super(children); + } + + @Override + public void accept(UnitVisitor visitor) { + visitor.visit(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "sergeant"; + } +} + +public class Soldier extends Unit { + + public Soldier(Unit... children) { + super(children); + } + + @Override + public void accept(UnitVisitor visitor) { + visitor.visit(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "soldier"; + } +} +``` + +He aquí, pues, algunos visitantes concretos. + +```java +@Slf4j +public class CommanderVisitor implements UnitVisitor { + + @Override + public void visit(Soldier soldier) { + // Do nothing + } + + @Override + public void visit(Sergeant sergeant) { + // Do nothing + } + + @Override + public void visit(Commander commander) { + LOGGER.info("Good to see you {}", commander); + } +} + +@Slf4j +public class SergeantVisitor implements UnitVisitor { + + @Override + public void visit(Soldier soldier) { + // Do nothing + } + + @Override + public void visit(Sergeant sergeant) { + LOGGER.info("Hello {}", sergeant); + } + + @Override + public void visit(Commander commander) { + // Do nothing + } +} + +@Slf4j +public class SoldierVisitor implements UnitVisitor { + + @Override + public void visit(Soldier soldier) { + LOGGER.info("Greetings {}", soldier); + } + + @Override + public void visit(Sergeant sergeant) { + // Do nothing + } + + @Override + public void visit(Commander commander) { + // Do nothing + } +} +``` + +Por último, podemos mostrar el poder de los visitantes en acción. + +```java +commander.accept(new SoldierVisitor()); +commander.accept(new SergeantVisitor()); +commander.accept(new CommanderVisitor()); +``` + +Salida del programa: + +``` +Greetings soldier +Greetings soldier +Greetings soldier +Greetings soldier +Greetings soldier +Greetings soldier +Hello sergeant +Hello sergeant +Good to see you commander +``` + +## Diagrama de clases + +![alt text](./etc/visitor_1.png "Visitor") + +## Aplicabilidad + +Utilice el patrón Visitor cuando + +* Una estructura de objetos contiene muchas clases de objetos con diferentes interfaces, y desea realizar operaciones en estos objetos que dependen de sus clases concretas. +* Es necesario realizar muchas operaciones distintas y no relacionadas en los objetos de una estructura de objetos, y se desea evitar "contaminar" sus clases con estas operaciones. Visitor permite mantener juntas las operaciones relacionadas definiéndolas en una clase. Cuando la estructura de objetos es compartida por muchas aplicaciones, utilice Visitor para poner las operaciones sólo en aquellas aplicaciones que las necesiten. +* Las clases que definen la estructura del objeto raramente cambian, pero a menudo se quieren definir nuevas operaciones sobre la estructura. Cambiar las clases de la estructura del objeto requiere redefinir la interfaz para todos los visitantes, lo que es potencialmente costoso. Si las clases de la estructura del objeto cambian a menudo, probablemente sea mejor definir las operaciones en esas clases. + +## Tutoriales + +* [Refactoring Guru](https://refactoring.guru/design-patterns/visitor) +* [Dzone](https://dzone.com/articles/design-patterns-visitor) +* [Sourcemaking](https://sourcemaking.com/design_patterns/visitor) + +## Usos conocidos + +* [Apache Wicket](https://github.com/apache/wicket) component tree, Mire [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java) +* [javax.lang.model.element.AnnotationValue](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/AnnotationValue.html) y [AnnotationValueVisitor](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/AnnotationValueVisitor.html) +* [javax.lang.model.element.Element](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/Element.html) y [Element Visitor](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/ElementVisitor.html) +* [java.nio.file.FileVisitor](http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileVisitor.html) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/es/visitor/etc/visitor.png b/localization/es/visitor/etc/visitor.png new file mode 100644 index 000000000000..5bbee60eeabf Binary files /dev/null and b/localization/es/visitor/etc/visitor.png differ diff --git a/localization/es/visitor/etc/visitor_1.png b/localization/es/visitor/etc/visitor_1.png new file mode 100644 index 000000000000..de5285d7fdc3 Binary files /dev/null and b/localization/es/visitor/etc/visitor_1.png differ diff --git a/localization/fa/abstract-document/README.md b/localization/fa/abstract-document/README.md new file mode 100644 index 000000000000..7097ffc8b4ea --- /dev/null +++ b/localization/fa/abstract-document/README.md @@ -0,0 +1,243 @@ +--- +title: "الگوی Abstract Document در جاوا: ساده‌سازی مدیریت داده با انعطاف‌پذیری" +shortTitle: Abstract Document +description: "الگوی طراحی Abstract Document در جاوا را بررسی کنید. با هدف، توضیح، کاربرد، مزایا و نمونه‌های دنیای واقعی برای پیاده‌سازی ساختارهای داده‌ای پویا و انعطاف‌پذیر آشنا شوید." +category: Structural +language: fa +tag: + - Abstraction + - Decoupling + - Dynamic typing + - Encapsulation + - Extensibility + - Polymorphism +--- + +## هدف الگوی طراحی Abstract Document + +الگوی طراحی Abstract Document در جاوا یک الگوی طراحی ساختاری مهم است که راهی یکپارچه برای مدیریت ساختارهای داده‌ای سلسله‌مراتبی و درخت‌ی فراهم می‌کند، با تعریف یک واسط مشترک برای انواع مختلف اسناد. این الگو ساختار اصلی سند را از فرمت‌های خاص داده جدا می‌کند، که باعث به‌روزرسانی پویا و نگهداری ساده‌تر می‌شود. + +## توضیح دقیق الگوی Abstract Document با نمونه‌های دنیای واقعی + +الگوی طراحی Abstract Document در جاوا امکان مدیریت پویا ویژگی‌های پویا(غیر استاتیک) را فراهم می‌کند. این الگو از مفهوم traits استفاده می‌کند تا ایمنی نوع‌داده (type safety) را فراهم کرده و ویژگی‌های کلاس‌های مختلف را به مجموعه‌ای از واسط‌ها تفکیک کند. + +مثال دنیای واقعی + +> فرض کنید یک سیستم کتابخانه از الگوی Abstract Document در جاوا استفاده می‌کند، جایی که کتاب‌ها می‌توانند فرمت‌ها و ویژگی‌های متنوعی داشته باشند: کتاب‌های فیزیکی، کتاب‌های الکترونیکی، و کتاب‌های صوتی. هر فرمت ویژگی‌های خاص خود را دارد، مانند تعداد صفحات برای کتاب‌های فیزیکی، حجم فایل برای کتاب‌های الکترونیکی، و مدت‌زمان برای کتاب‌های صوتی. الگوی Abstract Document به سیستم کتابخانه اجازه می‌دهد تا این فرمت‌های متنوع را به‌صورت انعطاف‌پذیر مدیریت کند. با استفاده از این الگو، سیستم می‌تواند ویژگی‌ها را به‌صورت پویا ذخیره و بازیابی کند، بدون نیاز به ساختار سفت و سخت برای هر نوع کتاب، و این کار افزودن فرمت‌ها یا ویژگی‌های جدید را در آینده بدون تغییرات عمده در کد آسان می‌سازد. + +به زبان ساده + +> الگوی Abstract Document اجازه می‌دهد ویژگی‌هایی به اشیاء متصل شوند بدون اینکه خود آن اشیاء از آن اطلاع داشته باشند. + +ویکی‌پدیا می‌گوید + +> یک الگوی طراحی ساختاری شی‌ء‌گرا برای سازماندهی اشیاء در کلید-مقدارهایی با تایپ آزاد و ارائه داده‌ها از طریق نمای تایپ است. هدف این الگو دستیابی به انعطاف‌پذیری بالا بین اجزا در یک زبان strongly typed است که در آن بتوان ویژگی‌های جدیدی را به‌صورت پویا به ساختار درختی اشیاء اضافه کرد، بدون از دست دادن پشتیبانی از type safety. این الگو از traits برای جداسازی ویژگی‌های مختلف یک کلاس در اینترفیس‌های متفاوت استفاده می‌کند. + +نمودار کلاس + +![Abstract Document class diagram](./etc/abstract-document.png "Abstract Document class diagram") + +## مثال برنامه‌نویسی از الگوی Abstract Document در جاوا + +فرض کنید یک خودرو داریم که از قطعات مختلفی تشکیل شده است. اما نمی‌دانیم آیا این خودرو خاص واقعاً همه قطعات را دارد یا فقط برخی از آن‌ها. خودروهای ما پویا و بسیار انعطاف‌پذیر هستند. + +بیایید ابتدا کلاس‌های پایه `Document` و `AbstractDocument` را تعریف کنیم. این کلاس‌ها اساساً یک شیء را قادر می‌سازند تا یک نقشه از ویژگی‌ها و هر تعداد شیء فرزند را نگه دارد. + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + + // Other properties and methods... +} +``` +در ادامه، یک enum به نام Property و مجموعه‌ای از واسط‌ها برای type، price، model و parts تعریف می‌کنیم. این کار به ما اجازه می‌دهد یک واسط با ظاهر استاتیک برای کلاس Car ایجاد کنیم. +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} + +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} + +public class Part extends AbstractDocument implements HasType, HasModel, HasPrice { + + public Part(Map properties) { + super(properties); + } +} +``` +اکنون آماده‌ایم تا کلاس Car را معرفی کنیم. +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` +و در نهایت، نحوه ساخت و استفاده از Car را در یک مثال کامل می‌بینید. +```java + public static void main(String[] args) { + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); +} +``` +خروجی برنامه: +``` +07:21:57.391 [main] INFO com.iluwatar.abstractdocument.App -- Constructing parts and car +07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- Here is our car: +07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- -> model: 300SL +07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> price: 10000 +07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> parts: +07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- wheel/15C/100 +07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- door/Lambo/300 +``` + + ### چه زمانی از الگوی Abstract Document در جاوا استفاده کنیم؟ + +الگوی طراحی Abstract Document به‌ویژه در سناریوهایی مفید است که نیاز به مدیریت انواع مختلفی از اسناد در جاوا وجود دارد که برخی ویژگی‌ها یا رفتارهای مشترک دارند، ولی ویژگی‌ها یا رفتارهای خاص خود را نیز دارند. در ادامه چند سناریوی مناسب برای این الگو آورده شده است: + +* سیستم‌های مدیریت محتوا (CMS): ممکن است انواع مختلفی از محتوا مانند مقاله، تصویر، ویدئو و... وجود داشته باشد. هر نوع محتوا ویژگی‌های مشترکی مثل تاریخ ایجاد، نویسنده و تگ‌ها دارد، ولی همچنین ویژگی‌های خاصی مثل ابعاد تصویر یا مدت‌زمان ویدئو. + +* سیستم‌های فایل: اگر یک سیستم فایل طراحی می‌کنید که باید انواع مختلف فایل مانند اسناد، تصاویر، فایل‌های صوتی و دایرکتوری‌ها را مدیریت کند، این الگو می‌تواند راهی یکپارچه برای دسترسی به ویژگی‌هایی مانند اندازه فایل یا تاریخ ایجاد، فراهم کند و در عین حال ویژگی‌های خاص هر نوع فایل را هم مدیریت کند. + +* سیستم‌های تجارت الکترونیک: یک پلتفرم فروش آنلاین ممکن است محصولات مختلفی داشته باشد مثل محصولات فیزیکی، فایل‌های دیجیتال، و اشتراک‌ها. این محصولات ویژگی‌هایی مثل نام، قیمت و توضیح را به اشتراک می‌گذارند، ولی ویژگی‌های خاصی هم دارند مانند وزن حمل برای محصولات فیزیکی یا لینک دانلود برای دیجیتال‌ها. + +* سیستم‌های سوابق پزشکی: در مراقبت سلامت، پرونده بیماران ممکن است داده‌های مختلفی مثل مشخصات فردی، سوابق پزشکی، نتایج آزمایش‌ها و نسخه‌ها را شامل شود. این الگو می‌تواند ویژگی‌های مشترک مثل شماره بیمار یا تاریخ تولد را مدیریت کند و هم‌زمان ویژگی‌های خاصی مثل نتایج آزمایش یا داروهای تجویزی را هم پوشش دهد. + +* مدیریت پیکربندی: هنگام کار با تنظیمات پیکربندی نرم‌افزار، ممکن است انواع مختلفی از عناصر پیکربندی وجود داشته باشد، هر یک با ویژگی‌های خاص خود. این الگو می‌تواند برای مدیریت این عناصر مفید باشد. + +* پلتفرم‌های آموزشی: سیستم‌های آموزشی ممکن است انواع مختلفی از منابع یادگیری داشته باشند مثل محتوای متنی، ویدیوها، آزمون‌ها و تمرین‌ها. ویژگی‌های مشترکی مثل عنوان، نویسنده و تاریخ انتشار وجود دارد، ولی ویژگی‌های خاصی مانند مدت ویدیو یا مهلت تحویل تمرین نیز ممکن است وجود داشته باشد. + +* ابزارهای مدیریت پروژه: در برنامه‌های مدیریت پروژه، ممکن است انواع مختلفی از وظایف مانند آیتم‌های to-do، milestoneها و issueها داشته باشید. این الگو می‌تواند برای مدیریت ویژگی‌های عمومی مانند نام وظیفه و مسئول آن استفاده شود و در عین حال ویژگی‌های خاص مانند تاریخ milestone یا اولویت issue را نیز پوشش دهد. + +* اسناد ساختار ویژگی‌های متنوع و در حال تحول دارند. + +* افزودن ویژگی‌های جدید به‌صورت پویا یک نیاز رایج است. + +* جداسازی دسترسی به داده از فرمت‌های خاص حیاتی است. + +* نگهداری‌پذیری و انعطاف‌پذیری برای کد اهمیت دارد. + +ایده اصلی پشت الگوی Abstract Document فراهم کردن روشی انعطاف‌پذیر و قابل توسعه برای مدیریت انواع مختلف اسناد یا موجودیت‌ها با ویژگی‌های مشترک و خاص است. با تعریف یک واسط مشترک و پیاده‌سازی آن در انواع مختلف اسناد، می‌توان به شیوه‌ای منظم و یکپارچه برای مدیریت ساختارهای پیچیده داده دست یافت. +### مزایا و معایب الگوی Abstract Document +
    +مزایا: + +* انعطاف‌پذیری: پشتیبانی از ساختارهای متنوع اسناد و ویژگی‌ها. + +* قابلیت توسعه: افزودن ویژگی‌های جدید بدون شکستن کد موجود. + +* نگهداری‌پذیری: ارتقاء کد تمیز و قابل تطبیق به‌واسطه جداسازی وظایف. + +* قابلیت استفاده مجدد: نمای دید تایپ‌شده باعث استفاده مجدد از کد برای دسترسی به نوع خاصی از ویژگی می‌شود. + +معایب: + +* پیچیدگی: نیاز به تعریف واسط‌ها و نماها، که باعث اضافه شدن سربار پیاده‌سازی می‌شود. + +* کارایی: ممکن است سربار کمی نسبت به دسترسی مستقیم به داده داشته باشد. +
    + +منابع و اعتبارها + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) + +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) + +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)] (https://amzn.to/49zRP4R) + +* [Patterns of Enterprise Application Architecture] (https://amzn.to/3WfKBPR) + +* [Abstract Document Pattern (Wikipedia)] (https://en.wikipedia.org/wiki/Abstract_Document_Pattern) + +* [Dealing with Properties (Martin Fowler)] (http://martinfowler.com/apsupp/properties.pdf) diff --git a/localization/fa/abstract-document/etc/abstract-document.png b/localization/fa/abstract-document/etc/abstract-document.png new file mode 100644 index 000000000000..6bc0b29a4e77 Binary files /dev/null and b/localization/fa/abstract-document/etc/abstract-document.png differ diff --git a/localization/fa/active-object/README.md b/localization/fa/active-object/README.md new file mode 100644 index 000000000000..7c105b072aaa --- /dev/null +++ b/localization/fa/active-object/README.md @@ -0,0 +1,220 @@ +--- +title: "الگوی Active Object در جاوا: دستیابی به پردازش ناهمگام کارآمد" +shortTitle: Active Object +description: "با الگوی طراحی Active Object در جاوا آشنا شوید. این راهنما رفتار ناهمگام، هم‌زمانی (concurrency) و مثال‌های کاربردی برای بهبود عملکرد برنامه‌های جاوای شما را پوشش می‌دهد." +category: Concurrency +language: fa +tag: + - Asynchronous + - Decoupling + - Messaging + - Synchronization + - Thread management +--- + +## هدف الگوی طراحی Active Object + +الگوی Active Object روشی مطمئن برای پردازش ناهمگام در جاوا فراهم می‌کند که به پاسخ‌گو بودن برنامه‌ها و مدیریت مؤثر threadها کمک می‌کند. این الگو با محصور کردن وظایف در شیءهایی که هر کدام thread و صف پیام مخصوص خود را دارند، به این هدف می‌رسد. این جداسازی باعث می‌شود thread اصلی پاسخ‌گو باقی بماند و مشکلاتی مانند دست‌کاری مستقیم threadها یا دسترسی به وضعیت مشترک (shared state) به وجود نیاید. + +## توضیح کامل الگوی Active Object با مثال‌های دنیای واقعی + +مثال دنیای واقعی + +> تصور کنید در یک رستوران شلوغ، مشتریان سفارش خود را به گارسون‌ها می‌سپارند. به‌جای آنکه گارسون‌ها خودشان به آشپزخانه بروند و غذا را آماده کنند، سفارش‌ها را روی کاغذهایی می‌نویسند و به یک هماهنگ‌کننده می‌دهند. این هماهنگ‌کننده گروهی از سرآشپزها را مدیریت می‌کند که غذاها را به صورت ناهمگام آماده می‌کنند. هرگاه آشپزی آزاد شود، سفارش بعدی را از صف برمی‌دارد، غذا را آماده می‌کند و پس از آن گارسون را برای سرو غذا مطلع می‌سازد. +> +> در این قیاس، گارسون‌ها نماینده threadهای کلاینت هستند، هماهنگ‌کننده نقش زمان‌بند (scheduler) را ایفا می‌کند، و آشپزها نمایان‌گر اجرای متدها در threadهای جداگانه هستند. این ساختار باعث می‌شود گارسون‌ها بتوانند بدون مسدود شدن توسط فرایند آماده‌سازی غذا، سفارش‌های بیشتری دریافت کنند—درست مانند اینکه الگوی Active Object، فراخوانی متد را از اجرای آن جدا می‌کند تا هم‌زمانی (concurrency) را افزایش دهد. + +به زبان ساده + +> الگوی Active Object، اجرای متد را از فراخوانی آن جدا می‌کند تا در برنامه‌های چندریسمانی (multithreaded)، هم‌زمانی و پاسخ‌گویی بهتری فراهم شود. + +طبق تعریف ویکی‌پدیا + +> الگوی طراحی Active Object اجرای متد را از فراخوانی آن جدا می‌کند، برای شیءهایی که هرکدام thread کنترل مخصوص به خود را دارند. هدف، معرفی هم‌زمانی با استفاده از فراخوانی متد به‌صورت ناهمگام و یک زمان‌بند برای مدیریت درخواست‌ها است. +> +> این الگو شامل شش جزء کلیدی است: +> +> * یک proxy، که رابطی برای کلاینت‌ها با متدهای عمومی فراهم می‌کند. +> * یک interface که درخواست متد برای شیء فعال (active object) را تعریف می‌کند. +> * فهرستی از درخواست‌های معلق از سوی کلاینت‌ها. +> * یک زمان‌بند (scheduler) که تصمیم می‌گیرد کدام درخواست بعدی اجرا شود. +> * پیاده‌سازی متد شیء فعال. +> * یک callback یا متغیر برای اینکه کلاینت نتیجه را دریافت کند. + +نمودار توالی + +![Active Object sequence diagram](./etc/active-object-sequence-diagram.png) + +## مثال برنامه‌نویسی از Active Object در جاوا + +این بخش نحوه عملکرد الگوی Active Object در جاوا را توضیح می‌دهد و کاربرد آن در مدیریت وظایف ناهمگام و کنترل هم‌زمانی را نشان می‌دهد. + +اورک‌ها به دلیل ذات وحشی و غیرقابل مهارشان شناخته می‌شوند. به‌نظر می‌رسد هرکدام thread کنترل مخصوص خود را دارند. برای پیاده‌سازی یک موجود که دارای سازوکار thread مستقل خود باشد و فقط API را در اختیار قرار دهد نه اجرای داخلی را، می‌توان از الگوی Active Object استفاده کرد. + +```java +public abstract class ActiveCreature { + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!", name()); + logger.info("{} has finished eating!", name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.", name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +می‌توان دید هر کلاسی که از ActiveCreature ارث‌بری کند، دارای thread کنترل مختص به خود برای فراخوانی و اجرای متدها خواهد بود. + +برای مثال، کلاس Orc: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } +} +``` +اکنون می‌توان چند موجود مانند orc ایجاد کرد، به آن‌ها دستور داد که بخورند و پرسه بزنند، و آن‌ها این دستورات را در thread مختص به خود اجرا می‌کنند: + +```java +public class App implements Runnable { + + private static final Logger logger = LoggerFactory.getLogger(App.class.getName()); + + private static final int NUM_CREATURES = 3; + + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + List creatures = new ArrayList<>(); + try { + for (int i = 0; i < NUM_CREATURES; i++) { + creatures.add(new Orc(Orc.class.getSimpleName() + i)); + creatures.get(i).eat(); + creatures.get(i).roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + Thread.currentThread().interrupt(); + } finally { + for (int i = 0; i < NUM_CREATURES; i++) { + creatures.get(i).kill(0); + } + } + } +} +``` + +خروجی برنامه: + +``` +09:00:02.501 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 is eating! +09:00:02.501 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 is eating! +09:00:02.501 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 is eating! +09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has finished eating! +09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has finished eating! +09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has started to roam in the wastelands. +09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has finished eating! +09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has started to roam in the wastelands. +09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has started to roam in the wastelands. +``` + +چه زمانی از الگوی Active Object در جاوا استفاده کنیم؟ + +از الگوی Active Object در جاوا استفاده کنید زمانی که: +> * نیاز دارید وظایف ناهمگام را بدون مسدود کردن thread اصلی مدیریت کنید تا عملکرد و پاسخ‌گویی بهتری داشته باشید. +> * نیاز به تعامل ناهمگام با منابع خارجی دارید. +> * می‌خواهید پاسخ‌گویی برنامه را افزایش دهید. +> * نیاز به مدیریت وظایف هم‌زمان به‌صورت ماژولار و قابل نگهداری دارید. + +آموزش‌های Java برای الگوی Active Object +> [Android and Java Concurrency: The Active Object Pattern (Douglas Schmidt)]((https://www.youtube.com/watch?v=Cd8t2u5Qmvc)) + +کاربردهای دنیای واقعی الگوی Active Object در جاوا + +> سیستم‌های معاملات بلادرنگ که درخواست‌ها به‌صورت ناهمگام پردازش می‌شوند. +> که در آن وظایف طولانی در پس‌زمینه اجرا می‌شوند بدون آنکه رابط کاربری را متوقف کنند. +> رابط‌های کاربری گرافیکی (GUI) +> برنامه‌نویسی بازی‌ها برای مدیریت به‌روزرسانی‌های هم‌زمان وضعیت بازی یا محاسبات هوش مصنوعی. + +مزایا و ملاحظات الگوی Active Object + +با مزایا و معایب استفاده از الگوی Active Object در جاوا آشنا شوید؛ از جمله بهبود ایمنی threadها و ملاحظات سربار احتمالی (overhead). + +> مزایا: +> +> * پاسخ‌گویی بهتر thread اصلی. +> * محصورسازی مسائل مربوط به هم‌زمانی درون شیءها. +> * بهبود سازمان‌دهی کد و قابلیت نگهداری. +> * فراهم‌سازی ایمنی در برابر شرایط بحرانی (thread safety) و جلوگیری از مشکلات وضعیت مشترک. + +> معایب: +> +> * سربار اضافی به دلیل ارسال پیام و مدیریت threadها. +> * برای تمام سناریوهای هم‌زمانی مناسب نیست. + +الگوهای طراحی مرتبط در جاوا + +> * [Command](https://java-design-patterns.com/patterns/command/): درخواست را به‌عنوان یک شیء کپسوله می‌کند، مشابه روشی که Active Object فراخوانی متد را کپسوله می‌کند. +> * [Promise](https://java-design-patterns.com/patterns/promise/): راهی برای دریافت نتیجه یک فراخوانی متد ناهمگام فراهم می‌کند؛ اغلب همراه با Active Object استفاده می‌شود. +> * [Proxy](https://java-design-patterns.com/patterns/proxy/): الگوی Active Object می‌تواند از proxy برای مدیریت فراخوانی‌های متد به‌صورت ناهمگام استفاده کند. + +منابع و مراجع + +> * [Design Patterns: Elements of Reusable Object Software](https://amzn.to/3HYqrBE) +> * [Concurrent Programming in Java: Design Principles and Patterns](https://amzn.to/498SRVq) +> * [Java Concurrency in Practice](https://amzn.to/4aRMruW) +> * [Learning Concurrent Programming in Scala](https://amzn.to/3UE07nV) +> * [Pattern Languages of Program Design 3](https://amzn.to/3OI1j61) +> * [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) + diff --git a/localization/fa/active-object/etc/active-object-sequence-diagram.png b/localization/fa/active-object/etc/active-object-sequence-diagram.png new file mode 100644 index 000000000000..b725d9b07b6d Binary files /dev/null and b/localization/fa/active-object/etc/active-object-sequence-diagram.png differ diff --git a/localization/fa/active-object/etc/active-object.urm.png b/localization/fa/active-object/etc/active-object.urm.png new file mode 100644 index 000000000000..c14f66144ee2 Binary files /dev/null and b/localization/fa/active-object/etc/active-object.urm.png differ diff --git a/localization/fa/active-object/etc/active-object.urm.puml b/localization/fa/active-object/etc/active-object.urm.puml new file mode 100644 index 000000000000..3fc3c8e1e921 --- /dev/null +++ b/localization/fa/active-object/etc/active-object.urm.puml @@ -0,0 +1,25 @@ +@startuml +package com.iluwatar.activeobject { + abstract class ActiveCreature { + - logger : Logger + - name : String + - requests : BlockingQueue + - thread : Thread + + ActiveCreature(name : String) + + eat() + + name() : String + + roam() + } + class App { + - creatures : Integer + - logger : Logger + + App() + + main(args : String[]) {static} + + run() + } + class Orc { + + Orc(name : String) + } +} +Orc --|> ActiveCreature +@enduml \ No newline at end of file diff --git a/localization/fa/factory/README.md b/localization/fa/factory/README.md new file mode 100644 index 000000000000..db41813464e3 --- /dev/null +++ b/localization/fa/factory/README.md @@ -0,0 +1,155 @@ +--- +title: "الگوی factory در جاوا: ساده‌سازی ایجاد اشیاء" +shortTitle: factory +description: "الگوی طراحی factory در جاوا را با مثال‌ها و توضیحات دقیق بیاموزید. یاد بگیرید چگونه با استفاده از الگوی factory کدی انعطاف‌پذیر و مقیاس‌پذیر ایجاد کنید. مناسب برای توسعه‌دهندگانی که به دنبال بهبود مهارت‌های طراحی شیءگرا هستند." +category: structural +language: fa +tag: + - Abstraction + - Encapsulation + - Gang of Four + - Instantiation + - Polymorphism +--- + +## هدف از الگوی طراحی factory + +الگوی طراحی factory در جاوا یک الگوی ساختاری است که یک رابط برای ایجاد یک شیء تعریف می‌کند اما به زیرکلاس‌ها اجازه می‌دهد نوع اشیائی را که ایجاد خواهند شد تغییر دهند. این الگو انعطاف‌پذیری و مقیاس‌پذیری را در کد شما ترویج می‌دهد. + +## توضیح دقیق الگوی factory با مثال‌های دنیای واقعی + +### مثال دنیای واقعی + +> تصور کنید در یک نانوایی انواع مختلف کیک‌ها با استفاده از الگوی طراحی factory ساخته می‌شوند. `CakeFactory` فرآیند ایجاد را مدیریت می‌کند و امکان افزودن آسان انواع جدید کیک‌ها را بدون تغییر در فرآیند اصلی فراهم می‌کند. `CakeFactory` می‌تواند انواع مختلفی از کیک‌ها مانند کیک شکلاتی، کیک وانیلی و کیک توت‌فرنگی تولید کند. به جای اینکه کارکنان نانوایی به صورت دستی مواد اولیه را انتخاب کنند و دستورالعمل‌های خاصی را برای هر نوع کیک دنبال کنند، از `CakeFactory` برای مدیریت فرآیند استفاده می‌کنند. مشتری فقط نوع کیک را درخواست می‌کند و `CakeFactory` مواد اولیه و دستورالعمل مناسب را تعیین کرده و نوع خاصی از کیک را ایجاد می‌کند. این تنظیم به نانوایی اجازه می‌دهد تا انواع جدید کیک‌ها را به راحتی اضافه کند بدون اینکه فرآیند اصلی تغییر کند، که این امر انعطاف‌پذیری و مقیاس‌پذیری را ترویج می‌دهد. + +### تعریف ویکی‌پدیا + +> الگوی factory یک شیء برای ایجاد اشیاء دیگر است – به طور رسمی، factory یک تابع یا متدی است که اشیاء با نمونه‌ها یا کلاس‌های مختلف را بازمی‌گرداند. + +### نمودار توالی + +![نمودار توالی factory](./etc/factory-sequence-diagram.png) + +## مثال برنامه‌نویسی از الگوی factory در جاوا + +تصور کنید یک کیمیاگر قصد دارد سکه‌هایی تولید کند. کیمیاگر باید بتواند هم سکه‌های طلا و هم سکه‌های مسی ایجاد کند و تغییر بین آن‌ها باید بدون تغییر در کد موجود امکان‌پذیر باشد. الگوی factory این امکان را فراهم می‌کند با ارائه یک متد ایجاد استاتیک که می‌توان آن را با پارامترهای مرتبط فراخوانی کرد. + +در جاوا، می‌توانید الگوی factory را با تعریف یک رابط `Coin` و پیاده‌سازی‌های آن `GoldCoin` و `CopperCoin` پیاده‌سازی کنید. کلاس `CoinFactory` یک متد استاتیک `getCoin` ارائه می‌دهد تا اشیاء سکه را بر اساس نوع ایجاد کند. + +```java +public interface Coin { + String getDescription(); +} +``` + +```java +public class GoldCoin implements Coin { + + static final String DESCRIPTION = "This is a gold coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +```java +public class CopperCoin implements Coin { + + static final String DESCRIPTION = "This is a copper coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +کد زیر انواع سکه‌هایی که پشتیبانی می‌شوند (`GoldCoin` و `CopperCoin`) را نشان می‌دهد. + +```java +@RequiredArgsConstructor +@Getter +public enum CoinType { + + COPPER(CopperCoin::new), + GOLD(GoldCoin::new); + + private final Supplier constructor; +} +``` + +سپس متد استاتیک `getCoin` برای ایجاد اشیاء سکه در کلاس factory `CoinFactory` کپسوله شده است. + +```java +public class CoinFactory { + + public static Coin getCoin(CoinType type) { + return type.getConstructor().get(); + } +} +``` + +اکنون، در کد کلاینت، می‌توانیم انواع مختلفی از سکه‌ها را با استفاده از کلاس factory تولید کنیم. + +```java +public static void main(String[] args) { + LOGGER.info("The alchemist begins his work."); + var coin1 = CoinFactory.getCoin(CoinType.COPPER); + var coin2 = CoinFactory.getCoin(CoinType.GOLD); + LOGGER.info(coin1.getDescription()); + LOGGER.info(coin2.getDescription()); +} +``` + +خروجی برنامه: + +``` +06:19:53.530 [main] INFO com.iluwatar.factory.App -- The alchemist begins his work. +06:19:53.533 [main] INFO com.iluwatar.factory.App -- This is a copper coin. +06:19:53.533 [main] INFO com.iluwatar.factory.App -- This is a gold coin. +``` + +## زمان استفاده از الگوی factory در جاوا + +* از الگوی طراحی factory در جاوا زمانی استفاده کنید که کلاس از قبل نوع دقیق و وابستگی‌های اشیائی که نیاز به ایجاد آن دارد را نمی‌داند. +* زمانی که یک متد یکی از چندین کلاس ممکن که یک کلاس والد مشترک دارند را بازمی‌گرداند و می‌خواهد منطق انتخاب شیء را کپسوله کند. +* این الگو معمولاً هنگام طراحی فریم‌ورک‌ها یا کتابخانه‌ها برای ارائه بهترین انعطاف‌پذیری و جداسازی از انواع کلاس‌های خاص استفاده می‌شود. + +## کاربردهای دنیای واقعی الگوی factory در جاوا + +> * [java.util.Calendar#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +> * [java.util.ResourceBundle#getBundle()](https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +> * [java.text.NumberFormat#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +> * [java.nio.charset.Charset#forName()](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +> * این مورد [java.net.URLStreamHandlerFactory#createURLStreamHandler(String)](https://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html) اشیاء singleton مختلف را بر اساس یک پروتکل بازمی‌گرداند +> * [java.util.EnumSet#of()](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of(E)) +> * [javax.xml.bind.JAXBContext#createMarshaller()](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) و متدهای مشابه دیگر. +> +> * کتابخانه‌ی JavaFX از الگوهای factory برای ایجاد کنترل‌های مختلف رابط کاربری متناسب با نیازهای محیط کاربر استفاده می‌کند. + +## مزایا و معایب الگوی factory + +### مزایا: + +> * پیاده‌سازی الگوی factory در برنامه جاوای شما، وابستگی بین پیاده‌سازی و کلاس‌هایی که استفاده می‌کند را کاهش می‌دهد. +> * از [اصل Open/Closed](https://java-design-patterns.com/principles/#open-closed-principle) پشتیبانی می‌کند، زیرا سیستم می‌تواند انواع جدیدی را بدون تغییر کد موجود معرفی کند. + +### معایب: + +> * کد می‌تواند به دلیل معرفی چندین کلاس اضافی پیچیده‌تر شود. +> * استفاده بیش از حد می‌تواند کد را کمتر خوانا کند اگر پیچیدگی ایجاد اشیاء کم یا غیرضروری باشد. + +## الگوهای طراحی مرتبط با جاوا + +> * الگوی [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): می‌توان آن را نوعی factory در نظر گرفت که با گروهی از محصولات کار می‌کند. +> * الگوی [Singleton](https://java-design-patterns.com/patterns/singleton/): اغلب همراه با factory استفاده می‌شود تا اطمینان حاصل شود که یک کلاس تنها یک نمونه دارد. +> * الگوی [Builder](https://java-design-patterns.com/patterns/builder/): ساخت یک شیء پیچیده را از نمایش آن جدا می‌کند، مشابه نحوه‌ای که factoryها مدیریت نمونه‌سازی را انجام می‌دهند. +> * الگوی [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): یک factory از محتوای غیرقابل تغییر با رابط‌های builder و factory جداگانه است. + +## منابع و اعتبارات + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0Rk5y) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG) diff --git a/localization/fa/factory/etc/factory-sequence-diagram.png b/localization/fa/factory/etc/factory-sequence-diagram.png new file mode 100644 index 000000000000..260bea92f247 Binary files /dev/null and b/localization/fa/factory/etc/factory-sequence-diagram.png differ diff --git a/localization/fr/README.md b/localization/fr/README.md new file mode 100644 index 000000000000..a593ffeeccd9 --- /dev/null +++ b/localization/fr/README.md @@ -0,0 +1,71 @@ + + +# Les patrons de conception implémentés en Java + +![Java CI with Maven](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI%20with%20Maven/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-148-orange.svg?style=flat-square)](#contributors-) + + +# Introduction + +Les patrons de conception (design patterns) sont les meilleures +pratiques formalisées qu’un programmeur peut utiliser pour résoudre +des problèmes courants lors de la conception d’une application +ou d’un système. + +Les patrons de conception peuvent accélérer le processus de +développement en fournissant des paradigmes éprouvés. + +La réutilisation de patrons de conception aide à se prémunir des problèmes subtils +qui causent des problèmes majeurs, et cette pratique augmente la lisibilité +du code pour les développeurs et architectes familiers de ces concepts. + +# Commencer + +Ce site présente des patrons de conception Java. Les solutions ont été développées +par des développeurs et architectes expérimentés de la communauté open source. +Les modèles peuvent être parcourus par leurs descriptions de haut niveau ou +en regardant leur code source. +Les exemples de code source sont bien commentés et peuvent être considérés +comme tutoriels de programmation sur la façon d’implémenter un modèle spécifique. +Nous utilisons les technologies Java open source les plus populaires et éprouvées. + +Avant de vous plonger dans le contenu, vous devriez vous familiariser avec divers +[Principes de conception de logiciels](https://java-design-patterns.com/principles/). + +Tous les modèles doivent être aussi simples que possible. +Vous devriez commencer par les principes KISS, YAGNI et +Faites La Chose La Plus Simple Qui Fonctionne. +La complexité et les modèles ne devraient être introduits +que lorsqu’ils sont nécessaires pour une extensibilité pratique. + +Une fois que vous êtes familiarisé avec ces concepts, vous pouvez commencer à explorer les +[modèles de conception disponibles](https://java-design-patterns.com/patterns/) +par n’importe laquelle des approches suivantes : + +- Recherchez un modèle spécifique par son nom. + Vous n’en trouvez pas ? Veuillez signaler un nouveau modèle [ici](https://github.com/iluwatar/java-design-patterns/issues). +- Utilisation de balises telles que `Performance`, `Gang of Four` ou `Data access`. +- Utilisation des catégories de modèles, `Creational`, `Behavioral` et autres. + +Nous espérons que vous trouverez les solutions orientées objet présentées +sur ce site utiles dans vos architectures et que vous aurez autant +de plaisir à les apprendre que nous en avons eu à les développer. + +# Comment contribuer + +Si vous souhaitez contribuer au projet, vous trouverez les informations pertinentes dans +notre [wiki développeur](https://github.com/iluwatar/java-design-patterns/wiki). +Nous vous aiderons répondrons à vos questions dans le [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns). + +# Licence + +Ce projet est concédé sous les termes de la licence MIT. + diff --git a/localization/fr/abstract-document/README.md b/localization/fr/abstract-document/README.md new file mode 100644 index 000000000000..d55c51ea8da6 --- /dev/null +++ b/localization/fr/abstract-document/README.md @@ -0,0 +1,199 @@ +--- +title: Abstract Document +category: Structural +language: fr +tag: + - Extensibility +--- + +## Intention + +Le patron de conception "Abstract Document" est un modèle de conception structurelle qui vise à fournir un moyen +cohérent de gérer les structures de données hiérarchiques et arborescentes en définissant une interface commune pour +différents types de documents. + +## Explication + +Le patron de conception "Abstract Document" permet de gérer des propriétés supplémentaires non statiques. Ce modèle +utilise le concept de traits pour assurer la sécurité des types et séparer les propriétés des différentes +classes dans un ensemble d'interfaces + +Exemple concret + +> Prenons l'exemple d'une voiture composée de plusieurs pièces. Cependant, nous ne savons pas si la voiture en question possède réellement toutes les pièces ou seulement certaines d'entre elles. Nos voitures sont dynamiques et extrêmement flexibles. + +En clair + +> Le modèle de document abstrait permet d'attacher des propriétés à des objets indépendament de ces derniers. + +Wikipedia dit + +> Un patron de conception structurelle orienté objet pour organiser des objets comme clé-valeur faiblement typés et exposer des données à l'aide de vues typées. L'objectif de ce modèle est d'atteindre un haut degré de flexibilité entre les composants +dans un langage fortement typé où de nouvelles propriétés peuvent être ajoutées à l'arbre d'objets à la volée, sans perdre le soutien de la sécurité de type. + +**Exemple de programme** + +Définissons en premier les classes de base `Document` et `AbstractDocument`. Ils font en sorte que l'objet contienne une carte(map) de propriétés et un nombre quelconque d'objets enfants. + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + ... +} +``` +Ensuite, nous définissons une enumération `Property` et un ensemble d'interfaces pour le type, le prix, le modèle et les pièces. Cela nous permet de créer une interface statique pour notre classe `Car`. + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} +``` + +Nous sommes maintenant prêts à présenter la classe `Car`. + +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` + +Enfin, voici comment nous construisons et utilisons la "voiture" dans un exemple complet. + +```java + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); + + // Constructing parts and car + // Here is our car: + // model: 300SL + // price: 10000 + // parts: + // wheel/15C/100 + // door/Lambo/300 +``` + +## Diagramme de classes + +![alt text](../../../abstract-document/etc/abstract-document.png "Abstract Document Traits and Domain") + +## Application + +Ce modèle est particulièrement utile dans les scénarios où vous avez différents types de documents qui partagent des attributs ou des comportements communs, mais qui ont également des attributs ou des comportements uniques, spécifiques à leurs types individuels. Voici quelques +Voici quelques scénarios dans lesquels le patron de conception Abstract Document peut s'appliquer : + +* Systèmes de gestion de contenu (SGC) : dans un SGC (CMS en anglais), vous pouvez avoir différents types de contenu tels que des articles, des images, des vidéos, etc. Chaque type de contenu peut avoir des attributs communs tels que la date de création, l'auteur et les balises, mais aussi des attributs spécifiques tels que les dimensions de l'image pour les images ou la durée de la vidéo pour les vidéos. + +* Systèmes de gestion de fichiers : Si vous concevez un système de gestion de fichiers dans lequel différents types de fichiers doivent être gérés; tels que des documents, des images, des fichiers audio et des répertoires, le patron "Abstract Document" peut vous aider à fournir un moyen cohérent d'accéder à des attributs tels que la taille du fichier, la date de création, etc., tout en autorisant des attributs spécifiques tels que la résolution de l'image ou la durée de l'audio. + +* Systèmes de commerce électronique ou vente en ligne : Une plateforme de commerce électronique peut avoir différents types de produits tels que des produits physiques, des téléchargements numériques et des abonnements. Chaque type peut partager des attributs communs tels que le nom, le prix et la description, tout en ayant des attributs uniques tels que le poids d'expédition pour les produits physiques ou le lien de téléchargement pour les produits numériques. + +* Systèmes de dossiers médicaux : En médécine, les dossiers des patients peuvent inclure différents types de données telles que des données démographiques, des antécédents médicaux, des résultats d'examens et des prescriptions. Le patron de conception "abstract document" peut aider à gérer des attributs partagés tels que l'ID du patient et sa date de naissance, tout en s'adaptant à des attributs spécialisés tels que les résultats d'examens ou les médicaments prescrits. + +* Gestion de la configuration : Lorsqu'il s'agit de paramètres de configuration pour des applications logicielles, il peut y avoir différents types d'éléments de configuration, chacun avec son propre ensemble d'attributs. Le patron de conception "abstract document" peut être utilisé pour gérer ces éléments de configuration tout en garantissant une manière cohérente d'accéder à leurs attributs et de les manipuler. + +* Plateformes éducatives : Les systèmes éducatifs peuvent disposer de différents types de matériel pédagogique, tels que des contenus textuels, des vidéos, des quiz et des devoirs. Les attributs communs tels que le titre, l'auteur et la date de publication peuvent être partagés, tandis que les attributs uniques tels que la durée des vidéos ou les dates d'échéance des devoirs peuvent être spécifiques à chaque type. + +* Outils de gestion de projet : Dans les applications de gestion de projet, vous pouvez avoir différents types de tâches comme les tâches à faire, les étapes et les problèmes. Le modèle de document abstrait peut être utilisé pour gérer des attributs généraux tels que le nom de la tâche et le destinataire, tout en autorisant des attributs spécifiques tels que la date du jalon ou la priorité du problème. + +L'idée principale du patron de conception Abstract Document est de fournir un moyen flexible et extensible de gérer différents types de documents ou d'entités avec des attributs partagés et distincts. En définissant une interface commune et en l'implémentant +dans les différents types de documents, vous pouvez obtenir une approche plus organisée et cohérente de la manipulation de structures de données complexes. + +## Crédits + +* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492) diff --git a/localization/fr/abstract-factory/README.md b/localization/fr/abstract-factory/README.md new file mode 100644 index 000000000000..e81c4ed2fa06 --- /dev/null +++ b/localization/fr/abstract-factory/README.md @@ -0,0 +1,227 @@ +--- +title: Abstract Factory +category: Creational +language: fr +tag: + - Gang of Four +--- + +## Également connu sous le nom de + +Kit + +## Intention + +Fournir une interface permettant de créer des familles d'objets liés ou dépendants +sans spécifier leurs classes concrètes. + +## Explication + +Exemple concret + +> Pour créer un royaume, nous avons besoin d'objets ayant un thème commun. Le royaume elfique a besoin d'un roi elfique, d'un château elfique et d'une armée elfique, tandis que le royaume orque a besoin d'un roi orque, d'un château orque et d'une armée orque. Il existe une dépendance entre les objets du royaume. + +En clair + +> Une usine d'usines ; une usine qui regroupe les usines individuelles mais liées/dépendantes sans spécifier leurs classes concrètes. + +Wikipedia dit + +> Le modèle d'usine abstraite permet d'encapsuler un groupe d'usines individuelles ayant un thème commun sans spécifier leurs classes concrètes. + +**Exemple de programme** + +Traduction de l'exemple du royaume ci-dessus. Tout d'abord, nous avons quelques interfaces et implémentations pour les objets du royaume. + +```java +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 -> ... + +``` + +Ensuite, nous avons l'abstraction et les implémentations de la fabrique de royaume. + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +Nous disposons maintenant d'une fabrique abstraite qui nous permet de créer une famille d'objets apparentés, par exemple la fabrique de royaume elfique crée un château elfique, un roi et une armée, etc. + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +Sortie du programme : + +```java +This is the elven castle! +This is the elven king! +This is the elven Army! +``` + +Maintenant, nous pouvons concevoir une fabrique pour nos différentes fabriques de royaumes. Dans cet exemple, nous avons créé `FactoryMaker`, responsable de retourner une instance de `ElfKingdomFactory` ou de `OrcKingdomFactory`. +Le client peut utiliser `FactoryMaker` pour créer la fabrique concrète désirée qui, à son tour, produira différents objets concrets (dérivés de `Army`, `King`, `Castle`). +Dans cet exemple, nous avons également utilisé une énumération pour paramétrer le type de fabrique de royaume que le client va demander. +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + default -> throw new IllegalArgumentException("KingdomType not supported."); + }; + } +} + + public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + --similar use of the orc factory + } +``` + +## Diagramme de classes + +![alt text](../../../abstract-factory/etc/abstract-factory.urm.png "Abstract Factory class diagram") + + +## Application + +Utiliser le patron de conception "abstract factory" lorsque + +* Le système doit être indépendant de la manière dont ses produits sont créés, composés et représentés. +* Le système doit être configuré avec l'une des multiples familles de produits. +* La famille d'objets produits apparentés est conçue pour être utilisée ensemble, et vous devez faire respecter cette contrainte +* Vous voulez fournir une bibliothèque de classes de produits, et vous voulez révéler seulement leurs interfaces, pas leurs implémentations. +* La durée de vie de la dépendance est conceptuellement plus courte que la durée de vie du consommateur. +* Vous avez besoin d'une valeur d'exécution pour construire une dépendance particulière. +* Vous voulez décider quel produit appeler à partir d'une famille au moment de l'exécution. +* Vous devez fournir un ou plusieurs paramètres qui ne sont connus qu'au moment de l'exécution avant de pouvoir résoudre une dépendance. +* Lorsque vous avez besoin d'une cohérence entre les produits. +* Vous ne voulez pas modifier le code existant lorsque vous ajoutez de nouveaux produits ou de nouvelles familles de produits au programme. + +Exemples de cas d'utilisation + +* Choisir d'appeler l'implémentation appropriée de FileSystemAcmeService ou DatabaseAcmeService ou NetworkAcmeService au moment de l'exécution. +* L'écriture de cas de tests unitaires devient beaucoup plus facile. +* Outils d'interface utilisateur pour différents systèmes d'exploitation. + +## Conséquences + +* L'injection de dépendances en Java masque les dépendances des classes de service qui peuvent entraîner des erreurs d'exécution qui auraient été détectées au moment de la compilation. +* Si le modèle est idéal pour la création d'objets prédéfinis, l'ajout de nouveaux objets peut s'avérer difficile. +* Le code devient plus compliqué qu'il ne devrait l'être car un grand nombre de nouvelles interfaces et classes sont introduites en même temps que le modèle. + +## Tutoriels + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## Utilisations connues + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## Modèles apparentés ou similaire (de la même catégorie) + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## Crédits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/fr/active-object/README.md b/localization/fr/active-object/README.md new file mode 100644 index 000000000000..0eae4af29c8b --- /dev/null +++ b/localization/fr/active-object/README.md @@ -0,0 +1,128 @@ +--- +title: Active Object +category: Concurrency +language: fr +tag: + - Performance +--- + + +## Intention + +Le patron de conception des "active object" actifs dissocie l'exécution et l'invocation des méthodes pour les objets qui résident chacun dans leur fil de contrôle. L'objectif est d'introduire la concurrence en utilisant l'invocation asynchrone des méthodes et un planificateur pour traiter les demandes. + +## Explication + +La classe qui met en œuvre le patron "active object", contiendra un mécanisme d'auto-synchronisation sans utiliser de méthodes "synchronisées". + +**Exemple concret** + +> Les orques sont connus pour leur caractère sauvage et leur âme indomptable. Il semble qu'ils aient leur propre système de contrôle basé sur leur comportement antérieur. + +Pour mettre en œuvre une créature qui possède son propre mécanisme de contrôle et qui n'expose que son API et non l'exécution elle-même, nous pouvons utiliser le patron "active-object". + + +**Exemple de programme** + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +Nous pouvons constater que toute classe qui hérite de la classe ActiveCreature aura son propre fil de contrôle pour invoquer et exécuter les méthodes. + +Par exemple, la classe Orc : + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` + +Désormais, nous pouvons créer plusieurs créatures telles que des orques, leur dire de manger et d'errer, et elles s'exécuteront selon leur propre fil(mechanisme) de contrôle : + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## Diagramme de classe + +![alt text](../../../active-object/etc/active-object.urm.png "Active Object class diagram") + +## Tutoriels + +* [Android and Java Concurrency: The Active Object Pattern](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) \ No newline at end of file diff --git a/localization/fr/acyclic-visitore/README.md b/localization/fr/acyclic-visitore/README.md new file mode 100644 index 000000000000..7e5b27e256ce --- /dev/null +++ b/localization/fr/acyclic-visitore/README.md @@ -0,0 +1,162 @@ +--- +title: Acyclic Visitor +category: Behavioral +language: fr +tag: + - Extensibility +--- + +## Intention + +Permettre l'ajout de nouvelles fonctions à des hiérarchies de classes existantes sans affecter ces hiérarchies et sans +créer de cycles de dépendance gênants inhérents au pqtron de conception GoF visitor. + +## Explication + +Exemple concret + +> Nous disposons d'une hiérarchie de classes de modems. Les modems de cette hiérarchie doivent être visités +> par un algorithme externe basé sur des critères de filtrage (s'agit-il d'un modem compatible Unix ou DOS). + +En clair + +> Le visiteur acyclique permet d'ajouter des fonctions à des hiérarchies de classes existantes sans modifier ces dernières. + +[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) dit + +> Le modèle du visiteur acyclique permet d'ajouter de nouvelles fonctions aux hiérarchies de classes existantes +> sans affecter ces hiérarchies et sans créer les cycles de dépendance inhérents au patron de conception GangOfFour visitor. + +**Exemple de Programme** + +Ci-dessous la hierarchie `Modem`. + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + +Ensuite, nous introduisons la hiérarchie `ModemVisitor`. + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + ... + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + ... + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +Enfin, voici les visitors en action. + +```java + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + var zoom = new Zoom(); + var hayes = new Hayes(); + hayes.accept(conDos); + zoom.accept(conDos); + hayes.accept(conUnix); + zoom.accept(conUnix); +``` + +Sortie du programme : + +``` + // Hayes modem used with Dos configurator. + // Zoom modem used with Dos configurator. + // Only HayesVisitor is allowed to visit Hayes modem + // Zoom modem used with Unix configurator. +``` + +## Diagramme de classes + +![alt text](../../../acyclic-visitor/etc/acyclic-visitor.png "Acyclic Visitor") + +## Application + +Ce patron de conception peut être utilisé: + +* Pour ajouter ne nouvelle fonction à une hiérarchie existante sans avoir à modifier ou à affecter cette hiérarchie. +* Lorsqu'il existe des fonctions qui opèrent sur une hiérarchie, mais qui n'appartiennent pas à la hiérarchie elle-même. Par exemple, le problème ConfigureForDOS / ConfigureForUnix / ConfigureForX. +* Lorsque vous devez éffectuer des opérations très différentes sur un objet en fonction de son type. +* Lorsque la hiérarchie des classes visitées sera fréquemment étendue avec de nouveaux dérivés de la classe Element. +*Lorsque la recompilation, l'interconnexion, le réessai ou la redistribution des dérivés de Element sont très coûteux. + +## Tutoriel + +* [Acyclic Visitor Pattern Example](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) + +## Consequences + +Le bon côté: + +* Pas de cycles de dépendance entre les hiérarchies de classes. +* Il n'est pas nécessaire de recompiler tous les visiteurs si un nouveau visiteur est ajouté. +* Ne provoque pas d'échec de compilation chez les visiteurs existants si la hiérarchie des classes a un nouveau membre. + +Le mauvais : + +* viole le [principe de substitution de Liskov](https://java-design-patterns.com/principles/#liskov-substitution-principle) en montrant qu'il peut accepter tous les visiteurs alors qu'il ne s'intéresse en réalité qu'à certains d'entre eux. +* Une hiérarchie parallèle de visiteurs doit être créée pour tous les membres de la hiérarchie des classes visitables. + +## Patron de conception associé + +* [Pqtron de conception Visitor](https://java-design-patterns.com/patterns/visitor/) + +## Crédits + +* [Acyclic Visitor by Robert C. Martin](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor in WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) diff --git a/localization/fr/adapter/README.md b/localization/fr/adapter/README.md new file mode 100644 index 000000000000..dfd85090af9f --- /dev/null +++ b/localization/fr/adapter/README.md @@ -0,0 +1,137 @@ +--- +title: Adapter +category: Structural +language: fr +tag: + - Gang of Four +--- + +## Également connu sous le nom de +Wrapper + +## Intention +Convertir l'interface d'une classe en une autre interface attendue par les clients. Adapter permet à des classes de travailler ensemble +qui ne pourraient pas fonctionner autrement en raison d'interfaces incompatibles. + +## Explication + +Exemple concrêt + +> Supposons que vous avez des photos sur votre carte mémoire et vous devez les transférer sur votre ordinateur. Pour ce faire, vous avez besoin d'un adaptateur qui est compatible aux ports de votre ordinateur pour vous permettre de connecter votre carte memoire à l'ordinateur. dans ce cas le lecteur de carte est un adapteur. +> Un autre exemple serait le fameux adaptateur électrique ; une fiche à trois branches ne peut pas être branchée sur une prise à deux branches, elle doit utiliser un adaptateur électrique qui la rend compatible avec les prises à deux branches. +> Un autre exemple serait celui d'un traducteur qui traduirait les mots prononcés par une personne à une autre. + +En clair + +> Le patron adapter permet d'envelopper un objet autrement incompatible dans un adaptateur afin de le rendre compatible avec une autre classe. + +Wikipedia dit + +> En génie logiciel, le pattron de conception adapter est un pattron de conception logicielle qui permet d'utiliser l'interface d'une classe existante comme une autre interface. Il est souvent utilisé pour faire fonctionner des classes existantes avec d'autres sans modifier leur code source. + +**Exemple de programme** + +Prenons l'exemple d'un capitaine qui ne peut utiliser que des bateaux à rames et qui ne peut pas du tout naviguer. + +Tout d'abord, nous avons les interfaces `RowingBoat` et `FishingBoat` + +```java +public interface RowingBoat { + void row(); +} + +@Slf4j +public class FishingBoat { + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } +} +``` + +Et le capitaine s'attend à ce qu'une implémentation de l'interface `RowingBoat` soit capable de se déplacer + +```java +public class Captain { + + private final RowingBoat rowingBoat; + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +Supposons maintenant que les pirates arrivent et que notre capitaine doive s'échapper, mais qu'il ne dispose que d'un bateau de pêche. Nous devons créer un adaptateur qui permette au capitaine de faire fonctionner le bateau de pêche avec ses compétences de rameur. + +```java +@Slf4j +public class FishingBoatAdapter implements RowingBoat { + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} +``` + +Et maintenant, `Captain` peut utiliser le `FishingBoat` pour échapper aux pirates. + +```java +var captain = new Captain(new FishingBoatAdapter()); +captain.row(); +``` + +## Diagramme des classes +![alt text](../../../adapter/etc/adapter.urm.png "Adapter class diagram") + +## Application +Utiliser le pattron de conception adapter lorsque + +* Vous souhaitez utiliser une classe existante, mais son interface ne correspond pas à celle dont vous avez besoin +* Vous souhaitez créer une classe réutilisable qui coopère avec des classes non liées ou imprévues, c'est-à-dire des classes qui n'ont pas nécessairement d'interfaces compatibles. +* Vous devez utiliser plusieurs sous-classes existantes, mais il n'est pas pratique d'adapter leur interface en les sous-classant toutes. Un adaptateur d'objet peut adapter l'interface de sa classe mère. +* La plupart des applications utilisant des bibliothèques tierces utilisent des adaptateurs comme couche intermédiaire entre l'application et la bibliothèque tierce afin de découpler l'application de la bibliothèque. Si une autre bibliothèque doit être utilisée, il suffit de créer un adaptateur pour la nouvelle bibliothèque sans avoir à modifier le code de l'application. + +## Tutoriels + +* [Dzone](https://dzone.com/articles/adapter-design-pattern-in-java) +* [Refactoring Guru](https://refactoring.guru/design-patterns/adapter/java/example) +* [Baeldung](https://www.baeldung.com/java-adapter-pattern) + +## Conséquences +Les adaptateurs de classe et d'objet présentent différents avantages. Un adaptateur de classe : + +* Adapte l'adaptateur à la cible en s'engageant dans une classe concrète d'adaptateur. Par conséquent, un adaptateur de classe ne fonctionnera pas si nous voulons adapter une classe et toutes ses sous-classes. +* Permet à l'adaptateur de surcharger certains comportements de l'adaptaté puisque l'adaptateur est une sous-classe de l'adaptaté. +* N'introduit qu'un seul objet, et aucune indirection de pointeur supplémentaire n'est nécessaire pour accéder à l'adaptateur. + +Un adaptateur d'objet : + +* Permet à un seul adaptateur de travailler avec de nombreux adaptatés, c'est-à-dire l'adaptateur lui-même et toutes ses sous-classes (le cas échéant). L'adaptateur peut également ajouter des fonctionnalités à tous les adaptatés en même temps. +* Rend plus difficile la modification du comportement de l'adapté. Il faudra créer des sous classes de l'adapta et faire en sorte que l'adaptateur se réfère à la sous-classe plutôt qu'à l'adapté lui-même. + + +## Utilisations connues + +* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +* [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +* [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + + +## Crédits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/fr/aggregator-microservices/README.md b/localization/fr/aggregator-microservices/README.md new file mode 100644 index 000000000000..ed27ca451659 --- /dev/null +++ b/localization/fr/aggregator-microservices/README.md @@ -0,0 +1,106 @@ +--- +title: Aggregator Microservices +category: Architectural +language: fr +tag: +- Cloud distributed +- Decoupling +- Microservices +--- + +## Intention + +L'utilisateur fait un appel unique au service d'agrégation, et ce dernier appelle ensuite chaque microservice approprié. + +## Explication + +Exemple concret + +> Notre marché en ligne a besoin d'informations sur les produits et leur stock actuel. Elle fait appel à un service +> d'agrégation qui, à son tour, appelle le microservice d'information sur les produits et le microservice d'inventaire +> des produits et renvoie les informations combinées. + +En clair + +> Aggregator Microservice collecte des éléments de données provenant de divers microservices et renvoie un agrégat pour traitement.. + +Stack Overflow dit + +> Aggregator Microservice invoque plusieurs services pour réaliser la fonctionnalité requise par l'application. + +**Exemple de programme** + +Commençons par le modèle de données. Voici notre `Product`. + +```java +public class Product { + private String title; + private int productInventories; + // getters and setters -> + ... +} +``` + +Ensuite, nous pouvons présenter notre microservice `Aggregator`. Il contient les clients `ProductInformationClient` et +`ProductInventoryClient` pour appeler les microservices respectifs. + +```java +@RestController +public class Aggregator { + + @Resource + private ProductInformationClient informationClient; + + @Resource + private ProductInventoryClient inventoryClient; + + @RequestMapping(path = "/product", method = RequestMethod.GET) + public Product getProduct() { + + var product = new Product(); + var productTitle = informationClient.getProductTitle(); + var productInventory = inventoryClient.getProductInventories(); + + //Fallback to error message + product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed")); + + //Fallback to default error inventory + product.setProductInventories(requireNonNullElse(productInventory, -1)); + + return product; + } +} +``` + +Voici l'essentiel de la mise en œuvre du microservice d'information. Le microservice dInventory est similaire, il renvoie simplement l'inventaire. + +```java +@RestController +public class InformationController { + @RequestMapping(value = "/information", method = RequestMethod.GET) + public String getProductTitle() { + return "The Product Title."; + } +} +``` + +L'appel à notre API REST `Aggregator` renvoie les informations sur le produit. + +```bash +curl http://localhost:50004/product +{"title":"The Product Title.","productInventories":5} +``` + +## Class diagram + +![alt text](../../../aggregator-microservices/aggregator-service/etc/aggregator-service.png "Aggregator Microservice") + +## Application + +Utilisez le modèle de microservices agrégateur lorsque vous avez besoin d'une API unifiée pour différents microservices, quel que soit l'appareil client. + +## Crédits + +* [Microservice Design Patterns](http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/) +* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=8b4e570267bc5fb8b8189917b461dc60) +* [Architectural Patterns: Uncover essential patterns in the most indispensable realm of enterprise architecture](https://www.amazon.com/gp/product/B077T7V8RC/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B077T7V8RC&linkId=c34d204bfe1b277914b420189f09c1a4) diff --git a/localization/fr/ambassador/README.md b/localization/fr/ambassador/README.md new file mode 100644 index 000000000000..d0659a826919 --- /dev/null +++ b/localization/fr/ambassador/README.md @@ -0,0 +1,204 @@ +--- +title: Ambassador +category: Structural +language: fr +tag: + - Decoupling + - Cloud distributed +--- + +## Intention + +Fournir une instance de service d'assistance à un client et décharger une fonctionnalité commune d'une ressource partagée. + +## Explication + +Exemple concret + +> Un service distant a de nombreux clients qui accèdent à une fonction qu'il fournit. Le service est une application +> ancienne qu'il est impossible de mettre à jour. Le grand nombre de requêtes des utilisateurs entraîne des problèmes de +> connectivité. De nouvelles règles relatives à la fréquence des requêtes doivent être mises en œuvre, ainsi que des +> contrôles de latence et une journalisation côté client. + +En clair + +>Avec le modèle Ambassador, nous pouvons mettre en œuvre des interrogations moins fréquentes de la part des clients, +> ainsi que des contrôles de latence et une journalisation. + +La documentation de Microsoft indique que + +> Un service ambassadeur peut être considéré comme un mandataire hors processus qui se trouve au même endroit que le client. +> Ce pattron peut être utile pour décharger les tâches courantes de connectivité client telles que la surveillance, +> la journalisation, le routage, la sécurité (comme TLS) et les modèles de résilience d'une manière indépendante du langage. +> Il est souvent utilisé avec des applications anciennes ou d'autres applications difficiles à modifier, afin d'étendre +> leurs capacités de mise en réseau. Il peut également permettre à une équipe spécialisée de mettre en œuvre ces fonctionnalités. + +**Exemple de programme** + +En gardant en mémoire l'introduction ci-dessus, nous reproduirons cette fonctionnalité dans ce exemple. Nous avons une interface +implémentée par un service distant aussi bien que service ambassadeur +We have an interface implemented +by the remote service as well as the ambassador service : + +```java +interface RemoteServiceInterface { + long doRemoteFunction(int value) throws Exception; +} +``` + +Un sercive distant représenté comme un singleton. + +```java +@Slf4j +public class RemoteService implements RemoteServiceInterface { + private static RemoteService service = null; + + static synchronized RemoteService getRemoteService() { + if (service == null) { + service = new RemoteService(); + } + return service; + } + + private RemoteService() {} + + @Override + public long doRemoteFunction(int value) { + long waitTime = (long) Math.floor(Math.random() * 1000); + + try { + sleep(waitTime); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep interrupted", e); + } + + return waitTime >= 200 ? value * 10 : -1; + } +} +``` + +Un service ambassadeur ajoute des fonctionnalités supplémentaires à l'instar de la journalisation et des contrôles de latence + +```java +@Slf4j +public class ServiceAmbassador implements RemoteServiceInterface { + private static final int RETRIES = 3; + private static final int DELAY_MS = 3000; + + ServiceAmbassador() { + } + + @Override + public long doRemoteFunction(int value) { + return safeCall(value); + } + + private long checkLatency(int value) { + var startTime = System.currentTimeMillis(); + var result = RemoteService.getRemoteService().doRemoteFunction(value); + var timeTaken = System.currentTimeMillis() - startTime; + + LOGGER.info("Time taken (ms): " + timeTaken); + return result; + } + + private long safeCall(int value) { + var retries = 0; + var result = (long) FAILURE; + + for (int i = 0; i < RETRIES; i++) { + if (retries >= RETRIES) { + return FAILURE; + } + + if ((result = checkLatency(value)) == FAILURE) { + LOGGER.info("Failed to reach remote: (" + (i + 1) + ")"); + retries++; + try { + sleep(DELAY_MS); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep state interrupted", e); + } + } else { + break; + } + } + return result; + } +} +``` + +Un client dispose d'un service ambassadeur local utilisé pour interagir avec le service distant : + +```java +@Slf4j +public class Client { + private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador(); + + long useService(int value) { + var result = serviceAmbassador.doRemoteFunction(value); + LOGGER.info("Service result: " + result); + return result; + } +} +``` + +Voici deux clients utilisant le service. + +```java +public class App { + public static void main(String[] args) { + var host1 = new Client(); + var host2 = new Client(); + host1.useService(12); + host2.useService(73); + } +} +``` + +Ci-déssous la sortie du programme : + +```java +Time taken (ms): 111 +Service result: 120 +Time taken (ms): 931 +Failed to reach remote: (1) +Time taken (ms): 665 +Failed to reach remote: (2) +Time taken (ms): 538 +Failed to reach remote: (3) +Service result: -1 +``` + +## Class diagram + +![alt text](../../../ambassador/etc/ambassador.urm.png "Ambassador class diagram") + +## Application + +* Le pattron ambassador s'applique lorsque l'on travaille avec un service distant existant qui ne peut pas être modifié ou +qui serait extrêmement difficile à modifier. Les fonctions de connectivité peuvent être mises en œuvre sur le client sans +qu'il soit nécessaire d'apporter des modifications au service distant. +* Ambassador fournit une interface locale pour un service distant. +* Ambassador assure la journalisation, la coupure de circuit, les tentatives et la sécurité sur le client. + +## Cas d'utilisation typique + +* Contrôler l'accès à un autre objet +* Mise en œuvre de la journalisation +* Mettre en œuvre d'un coupe-circuit +* Décharger les tâches de service à distance +* Faciliter la connexion au réseau + +## Utilisations connues + +* [Kubernetes-native API gateway for microservices](https://github.com/datawire/ambassador) + +## Modèles connexes + +* [Proxy](https://java-design-patterns.com/patterns/proxy/) + +## Crédits + +* [Ambassador pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador) +* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://www.amazon.com/s?k=designing+distributed+systems&sprefix=designing+distri%2Caps%2C156&linkCode=ll2&tag=javadesignpat-20&linkId=a12581e625462f9038557b01794e5341&language=en_US&ref_=as_li_ss_tl) diff --git a/localization/fr/anti-corruption-layer/README.md b/localization/fr/anti-corruption-layer/README.md new file mode 100644 index 000000000000..46a62ae1ffe3 --- /dev/null +++ b/localization/fr/anti-corruption-layer/README.md @@ -0,0 +1,180 @@ +--- +title: "Patron de conception Couche Anti-Corruption en Java : Assurer l'intégrité du système face aux systèmes hérités" +shortTitle: Couche Anti-Corruption +description: "Découvrez comment le patron de conception de la Couche Anti-Corruption (Anti-Corruption Layer Pattern) aide à découpler les sous-systèmes, à prévenir la corruption des données et à faciliter une intégration fluide dans les applications Java." +category: Integration +language: fr +tag: + - Architecture + - Decoupling + - Integration + - Isolation + - Layered architecture + - Migration + - Modernization + - Refactoring + - Wrapping +--- + +## Aussi connu sous le nom de + +* ACL +* Couche d'interface +* Couche de traduction + +## Intention du modèle de conception de la couche anti-corruption + +La couche anti-corruption (ACL) est un patron de conception essentiel dans le développement Java, en particulier pour l'intégration des systèmes et le maintien de l'intégrité des données. Implémentez une couche de façade ou d'adaptateur entre différents sous-systèmes qui ne partagent pas la même sémantique. Elle traduit entre différents formats de données et systèmes, garantissant que l'intégration entre les systèmes ne conduit pas à une corruption de la logique métier ou à une perte d'intégrité des données. + +## Explication détaillée du patron de conception Couche Anti-Corruption avec des exemples concrets + +Exemple concret + +> Cet exemple montre comment la couche anti-corruption garantit une intégration fluide entre les systèmes hérités et les plateformes modernes, essentiel pour maintenir l'intégrité de la logique métier lors de la migration du système. +> +> Imaginez une grande entreprise de vente au détail qui passe d'un ancien logiciel de gestion des stocks à une nouvelle plateforme moderne. Le système hérité est utilisé depuis des décennies et contient des règles métier complexes et des formats de données incompatibles avec le nouveau système. Au lieu de connecter directement le nouveau système à l'ancien, l'entreprise implémente une couche anti-corruption (ACL). +> +> L'ACL agit comme un médiateur, traduisant et adaptant les données entre les deux systèmes. Lorsque le nouveau système demande des données d'inventaire, l'ACL traduit la requête dans un format compréhensible par le système hérité, récupère les données, puis les traduit à nouveau dans un format adapté au nouveau système. Cette approche garantit que le nouveau système reste indépendant des complexités du système hérité, évitant ainsi la corruption des données et de la logique métier tout en facilitant une transition en douceur. + +En termes simples + +> Le patron de conception Couche Anti-Corruption protège un système des complexités et des changements des systèmes externes en fournissant une couche de traduction intermédiaire. + +[La documentation de Microsoft](https://learn.microsoft.com/fr-fr/azure/architecture/patterns/anti-corruption-layer) dit + +> Implémentez une couche de façade ou d’adaptateur entre différents sous-systèmes qui ne partagent pas la même sémantique. Cette couche traduit les requêtes qu’un sous-système envoie à l’autre sous-système. Utilisez ce modèle pour vous assurer que la conception d’une application n’est pas limitée par les dépendances aux sous-systèmes externes. Ce modèle a d’abord été décrit par Eric Evans dans Domain-Driven Design (Conception orientée domaine). + +## Exemple programmatique du patron de conception de Couche Anti-Corruption en Java + +Le modèle ACL en Java fournit une couche intermédiaire qui traduit les formats de données, garantissant que l'intégration entre différents systèmes ne conduit pas à une corruption des données. + +Voici 2 systèmes de commande de magasin : `Legacy` et `Modern`. + +Ces systèmes ont des modèles de domaine différents et doivent fonctionner simultanément. Comme ils travaillent de manière indépendante, les commandes peuvent provenir soit du système `Legacy`, soit du système `Modern`. Par conséquent, le système qui reçoit la commande `orderLegacy` doit vérifier si cette commande est valide et non présente dans l'autre système. Ensuite, il peut placer la commande `orderLegacy` dans son propre système. + +Mais pour cela, le système doit connaître le modèle de domaine de l'autre système et pour éviter cela, la couche anti-corruption (ACL) est introduite. L'ACL est une couche qui traduit le modèle de domaine du système `Legacy` en celui du système `Modern` et inversement. De plus, elle masque toutes les autres opérations avec l'autre système, découplant les systèmes. + +Modèle de domaine du système `Legacy` : + +```java +public class LegacyOrder { + private String id; + private String customer; + private String item; + private String qty; + private String price; +} +``` + +Modèle de domaine du système `Modern` : + +```java +public class ModernOrder { + private String id; + private Customer customer; + + private Shipment shipment; + + private String extra; +} + +public class Customer { + private String address; +} + +public class Shipment { + private String item; + private String qty; + private String price; +} +``` + +Couche anti-corruption : + +```java +public class AntiCorruptionLayer { + + @Autowired + private ModernShop modernShop; + + @Autowired + private LegacyShop legacyShop; + + public Optional findOrderInModernSystem(String id) { + return modernShop.findOrder(id).map(o -> /* map to legacyOrder*/); + } + + public Optional findOrderInLegacySystem(String id) { + return legacyShop.findOrder(id).map(o -> /* map to modernOrder*/); + } + +} +``` + +La connexion entre les systèmes. Chaque fois que le système `Legacy` ou `Modern` doit communiquer avec l'autre, l'ACL doit être utilisée pour éviter de corrompre le modèle de domaine actuel. L'exemple ci-dessous montre comment le système `Legacy` passe une commande avec une validation du système `Modern`. + +```java +public class LegacyShop { + @Autowired + private AntiCorruptionLayer acl; + + public void placeOrder(LegacyOrder legacyOrder) throws ShopException { + + String id = legacyOrder.getId(); + + Optional orderInModernSystem = acl.findOrderInModernSystem(id); + + if (orderInModernSystem.isPresent()) { + // la commande est déjà dans le système moderne + } else { + // passer la commande dans le système actuel + } + } +} +``` +## Quand utiliser le patron de conception Couche Anti-Corruption en Java + +Utilisez ce modèle lorsque : + +* Une migration est prévue en plusieurs étapes, mais l'intégration entre les nouveaux et les anciens systèmes doit être maintenue +* Deux ou plusieurs sous-systèmes ont une sémantique différentes, mais doivent tout de même communiquer +* Lors de l'intégration avec des systèmes hérités ou des systèmes externes où une intégration directe pourrait polluer le modèle de domaine du nouveau système +* Dans des scénarios où différents sous-systèmes au sein d'un système plus large utilisent différents formats ou structures de données +* Lorsqu'il est nécessaire de garantir un découplage lâche entre différents sous-systèmes ou services externes pour faciliter la maintenance et la scalabilité + +## Tutoriels sur le patron de conception Couche Anti-Corruption en Java + +* [Couche Anti-Corruption](https://learn.microsoft.com/fr-fr/azure/architecture/patterns/anti-corruption-layer) +* [Patron de conception Couche Anti-Corruption](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/acl.html) + +## Applications concrètes du modèle de couche anti-corruption en Java + +* Architectures microservices où les services individuels doivent communiquer sans être étroitement couplés aux schémas de données des autres +* Intégration des systèmes d'entreprise, notamment lors de l'intégration des systèmes modernes avec des systèmes hérités +* Dans des contextes délimités au sein de la Domain-Driven Design (DDD) pour maintenir l'intégrité d'un modèle de domaine lors de l'interaction avec des systèmes ou sous-systèmes externes + +## Avantages et compromis du modèle de couche anti-corruption + +Avantages : + +* Protège l'intégrité du modèle de domaine en fournissant une frontière claire +* Favorise le découplage lâche entre les systèmes, rendant le système plus résilient aux changements des systèmes externes +* Facilite un code plus propre et plus facile à maintenir en isolant le code d'intégration de la logique métier + +Compromis : + +* Introduit une complexité supplémentaire et un potentiel de surcharge de performance en raison du processus de traduction +* Nécessite un effort supplémentaire dans la conception et la mise en œuvre pour s'assurer que la couche est efficace sans devenir un goulet d'étranglement +* Peut entraîner une duplication des modèles s'il n'est pas géré avec soin + +## Patron de conception Java associés + +* [Adaptateur (Adapter)](https://java-design-patterns.com/patterns/adapter/): La couche anti-corruption peut être implémentée en utilisant le modèle Adaptateur pour traduire entre différents formats ou structures de données +* [Façade](https://java-design-patterns.com/patterns/facade/): La couche anti-corruption peut être vue comme une forme spécialisée du modèle Façade utilisée pour isoler différents sous-systèmes +* [Passerelle (Gateway)](https://java-design-patterns.com/patterns/gateway/): La couche anti-corruption peut être utilisée comme une passerelle vers des systèmes externes pour fournir une interface unifiée + +## Références et Crédits + +* [Domain-Driven Design : Résoudre la complexité au cœur du logiciel](https://amzn.to/3vptcJz) +* [Implémentation du Domain-Driven Design](https://amzn.to/3ISOSRA) +* [Patterns of Enterprise Application Architecture (Modèles d'architecture des applications d'entreprise)](https://amzn.to/3WfKBPR) diff --git a/localization/fr/api-gateway/README.md b/localization/fr/api-gateway/README.md new file mode 100644 index 000000000000..70e513e00e1f --- /dev/null +++ b/localization/fr/api-gateway/README.md @@ -0,0 +1,164 @@ +--- +title: API Gateway +category: Architectural +language: fr +tag: + - Cloud distributed + - Decoupling + - Microservices +--- + +## Intention + +Regrouper les appels aux microservices en un seul endroit, la passerelle API. +L'utilisateur fait un seul appel à la passerelle API, qui appelle ensuite chaque microservice concerné. + +## Explication + +Avec les pattrons microservices, un client peut avoir besoin de données provenant de plusieurs microservices différents. +Si le client appelait directement chaque microservice, cela pourrait contribuer à allonger les temps de chargement, +puisque le client devrait faire une requete réseau pour chaque microservice appelé. En outre, le fait que le client appelle +chaque microservice directement le lie à ce microservice - si les implémentations internes des microservices changent +(par exemple, si deux microservices sont combinés) ou si l'emplacement (hôte et port) d'un microservice change, +alors chaque client qui utilise ces microservices doit être informé de l'existence de ce microservice. + +L'objectif du pattron API Gateway est d'atténuer certains de ces problèmes. Dans le pattron API Gateway une entité supplémentaire +(la passerelle API) est placée entre le client et les microservices. Le rôle de la passerelle API est d'agréger les appels aux microservices. Plutôt que le client +appelle chaque microservice individuellement, le client appelle la passerelle API une seule fois. +La passerelle API appelle alors chacun des microservices dont le client a besoin. + +Exemple concret + +> Nous mettons en œuvre des microservices et un pattron API Gateway pour un site de commerce en ligne. +> Dans ce système la passerelle API fait des appels aux microservices Image et Prix. + +En clair + +> Pour un système mis en œuvre à l'aide d'une architecture de microservices, +> API Gateway est le point d'entrée unique qui regroupe les appels aux différents microservices. + +Wikipedia dit + +> La passerelle API est un serveur qui agit comme un front-end API, reçoit les requêtes API, applique des politiques de +> limitation et de sécurité, transmet les requêtes au service back-end et renvoie la réponse au demandeur. +> Une passerelle comprend souvent un moteur de transformation pour orchestrer et modifier les demandes et les réponses à la volée. +> Une passerelle peut également fournir des fonctionnalités telles que la collecte de données analytiques et la mise en cache. +> La passerelle peut fournir des fonctionnalités pour prendre en charge l'authentification, l'autorisation, la sécurité, +> l'audit et la conformité réglementaire. + +**Exemple de programme** + +Cette mise en œuvre montre à quoi pourrait ressembler le pattron de conception API Gateway pour un site de commerce électronique. +La passerelle `ApiGateway` fait des appels aux microservices Image et Price en utilisant respectivement `ImageClientImpl` et `PriceClientImpl` respectivement. +Les clients qui consultent le site sur un ordinateur de bureau peuvent voir à la fois les informations sur le prix et l'image d'un produit. +Les clients qui consultent le site sur un ordinateur de bureau peuvent voir à la fois des informations sur le prix et l'image d'un produit, +donc la passerelle appelle les deux microservices et regroupe les données dans le modèle `DesktopProduct`. +Cependant, les utilisateurs mobiles ne voient que les informations sur le prix ; Ils ne voient pas l'image du produit. +Pour les utilisateurs mobiles, la passerelle `ApiGateway` ne récupère que les informations de prix, qu'elle utilise pour remplir le modèle `MobileProduct`. + +Voici l'implémentation du microservice Image. + +```java +public interface ImageClient { + String getImagePath(); +} + +public class ImageClientImpl implements ImageClient { + @Override + public String getImagePath() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50005/image-path")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +Voici l'implémentation du microservice Price. + +```java +public interface PriceClient { + String getPrice(); +} + +public class PriceClientImpl implements PriceClient { + + @Override + public String getPrice() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50006/price")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +Nous voyons ici comment API Gateway fait correspondre les demandes aux microservices. + +```java +public class ApiGateway { + + @Resource + private ImageClient imageClient; + + @Resource + private PriceClient priceClient; + + @RequestMapping(path = "/desktop", method = RequestMethod.GET) + public DesktopProduct getProductDesktop() { + var desktopProduct = new DesktopProduct(); + desktopProduct.setImagePath(imageClient.getImagePath()); + desktopProduct.setPrice(priceClient.getPrice()); + return desktopProduct; + } + + @RequestMapping(path = "/mobile", method = RequestMethod.GET) + public MobileProduct getProductMobile() { + var mobileProduct = new MobileProduct(); + mobileProduct.setPrice(priceClient.getPrice()); + return mobileProduct; + } +} +``` + +## Diagramme de clqsses +![alt text](../../../api-gateway/etc/api-gateway.png "API Gateway") + +## Application + +Utilisez le pattron de passerelle API lorsque + +* Vous utilisez une architecture de microservices et avez besoin d'un point d'agrégation unique pour vos appels de microservices. + +## Tutoriels + +* [Exploring the New Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway) +* [Spring Cloud - Gateway](https://www.tutorialspoint.com/spring_cloud/spring_cloud_gateway.htm) +* [Getting Started With Spring Cloud Gateway](https://dzone.com/articles/getting-started-with-spring-cloud-gateway) + +## Crédits + +* [microservices.io - API Gateway](http://microservices.io/patterns/apigateway.html) +* [NGINX - Building Microservices: Using an API Gateway](https://www.nginx.com/blog/building-microservices-using-an-api-gateway/) +* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=ac7b6a57f866ac006a309d9086e8cfbd) +* [Building Microservices: Designing Fine-Grained Systems](https://www.amazon.com/gp/product/1491950358/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1491950358&linkId=4c95ca9831e05e3f0dadb08841d77bf1) diff --git a/localization/fr/arrange-act-assert/README.md b/localization/fr/arrange-act-assert/README.md new file mode 100644 index 000000000000..f254878cb543 --- /dev/null +++ b/localization/fr/arrange-act-assert/README.md @@ -0,0 +1,140 @@ +--- +title: Arrange/Act/Assert +category: Idiom +language: fr +tag: + - Testing +--- + +## Aussi connu sous le nom de + +Given/When/Then + +## Intention + +Arrange/Act/Assert (AAA) est un pattron d'organisation des tests unitaires. +Il décompose les tests en trois étapes claires et distinctes : + +1. Arrange : éffectuer la configuration et l'initialisation requises pour le test. +2. Act : éffectuer la ou les actions requises pour le test. +3. Assert: Vérifier le(s) résultat(s) du test. + +## Explication + +Ce pattron présente plusieurs avantages importants. Il crée une séparation claire entre la mise en place d'un test d'un test, +les opérations et les résultats. Cette structure rend le code plus facile à lire et à comprendre. +Si vous placez les étapes dans l'ordre et que vous formatez votre code source pour les séparer, vous pouvez parcourir un test et comprendre rapidement ce qu'il fait. + +Il impose également un certain degré de discipline lors de l'écriture des tests. Vous devez penser clairement les trois étapes de votre test. +Il est plus naturel d'écrire les tests en même temps, puisque vous avez déjà un plan. + +Exemple + +> Pour écrire des tests unitaire clairs et compréhensibles. + +En clair + +> Arrange/Act/Assert est un pattron de conception de tests qui organise les tests en trois étapes pour une maintenance facile. + +WikiWikiWeb dit + +> Arrange/Act/Assert est un pattron pour organiser et formater un code dans les methodes de test unitaire. + +**Exemple de programme** + +Commençons par présenter notre classe `Cash` qui subira un test unitaire. + +```java +public class Cash { + + private int amount; + + Cash(int amount) { + this.amount = amount; + } + + void plus(int addend) { + amount += addend; + } + + boolean minus(int subtrahend) { + if (amount >= subtrahend) { + amount -= subtrahend; + return true; + } else { + return false; + } + } + + int count() { + return amount; + } +} +``` + +Ensuite, nous rédigeons nos tests unitaires suivant le pattron Arrange/Act/Assert. +Notez les étapes clairement séparées pour chaque test unitaire. + +```java +class CashAAATest { + + @Test + void testPlus() { + //Arrange + var cash = new Cash(3); + //Act + cash.plus(4); + //Assert + assertEquals(7, cash.count()); + } + + @Test + void testMinus() { + //Arrange + var cash = new Cash(8); + //Act + var result = cash.minus(5); + //Assert + assertTrue(result); + assertEquals(3, cash.count()); + } + + @Test + void testInsufficientMinus() { + //Arrange + var cash = new Cash(1); + //Act + var result = cash.minus(6); + //Assert + assertFalse(result); + assertEquals(1, cash.count()); + } + + @Test + void testUpdate() { + //Arrange + var cash = new Cash(5); + //Act + cash.plus(6); + var result = cash.minus(3); + //Assert + assertTrue(result); + assertEquals(8, cash.count()); + } +} +``` + +## Application + +Le pattron Arrange/Act/Assert peut être utilisé lorsque : + +* Vous avez besoin d'organiser vos tests unitaire pour qu'il soit facile à lire, maintenir et améliorer. + +## Crédits + +* [Arrange, Act, Assert: What is AAA Testing?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx) +* [Bill Wake: 3A – Arrange, Act, Assert](https://xp123.com/articles/3a-arrange-act-assert/) +* [Martin Fowler: GivenWhenThen](https://martinfowler.com/bliki/GivenWhenThen.html) +* [xUnit Test Patterns: Refactoring Test Code](https://www.amazon.com/gp/product/0131495054/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0131495054&linkId=99701e8f4af2f7e8dd50d720c9b63dbf) +* [Unit Testing Principles, Practices, and Patterns](https://www.amazon.com/gp/product/1617296279/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617296279&linkId=74c75cf22a63c3e4758ae08aa0a0cc35) +* [Test Driven Development: By Example](https://www.amazon.com/gp/product/0321146530/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321146530&linkId=5c63a93d8c1175b84ca5087472ef0e05) diff --git a/localization/fr/async-method-invocation/README.md b/localization/fr/async-method-invocation/README.md new file mode 100644 index 000000000000..0eef955ad614 --- /dev/null +++ b/localization/fr/async-method-invocation/README.md @@ -0,0 +1,166 @@ +--- +title: Async Method Invocation +category: Concurrency +language: fr +tag: + - Reactive +--- + +## Intention + +Le pattron de conception Asynchronous method invocation est un pattron dans lequel le thread appelé n'est pas bloqué en +attendant la fin de l'exécution des tâches. +Ce pattron permet le traitement parallèle de plusieurs tâches indépendantes et récupère les résultats via les callback ou patiente jusqu'à la fin. + +## Explication + +Exemple concret + +> Le lancement de fusées spatiales est une activité passionnante. Le commandant de la mission donne +> l'ordre de lancement et, après un temps indéterminé, la fusée réussit son lancement ou échoue lamentablement. + +En clair + +> Asynchronous method invocation démarre l'exécution de la tâche et retourne directement avant la fin de l'exécution de la tâche. +> Les résultats de l'exécution des tâches sont retournés après. + +Wikipedia dit + +> Dans la programmation multithread, asynchronous method invocation (AMI), également connue sous le nom de asynchronous method calls +> ou le pattron asynchronous, est un pattron de conception dans lequel le site d'appel n'est pas bloqué en attendant que le code appelé se termine. +> Au lieu de cela, le thread appelant est informé de l'arrivée de la réponse. L'interrogation pour une réponse est une option non souhaitée. + +**Exemple de programme** + +Dans cet exemple, nous lançons des fusées spatiales et déployons des rovers lunaires. + +L'application démontre le pattron async method invocation. Les éléments clés de ce modèle sont `AsyncResult` +qui est un conteneur intermédiaire pour une valeur évaluée de manière asynchrone, `AsyncCallback` qui peut être fourni +pour être exécuté à la fin de la tâche et `AsyncExecutor` qui gère l'exécution des tâches asynchrones. qui gère l'exécution des tâches asynchrones. + +```java +public interface AsyncResult { + boolean isCompleted(); + T getValue() throws ExecutionException; + void await() throws InterruptedException; +} +``` + +```java +public interface AsyncCallback { + void onComplete(T value, Optional ex); +} +``` + +```java +public interface AsyncExecutor { + AsyncResult startProcess(Callable task); + AsyncResult startProcess(Callable task, AsyncCallback callback); + T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException; +} +``` + +`ThreadAsyncExecutor` est une implémentation de `AsyncExecutor`. Certains de ses éléments clés sont décrits ci-dessous. + +```java +public class ThreadAsyncExecutor implements AsyncExecutor { + + @Override + public AsyncResult startProcess(Callable task) { + return startProcess(task, null); + } + + @Override + public AsyncResult startProcess(Callable task, AsyncCallback callback) { + var result = new CompletableResult<>(callback); + new Thread( + () -> { + try { + result.setValue(task.call()); + } catch (Exception ex) { + result.setException(ex); + } + }, + "executor-" + idx.incrementAndGet()) + .start(); + return result; + } + + @Override + public T endProcess(AsyncResult asyncResult) + throws ExecutionException, InterruptedException { + if (!asyncResult.isCompleted()) { + asyncResult.await(); + } + return asyncResult.getValue(); + } +} +``` + +Nous sommes ensuite prêts à lancer quelques fusées pour voir comment tout fonctionne ensemble. + +```java +public static void main(String[] args) throws Exception { + // construct a new executor that will run async tasks + var executor = new ThreadAsyncExecutor(); + + // start few async tasks with varying processing times, two last with callback handlers + final var asyncResult1 = executor.startProcess(lazyval(10, 500)); + final var asyncResult2 = executor.startProcess(lazyval("test", 300)); + final var asyncResult3 = executor.startProcess(lazyval(50L, 700)); + final var asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Deploying lunar rover")); + final var asyncResult5 = + executor.startProcess(lazyval("callback", 600), callback("Deploying lunar rover")); + + // emulate processing in the current thread while async tasks are running in their own threads + Thread.sleep(350); // Oh boy, we are working hard here + log("Mission command is sipping coffee"); + + // wait for completion of the tasks + final var result1 = executor.endProcess(asyncResult1); + final var result2 = executor.endProcess(asyncResult2); + final var result3 = executor.endProcess(asyncResult3); + asyncResult4.await(); + asyncResult5.await(); + + // log the results of the tasks, callbacks log immediately when complete + log("Space rocket <" + result1 + "> launch complete"); + log("Space rocket <" + result2 + "> launch complete"); + log("Space rocket <" + result3 + "> launch complete"); +} +``` + +Voici la sortie de la console du programme. + +```java +21:47:08.227 [executor-2] INFO com.iluwatar.async.method.invocation.App - Space rocket launched successfully +21:47:08.269 [main] INFO com.iluwatar.async.method.invocation.App - Mission command is sipping coffee +21:47:08.318 [executor-4] INFO com.iluwatar.async.method.invocation.App - Space rocket <20> launched successfully +21:47:08.335 [executor-4] INFO com.iluwatar.async.method.invocation.App - Deploying lunar rover <20> +21:47:08.414 [executor-1] INFO com.iluwatar.async.method.invocation.App - Space rocket <10> launched successfully +21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - Space rocket launched successfully +21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - Deploying lunar rover +21:47:08.616 [executor-3] INFO com.iluwatar.async.method.invocation.App - Space rocket <50> launched successfully +21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - Space rocket <10> launch complete +21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - Space rocket launch complete +21:47:08.618 [main] INFO com.iluwatar.async.method.invocation.App - Space rocket <50> launch complete +``` + +# Diagramme de classes + +![alt text](../../../async-method-invocation/etc/async-method-invocation.png "Async Method Invocation") + +## Application + +Utilisez le pattron async method invocation lorsque + +* Vous avez plusieurs tâches indépendantes qui peuvent être exécutées en parallèle +* Vous devez améliorer les performances d'un groupe de tâches séquentielles +* Vous disposez d'une capacité de traitement limitée ou de tâches à long terme et l'appelant ne doit pas attendre que les tâches soient exécutées. + +## Application concrete + +* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html) +* [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) +* [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) +* [Task-based Asynchronous Pattern](https://msdn.microsoft.com/en-us/library/hh873175.aspx) diff --git a/localization/fr/balking/README.md b/localization/fr/balking/README.md new file mode 100644 index 000000000000..ea066a510121 --- /dev/null +++ b/localization/fr/balking/README.md @@ -0,0 +1,133 @@ +--- +title: Balking +category: Concurrency +language: fr +tag: + - Decoupling +--- + +## Intention + +Le pattron de conception Balking est utilisé pour empêcher un objet d'exécuter un certain code +s'il est dans un état incomplet ou inapproprié. + +## Explication + +Exemple concret + +> Sur une machine à laver, un bouton de démarrage permet de lancer le lavage du linge. Lorsque la machine à laver est inactive, +> le bouton fonctionne comme prévu, mais si la machine est déjà en train de laver, le bouton ne fait rien. + +En clair + +> En utilisant le pattron balking, un certain code ne s'exécute que si l'objet se trouve dans un état particulier. + +Wikipedia dit + +> Le pattron de conception balking est un pattron de conception de logiciel qui n'exécute une action sur un objet que +> lorsque l'objet se trouve dans un état particulier. Par exemple, si un objet lit des fichiers ZIP et qu'une méthode +> appelante invoque une méthode get sur l'objet alors que le fichier ZIP n'est pas ouvert, l'objet rejette la demande. + +**Exemple de programme** + +Dans cet exemple d'implémentation, `WashingMachine` est un objet qui peut être dans deux états : ENABLED et WASHING. +Si la machine est ENABLED, l'état change en WASHING en utilisant une méthode thread-safe. D'autre part, si elle a déjà +été lavée et qu'un autre thread exécute `wash()`, elle ne le fera pas et terminera sans rien faire. + +Voici les parties pertinentes de la classe `WashingMachine` + +```java +@Slf4j +public class WashingMachine { + + private final DelayProvider delayProvider; + private WashingMachineState washingMachineState; + + public WashingMachine(DelayProvider delayProvider) { + this.delayProvider = delayProvider; + this.washingMachineState = WashingMachineState.ENABLED; + } + + public WashingMachineState getWashingMachineState() { + return washingMachineState; + } + + public void wash() { + synchronized (this) { + var machineState = getWashingMachineState(); + LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState); + if (this.washingMachineState == WashingMachineState.WASHING) { + LOGGER.error("Cannot wash if the machine has been already washing!"); + return; + } + this.washingMachineState = WashingMachineState.WASHING; + } + LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); + this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing); + } + + public synchronized void endOfWashing() { + washingMachineState = WashingMachineState.ENABLED; + LOGGER.info("{}: Washing completed.", Thread.currentThread().getId()); + } +} +``` + +Voici l'interface simple `DelayProvider` utilisée par le `WashingMachine`. + +```java +public interface DelayProvider { + void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task); +} +``` + +Nous allons maintenant présenter l'application en utilisant le `WashingMachine`. + +```java + public static void main(String... args) { + final var washingMachine = new WashingMachine(); + var executorService = Executors.newFixedThreadPool(3); + for (int i = 0; i < 3; i++) { + executorService.execute(washingMachine::wash); + } + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + LOGGER.error("ERROR: Waiting on executor service shutdown!"); + Thread.currentThread().interrupt(); + } + } +``` + +Voici la sortie de la console du programme. + +``` +14:02:52.268 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Actual machine state: ENABLED +14:02:52.272 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Doing the washing +14:02:52.272 [pool-1-thread-3] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-3: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-3] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.273 [pool-1-thread-1] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-1: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-1] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.324 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - 14: Washing completed. +``` + +## Diagramme de classe + +![alt text](../../../balking/etc/balking.png "Balking") + +## Application + +Utilisé le pattron balking lorsque : + +* Vous souhaitez invoquer une action sur un objet uniquement lorsqu'il se trouve dans un état spécifique +* Les objets ne sont généralement que dans un état susceptible d'évoluer temporairement, mais pour une durée inconnue. + +## Pattron de conception apparentés + +* [Guarded Suspension Pattern](https://java-design-patterns.com/patterns/guarded-suspension/) +* [Double Checked Locking Pattern](https://java-design-patterns.com/patterns/double-checked-locking/) + +## Crédits + +* [Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML, 2nd Edition, Volume 1](https://www.amazon.com/gp/product/0471227293/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0471227293&linkId=0e39a59ffaab93fb476036fecb637b99) diff --git a/localization/fr/bridge/README.md b/localization/fr/bridge/README.md new file mode 100644 index 000000000000..0d24a568731a --- /dev/null +++ b/localization/fr/bridge/README.md @@ -0,0 +1,215 @@ +--- +title: Bridge +category: Structural +language: fr +tag: + - Gang of Four +--- + +## Également connu sous le nom de + +Handle/Body + +## Intention + +Découpler une abstraction de son implémentation afin que les deux puissent varier indépendamment. + +## Explication + +Exemple concret + +> Considérons que vous avez une arme avec différents enchantements, et que vous êtes censé permettre de mélanger +> différentes armes avec différents enchantements. Que feriez-vous ? Créer plusieurs copies de chaque arme pour chacun +> des enchantements ou simplement créer un enchantement séparé et l'appliquer à l'arme en fonction des besoins ? +> Le pattron de concepetion Bridge pattern vous permet de faire la deuxième solution. + +En clair + +> Bridge pattern consiste à préférer la composition à l'héritage. Les détails de la mise en œuvre(implémentation) +> sont transférés d'une hiérarchie à un autre objet ayant une hiérarchie distincte. + +Wikipedia dit + +> Bridge pattern est un patron de conception utilisé en génie logiciel qui vise à "découpler une abstraction de sa +> mise en œuvre(son implémention) de manière à ce que les deux puissent varier de manière indépendante" + +**Exemple de programme** + +Servons nous de notre exemple d'arme ci-dessus. Nous avons ici la hiérarchie `Weapon` : + +```java +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; + } +} +``` + +Voici la hiérarchie des enchantements distincts : + +```java +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."); + } +} +``` + +Voici les deux hiérarchies en action : + +```java +LOGGER.info("The knight receives an enchanted sword."); +var enchantedSword = new Sword(new SoulEatingEnchantment()); +enchantedSword.wield(); +enchantedSword.swing(); +enchantedSword.unwield(); + +LOGGER.info("The valkyrie receives an enchanted hammer."); +var hammer = new Hammer(new FlyingEnchantment()); +hammer.wield(); +hammer.swing(); +hammer.unwield(); +``` + +Voici la sortie de la console. + +``` +The knight receives an enchanted sword. +The sword is wielded. +The item spreads bloodlust. +The sword is swung. +The item eats the soul of enemies. +The sword is unwielded. +Bloodlust slowly disappears. +The valkyrie receives an enchanted hammer. +The hammer is wielded. +The item begins to glow faintly. +The hammer is swung. +The item flies and strikes the enemies finally returning to owner's hand. +The hammer is unwielded. +The item's glow fades. +``` + +## Diagramme de classes + +![alt text](../../../bridge/etc/bridge.urm.png "Bridge class diagram") + +## Application + +Utilisez Bridge pattern lorsque + +* Vous souhaitez éviter un lien permanent entre une abstraction et son implémentation. Cela peut être le cas, par exemple, lorsque l'implémentation doit être sélectionnée ou changée au moment de l'exécution. +* Les abstractions et leurs implémentations doivent être extensibles par des classes filles. Dans ce cas, Bridge pattern vous permet de combiner les différentes abstractions et implémentations et de les étendre indépendamment. +* Les changements dans l'implémentation d'une abstraction ne doivent pas avoir d'impact sur les clients, c'est-à-dire que leur code ne doit pas être recompilé. +* Vous avez une prolifération de classes. Une telle hiérarchie de classes indique la nécessité de diviser un objet en deux parties. Rumbaugh utilise le terme de "généralisations imbriquées" pour désigner de telles hiérarchies de classes. +* Vous souhaitez partager une implémentation entre plusieurs objets (peut-être en utilisant le comptage de références), et ce fait doit être caché au client. Un exemple simple est la classe String de Coplien, dans laquelle plusieurs objets peuvent partager la même représentation d'une chaîne de caractères. + +## Tutoriel + +* [Bridge Pattern Tutorial](https://www.journaldev.com/1491/bridge-design-pattern-java) + +## Crédits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/fr/builder/README.md b/localization/fr/builder/README.md new file mode 100644 index 000000000000..1c731520993a --- /dev/null +++ b/localization/fr/builder/README.md @@ -0,0 +1,205 @@ +--- +title: "Patron de conception 'Builder' en Java: Créer des objets personnalisés avec clarté" +shortTitle: Builder +description: "Découvrez le patron de conception Builder en Java, un puissant modèle de création qui simplifie la construction d'objets. Apprenez à séparer la construction d'un objet complexe de sa représentation avec des exemples pratiques et des cas d'utilisation." +category: Creational +language: fr +tag: + - Gang of Four + - Instantiation + - Object composition +--- + +## Intention du Patron de conception Builder + +Le patron de conception Builder en Java, un modèle de création fondamental, permet de construire des objets complexes étape par étape. Il sépare la construction d'un objet complexe de sa représentation afin que le même processus de construction puisse créer différentes représentations. + +## Explication détaillée du patron de conception Builder avec des exemples réels + +Exemple réel + +> Le patron de conception Builder en Java est particulièrement utile dans des scénarios où la création d'un objet nécessite de nombreux paramètres. +> +> Imaginez que vous créez un sandwich personnalisable dans un restaurant. Le patron de conception Builder dans ce contexte impliquerait un `SandwichBuilder` qui vous permet de spécifier chaque composant du sandwich, comme le type de pain, de viande, de fromage, de légumes, et de condiments. Au lieu de savoir comment assembler le sandwich de zéro, vous utilisez le `SandwichBuilder` pour ajouter chaque composant désiré étape par étape, assurant que vous obtenez exactement le sandwich que vous souhaitez. Cette séparation entre la construction et la représentation finale du produit garantit que le même processus de construction peut produire différents types de sandwiches selon les composants spécifiés. + +En termes simples + +> Il vous permet de créer différentes versions d'un objet tout en évitant la "pollution" des constructeurs. Utile lorsque plusieurs variantes d'un objet sont possibles, ou lorsqu'il y a beaucoup d'étapes impliquées dans la création d'un objet. + +Wikipedia dit + +> Le modèle Builder est un modèle de conception de création d'objets qui vise à trouver une solution au problème des constructeurs à paramètres multiples, aussi connu sous le nom d'antipattern du constructeur télescopique. + +Avec cela à l'esprit, expliquons ce qu'est l'antipattern du constructeur télescopique. À un moment donné, nous avons tous rencontré un constructeur comme celui-ci: + +```java +public Hero(Profession profession,String name,HairType hairType,HairColor hairColor,Armor armor,Weapon weapon){ + // Assignation des valeurs +} +``` + +Comme vous pouvez le voir, le nombre de paramètres du constructeur peut rapidement devenir écrasant, ce qui rend difficile de comprendre leur agencement. De plus, cette liste de paramètres pourrait continuer à s'allonger si vous décidez d'ajouter plus d'options à l'avenir. Cela s'appelle l'antipattern du constructeur télescopique. + +## Exemple programmatique du Modèle Builder en Java + +Dans cet exemple du patron de conception Builder en Java, nous construisons différents types d'objets `Hero` avec des attributs variés. + +Imaginez un générateur de personnages pour un jeu de rôle. La solution la plus simple est de laisser l'ordinateur générer le personnage pour vous. Cependant, si vous préférez sélectionner manuellement les détails du personnage comme la profession, le genre, la couleur des cheveux, etc., la création de personnage devient un processus étape par étape qui se termine une fois toutes les sélections effectuées. + +Une approche plus logique est d'utiliser le modèle Builder. D'abord, considérons le `Hero` que nous voulons créer: + +```java +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; + } +} +```` + +Ensuite, nous avons le `Builder`: + +```java + 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); + } +} +``` + +Ensuite, il peut être utilisé comme suit: + +```java + public static void main(String[] args) { + + var mage = new Hero.Builder(Profession.MAGE, "Riobard") + .withHairColor(HairColor.BLACK) + .withWeapon(Weapon.DAGGER) + .build(); + LOGGER.info(mage.toString()); + + var warrior = new Hero.Builder(Profession.WARRIOR, "Amberjill") + .withHairColor(HairColor.BLOND) + .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD) + .build(); + LOGGER.info(warrior.toString()); + + var thief = new Hero.Builder(Profession.THIEF, "Desmond") + .withHairType(HairType.BALD) + .withWeapon(Weapon.BOW) + .build(); + LOGGER.info(thief.toString()); +} +``` + +Sortie du programme: + +``` +16:28:06.058 [main] INFO com.iluwatar.builder.App -- This is a mage named Riobard with black hair and wielding a dagger. +16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a warrior named Amberjill with blond long curly hair wearing chain mail and wielding a sword. +16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a thief named Desmond with bald head and wielding a bow. +``` + +## Diagramme de classe du Modèle Builder + +![Builder](./etc/builder.urm.png "Diagramme de classe du patron Builder") + +## Quand utiliser le patron de conception Builder en Java + +Utilisez le modèle Builder lorsque + +* Le patron de conception Builder est idéal pour les applications Java nécessitant la création d'objets complexes. +* L'algorithme pour créer un objet complexe doit être indépendant des parties qui composent l'objet et de la façon dont elles sont assemblées. +* Le processus de construction doit permettre différentes représentations de l'objet construit. +* Il est particulièrement utile lorsqu'un produit nécessite beaucoup d'étapes pour être créé et lorsque ces étapes doivent être exécutées dans un ordre spécifique. + +## Tutoriels Java sur le Modèle Builder + + +* [Patron de conception Builder (DigitalOcean)](https://www.journaldev.com/1425/builder-design-pattern-in-java) +* [Builder (Refactoring Guru)](https://refactoring.guru/design-patterns/builder) +* [Exploring Joshua Bloch’s Builder design pattern in Java (Java Magazine)](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) + +## Applications réelles du Modèle Builder en Java + +* StringBuilder en Java pour construire des chaînes de caractères. +* java.lang.StringBuffer utilisé pour créer des objets chaîne modifiables. +* Java.nio.ByteBuffer ainsi que des tampons similaires comme FloatBuffer, IntBuffer, et d'autres. +* javax.swing.GroupLayout.Group#addComponent() +* Divers constructeurs d'IHM dans les IDE qui créent des composants d'interface utilisateur. +* Toutes les implémentations de [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) +* [Constructeurs Apache Camel](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## Avantages et inconvénients du Modèle Builder + +Avantages: + +* Plus de contrôle sur le processus de construction par rapport à d'autres modèles de création. +* Permet de construire des objets étape par étape, de différer les étapes de construction ou d'exécuter des étapes de manière récursive. +* Peut construire des objets qui nécessitent un assemblage complexe de sous-objets. Le produit final est détaché des parties qui le composent ainsi que de leur processus d'assemblage. +* Principe de responsabilité unique. Vous pouvez isoler le code de construction complexe de la logique métier du produit. + +Inconvénients: + +* La complexité générale du code peut augmenter car le modèle nécessite la création de plusieurs nouvelles classes. +* Peut augmenter l'utilisation de la mémoire en raison de la nécessité de créer plusieurs objets builder. + +## Patrons de conception Java liés + +* [Fabrique abstraite (Abstract Factory)](https://java-design-patterns.com/patterns/abstract-factory/): Peut être utilisé en conjonction avec le patron de conception Builder pour construire des parties d'un objet complexe. +* [Prototype](https://java-design-patterns.com/patterns/prototype/): Les builders créent souvent des objets à partir d'un prototype. +* [Step Builder](https://java-design-patterns.com/patterns/step-builder/): Il s'agit d'une variation du modèle Builder qui génère un objet complexe en utilisant une approche étape par étape. Le modèle Step Builder est un bon choix lorsque vous avez besoin de construire un objet avec un grand nombre de paramètres optionnels, et que vous souhaitez éviter l'antipattern du constructeur télescopique. + +## Références et crédits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/localization/fr/business-delegate/README.md b/localization/fr/business-delegate/README.md new file mode 100644 index 000000000000..ba44559ea1fb --- /dev/null +++ b/localization/fr/business-delegate/README.md @@ -0,0 +1,187 @@ +--- +title: "Business Delegate Pattern en Java: Simplifier l'intéraction avec les services métiers" +shortTitle: Business Delegate +description: "Apprenez à connaître le patron Business Delegate en Java. Ce patron ajoute une niveau d'abstraction en la couche de présentation et la couche métier, assurant un couplage faible et une intéraction simplifiée entre les sevices." +category: Structural +language: fr +tag: + - Business + - Decoupling + - Delegation + - Enterprise patterns + - Layered architecture +--- + +## Aussi connu sous le nom de + +* Service Representative + +## But du modèle de conception Business-Delegate + +Le modèle Business Delegate est un modèle de conception structurel en Java qui ajoute un niveau d'abstraction en la couche de pésentation et la couche métier. Utiliser ce modèle garanti un couplage faible entre les couches et encapsule les informations sur la localisation, la connexion et les interactions des objets métiers qui composent l'application. + +## Explication détaillée et exemples concrets + +Exemple concret + +> Dans une application d'entreprise utilisant Java EE, le modèle Business-Delegate permet de gérer les interactions entre les différents services commerciaux. +> +> Imaginez un restaurant où le personnel de service sert d'intermédiaire entre les clients et la cuisine. Lorsqu'un client passe une commande, le serveur l'apporte à la cuisine, transmet toute demande spécifique et ramène ensuite le plat préparé au client. Le personnel de salle fait abstraction de la complexité des opérations de cuisine, ce qui permet aux chefs de se concentrer uniquement sur la préparation des plats, sans avoir à interagir directement avec les clients. Cette configuration permet au service à la clientèle (niveau de présentation) et à la cuisine (service commercial) de fonctionner de manière indépendante et efficace. Le personnel de service joue le rôle de délégué commercial, en gérant la communication et en garantissant des interactions harmonieuses entre les deux secteurs distincts. + +En clair + +> Le Business-Delegate ajoute une couche d'abstraction entre le niveau de présentation et le niveau commercial. + +Définition Wikipedia : + +> Business Delegate est un modèle de conception Java EE. Ce modèle vise à réduire le couplage entre les services métier et le niveau de présentation connecté, et à masquer les détails de mise en œuvre des services (y compris la consultation et l'accessibilité de l'architecture EJB). Les délégués commerciaux agissent comme un adaptateur permettant d'invoquer des objets commerciaux à partir du niveau de présentation. + +## Example de programme + +Le code Java suivant montre comment mettre en œuvre le modèle de délégué commercial. Ce modèle est particulièrement utile dans les applications nécessitant un couplage lâche et une interaction efficace entre les services. + +Une application pour téléphone portable promet de diffuser en continu n'importe quel film existant sur votre appareil. Elle capture la chaîne de recherche de l'utilisateur et la transmet au Business Delegate. Ce dernier sélectionne le service de streaming vidéo le plus approprié et lit la vidéo à partir de là. + +Tout d'abord, nous disposons d'une abstraction pour les services de streaming vidéo et de quelques implémentations. + +```java +public interface VideoStreamingService { + void doProcessing(); +} + +@Slf4j +public class NetflixService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("NetflixService is now processing"); + } +} + +@Slf4j +public class YouTubeService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("YouTubeService is now processing"); + } +} +``` + +Ensuite, nous avons un service de recherche qui décide quel service de streaming vidéo utiliser. + +```java + +@Setter +public class BusinessLookup { + + private NetflixService netflixService; + private YouTubeService youTubeService; + + public VideoStreamingService getBusinessService(String movie) { + if (movie.toLowerCase(Locale.ROOT).contains("die hard")) { + return netflixService; + } else { + return youTubeService; + } + } +} +``` + +Le Business Delegate utilise un service de recherche pour acheminer les requêtes vers le bon service de streaming. + +```java + +@Setter +public class BusinessDelegate { + + private BusinessLookup lookupService; + + public void playbackMovie(String movie) { + VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie); + videoStreamingService.doProcessing(); + } +} +``` + +Le client mobile se sert du Business Delegate pour appeler la couche métier. + +```java +public class MobileClient { + + private final BusinessDelegate businessDelegate; + + public MobileClient(BusinessDelegate businessDelegate) { + this.businessDelegate = businessDelegate; + } + + public void playbackMovie(String movie) { + businessDelegate.playbackMovie(movie); + } +} +``` + +Finalement, l'exemple concret en action. + +```java +public static void main(String[] args) { + + // prepare the objects + var businessDelegate = new BusinessDelegate(); + var businessLookup = new BusinessLookup(); + businessLookup.setNetflixService(new NetflixService()); + businessLookup.setYouTubeService(new YouTubeService()); + businessDelegate.setLookupService(businessLookup); + + // create the client and use the business delegate + var client = new MobileClient(businessDelegate); + client.playbackMovie("Die Hard 2"); + client.playbackMovie("Maradona: The Greatest Ever"); +} +``` + +Voici la sortie affichée dans la console. + +``` +21:15:33.790 [main] INFO com.iluwatar.business.delegate.NetflixService - NetflixService is now processing +21:15:33.794 [main] INFO com.iluwatar.business.delegate.YouTubeService - YouTubeService is now processing +``` + +## Diagramme de classe + +![Business Delegate](./etc/business-delegate.urm.png "Business Delegate") + +## Quand utiliser ce modèle de conception + +Utilisez le modèle Business Delegate lorsque + +* Vous avez besoin d'un couplage lâche entre les niveaux de présentation et d'activité ou vous avez besoin d'abstraire les recherches de services. +* Vous souhaitez organiser des appels à de multiples services commerciaux. +* Vous voulez encapsuler les recherches et les appels de services. +* Il est nécessaire d'abstraire et d'encapsuler la communication entre le niveau client et les services métier. + +## Tutoriels + +* [Design Patterns - Business Delegate Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/business_delegate_pattern.htm) + +## Applications concrêtes + +* Applications d'entreprise utilisant Java EE (Java Platform, Enterprise Edition) +* Applications nécessitant un accès à distance aux services de l'entreprised + +## Avantages et inconvénients + +Avantages : + +* Découplage des niveaux de présentation et d'activité : Permet au niveau client et aux services commerciaux d'évoluer indépendamment. +* Transparence de l'emplacement : Les clients ne sont pas affectés par les changements de localisation ou d'instanciation des services commerciaux. +* Réutilisation et évolutivité : Les objets Business Delegate peuvent être réutilisés par plusieurs clients, et le modèle prend en charge l'équilibrage de la charge et l'évolutivité. + +Inconvénients : + +* Complexity: Introduces additional layers and abstractions, which may increase complexity. +* Performance Overhead: The additional indirection may incur a slight performance penalty. + +## Réferences et crédits + +* [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) diff --git a/localization/hi/README.md b/localization/hi/README.md new file mode 100644 index 000000000000..e6525eb26d45 --- /dev/null +++ b/localization/hi/README.md @@ -0,0 +1,55 @@ + + +# जावा में कार्यान्वित डिजाइन पैटर्न + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-213-orange.svg?style=flat-square)](#contributors-) + + +# परिचय + +डिज़ाइन पैटर्न सर्वोत्तम, औपचारिक अभ्यास हैं जिनका उपयोग एक प्रोग्रामर कर सकता है +किसी एप्लिकेशन या सिस्टम को डिजाइन करते समय सामान्य समस्याओं को हल करें। + +डिज़ाइन पैटर्न परीक्षण किए गए, सिद्ध विकास प्रतिमान प्रदान करके विकास प्रक्रिया को गति दे सकते हैं। + +डिज़ाइन पैटर्न का पुन: उपयोग करने से सूक्ष्म मुद्दों को रोकने में मदद मिलती है जो बड़ी समस्याएं पैदा करते हैं, और यह कोडर्स और आर्किटेक्ट्स के लिए कोड पठनीयता में भी सुधार करता है जो पैटर्न से परिचित हैं। + +# शुरू करते है + +यह साइट जावा डिज़ाइन पैटर्न प्रदर्शित करती है। समाधान द्वारा विकसित किए गए हैं +ओपन-सोर्स समुदाय के अनुभवी प्रोग्रामर और आर्किटेक्ट। +पैटर्न को उनके उच्च-स्तरीय विवरणों द्वारा या उनके को देखकर ब्राउज़ किया जा सकता है +सोर्स कोड। स्रोत कोड के उदाहरणों पर अच्छी तरह से टिप्पणी की गई है और इसे इस प्रकार माना जा सकता है +एक विशिष्ट पैटर्न को लागू करने के तरीके पर प्रोग्रामिंग ट्यूटोरियल। हम सबसे ज्यादा इस्तेमाल करते हैं +लोकप्रिय युद्ध-सिद्ध ओपन-सोर्स जावा प्रौद्योगिकियां। + +सामग्री में गोता लगाने से पहले, आपको विभिन्न से परिचित होना चाहिए +[सॉफ्टवेयर डिजाइन सिद्धांत](https://java-design-patterns.com/principles/). + +सभी डिज़ाइन यथासंभव सरल होने चाहिए। आपको KISS, YAGNI से शुरू करना चाहिए और वह सरलतम कार्य करें जो संभवतः सिद्धांतों पर कार्य कर सके। जटिलता और पैटर्न केवल तभी पेश किए जाने चाहिए जब व्यावहारिक विस्तारशीलता के लिए उनकी आवश्यकता हो। + +एक बार जब आप इन अवधारणाओं से परिचित हो जाते हैं तो आप नीचे की ओर ड्रिलिंग शुरू कर सकते हैं +[उपलब्ध डिजाइन पैटर्न](https://java-design-patterns.com/patterns/) निम्नलिखित में से किसी भी दृष्टिकोण से + + - नाम से एक विशिष्ट पैटर्न खोजें। एक नहीं मिल रहा है? कृपया एक नए पैटर्न की रिपोर्ट करें [यहां](https://github.com/iluwatar/java-design-patterns/issues). + - `Performance`, `Gang of Four` या `Data access` जैसे टैग का उपयोग करना। + - पैटर्न श्रेणियों, `Creational`, `Behavioral`, और अन्य का उपयोग करना। + +उम्मीद है, आप इस साइट पर प्रस्तुत किए गए ऑब्जेक्ट-ओरिएंटेड समाधान अपने आर्किटेक्चर में उपयोगी पाते हैं और उन्हें सीखने में उतना ही मज़ा आता है जितना हमें उन्हें विकसित करते समय मिला था। + +# कैसे योगदान करें + +यदि आप परियोजना में योगदान करने के इच्छुक हैं तो आपको हमारे [डेवलपर विकी](https://github.com/iluwatar/java-design-patterns/wiki) में प्रासंगिक जानकारी मिल जाएगी। हम आपकी मदद करेंगे और [गिटर चैटरूम](https://gitter.im/iluwatar/java-design-patterns) में आपके सवालों के जवाब देंगे। + +# लाइसेंस + +यह परियोजना एमआईटी लाइसेंस की शर्तों के तहत लाइसेंस प्राप्त है। + diff --git a/localization/hi/abstract-document/README.md b/localization/hi/abstract-document/README.md new file mode 100644 index 000000000000..965cbb4c741b --- /dev/null +++ b/localization/hi/abstract-document/README.md @@ -0,0 +1,187 @@ +--- +title: Abstract Document +category: Structural +language: hi +tag: + - Extensibility +--- + +## हेतु + +गतिशील गुणों का उपयोग करें और टाइप-सेफ्टी रखते हुए अनटाइप्ड लैंग्वेज का लचीलापन प्राप्त करें। + +## व्याख्या + +सार दस्तावेज़ पैटर्न अतिरिक्त, गैर-स्थैतिक गुणों को संभालने में सक्षम बनाता है। यह पैटर्न +प्रकार की सुरक्षा और विभिन्न वर्गों के अलग-अलग गुणों को सक्षम करने के लिए लक्षणों की अवधारणा का उपयोग करता है +इंटरफेस का सेट। +वास्तविक उदाहरण + +> एक कार पर विचार करें जिसमें कई हिस्से होते हैं। हालाँकि हम नहीं जानते कि क्या विशिष्ट कार में वास्तव में सभी पुर्जे हैं, या उनमें से कुछ ही हैं। हमारी कारें गतिशील और बेहद लचीली हैं। + +सरल शब्दो मे + +> सार दस्तावेज़ पैटर्न वस्तुओं को इसके बारे में जानने के बिना गुणों को संलग्न करने की अनुमति देता है। + +विकिपीडिया कहता है + +> ढीले टाइप की-वैल्यू स्टोर्स और एक्सपोज़िंग में ऑब्जेक्ट्स को व्यवस्थित करने के लिए एक ऑब्जेक्ट-ओरिएंटेड स्ट्रक्चरल डिज़ाइन पैटर्न +टाइप किए गए दृश्यों का उपयोग कर डेटा। पैटर्न का उद्देश्य घटकों के बीच उच्च स्तर का लचीलापन प्राप्त करना है +एक दृढ़ता से टाइप की गई भाषा में जहां ऑब्जेक्ट-ट्री में नए गुण जोड़े जा सकते हैं, बिना खोए +प्रकार-सुरक्षा का समर्थन। पैटर्न एक वर्ग के विभिन्न गुणों को अलग-अलग करने के लिए लक्षणों का उपयोग करता है +इंटरफेस। + +**प्रोग्रामेटिक उदाहरण** + +आइए पहले आधार वर्ग `Document` और `AbstractDocument` को परिभाषित करें। वे मूल रूप से वस्तु को एक संपत्ति बनाते हैं +नक्शा और बाल वस्तुओं की कोई भी राशि। + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + ... +} +``` +इसके बाद हम एक एनुम `Property` और प्रकार, मूल्य, मॉडल और भागों के लिए इंटरफेस का एक सेट परिभाषित करते हैं। यह हमें बनाने की अनुमति देता है +हमारे `Car` वर्ग के लिए स्थिर दिखने वाला इंटरफ़ेस। + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} +``` + +अब हम पेश करने के लिए तैयार हैं `Car`. + +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` + +और अंत में यहां बताया गया है कि कैसे हम `Car` का निर्माण और उपयोग एक पूर्ण उदाहरण में करते हैं। + +```java + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); + + // Constructing parts and car + // Here is our car: + // model: 300SL + // price: 10000 + // parts: + // wheel/15C/100 + // door/Lambo/300 +``` + +## क्लास डायग्राम + +![alt text](../../../abstract-document/etc/abstract-document.png "Abstract Document Traits and Domain") + +## उपयोग + +कब सार दस्तावेज़ पैटर्न का प्रयोग करें + +* तत्काल नई संपत्तियों को जोड़ने की जरूरत है +* आप डोमेन को वृक्ष जैसी संरचना में व्यवस्थित करने के लिए एक लचीला तरीका चाहते हैं +* आप अधिक शिथिल युग्मित प्रणाली चाहते हैं + +## श्रेय + +* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492) diff --git a/localization/hi/abstract-factory/README.md b/localization/hi/abstract-factory/README.md new file mode 100644 index 000000000000..8f6fd13e86d4 --- /dev/null +++ b/localization/hi/abstract-factory/README.md @@ -0,0 +1,229 @@ +--- +title: Abstract Factory +category: Creational +language: hi +tag: + - Gang of Four +--- + +## के रूप में भी जाना जाता है + +किट + +## हेतु + +संबंधित या आश्रित परिवारों को बनाने के लिए एक इंटरफ़ेस प्रदान करें +वस्तुओं को उनके ठोस वर्गों को निर्दिष्ट किए बिना। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> एक राज्य बनाने के लिए हमें एक सामान्य विषय वाली वस्तुओं की आवश्यकता होती है। Elven किंगडम को एक Elven King, Elven Castle और Elven सेना की आवश्यकता होती है जबकि Orcish राज्य को एक Orcish King, Orcish Castle और Orcish सेना की आवश्यकता होती है। राज्य में वस्तुओं के बीच एक निर्भरता है। + +सरल शब्दो मे + +> कारखानों का एक कारखाना; एक कारखाना जो व्यक्तिगत लेकिन संबंधित/आश्रित कारखानों को उनके ठोस वर्गों को निर्दिष्ट किए बिना एक साथ समूहित करता है। + +विकिपीडिया कहता है + +> अमूर्त फ़ैक्टरी पैटर्न व्यक्तिगत फ़ैक्टरियों के एक समूह को समाहित करने का एक तरीका प्रदान करता है, जिनके ठोस वर्गों को निर्दिष्ट किए बिना एक सामान्य विषय है। + +**Programmatic Example** + +ऊपर किंगडम उदाहरण का अनुवाद। सबसे पहले, हमारे पास वस्तुओं के लिए कुछ इंटरफेस और कार्यान्वयन हैं +साम्राज्य। + +```java +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 -> ... + +``` + +फिर हमारे पास राज्य कारखाने के लिए अमूर्तता और कार्यान्वयन है। + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +अब हमारे पास एब्स्ट्रैक्ट फैक्ट्री है जो हमें संबंधित वस्तुओं का एक परिवार बनाने की सुविधा देती है, जैसे कि एल्वेन किंगडम फैक्ट्री एल्वेन कैसल, राजा और सेना आदि बनाती है। + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +Program output: + +```java +This is the elven castle! +This is the elven king! +This is the elven Army! +``` + +अब, हम अपने विभिन्न राज्य कारखानों के लिए एक कारखाना डिजाइन कर सकते हैं। इस उदाहरण में, हमने `FactoryMaker` बनाया, जो `ElfKingdomFactory` या `OrcKingdomFactory` के उदाहरण को वापस करने के लिए ज़िम्मेदार है। +ग्राहक वांछित कंक्रीट फैक्ट्री बनाने के लिए `फैक्ट्रीमेकर` का उपयोग कर सकता है, जो बदले में, विभिन्न ठोस वस्तुओं का उत्पादन करेगा (`आर्मी`, `किंग`, `कैसल` से व्युत्पन्न)। +इस उदाहरण में, हमने क्लाइंट द्वारा अनुरोध किए जाने वाले राज्य कारखाने के प्रकार को पैरामीटर करने के लिए एक एनम का भी उपयोग किया। + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + default -> throw new IllegalArgumentException("KingdomType not supported."); + }; + } +} + + public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + --similar use of the orc factory + } +``` + +## क्लास डायग्राम + +![alt text](../../../abstract-factory/etc/abstract-factory.urm.png "Abstract Factory class diagram") + + +## प्रयोज्यता + +एब्सट्रैक्ट फ़ैक्टरी पैटर्न का उपयोग कब करें + +* सिस्टम इस बात से स्वतंत्र होना चाहिए कि इसके उत्पाद कैसे बनाए जाते हैं, बनाए जाते हैं और प्रस्तुत किए जाते हैं +* सिस्टम को उत्पादों के कई परिवारों में से एक के साथ कॉन्फ़िगर किया जाना चाहिए +* संबंधित उत्पाद वस्तुओं के परिवार को एक साथ उपयोग करने के लिए डिज़ाइन किया गया है, और आपको इस बाधा को लागू करने की आवश्यकता है +* आप उत्पादों की एक क्लास लाइब्रेरी प्रदान करना चाहते हैं, और आप केवल उनके इंटरफेस को प्रकट करना चाहते हैं, उनके कार्यान्वयन को नहीं +* निर्भरता का जीवनकाल अवधारणात्मक रूप से उपभोक्ता के जीवनकाल से छोटा होता है। +* किसी विशेष निर्भरता के निर्माण के लिए आपको रन-टाइम मान की आवश्यकता होती है +* आप यह तय करना चाहते हैं कि रनटाइम के दौरान परिवार से किस उत्पाद को कॉल किया जाए। +* आपको निर्भरता को हल करने से पहले केवल रन-टाइम पर ज्ञात एक या अधिक पैरामीटर प्रदान करने की आवश्यकता है। +* जब आपको उत्पादों के बीच निरंतरता की आवश्यकता हो +* प्रोग्राम में नए उत्पादों या उत्पादों के समूह को जोड़ते समय आप मौजूदा कोड को बदलना नहीं चाहते हैं। + +उदाहरण उपयोग के मामले + +* रनटाइम पर FileSystemAcmeService या DatabaseAcmeService या NetworkAcmeService के उपयुक्त कार्यान्वयन के लिए कॉल करने का चयन करना। +* यूनिट टेस्ट केस लिखना बहुत आसान हो जाता है +* विभिन्न ओएस के लिए यूआई उपकरण + +## नतीजे + +* जावा में निर्भरता इंजेक्शन सेवा वर्ग की निर्भरता को छुपाता है जो रनटाइम त्रुटियों को जन्म दे सकता है जो संकलन समय पर पकड़ा गया होता। +* जबकि पूर्वनिर्धारित वस्तुओं को बनाते समय पैटर्न बहुत अच्छा होता है, नए को जोड़ना चुनौतीपूर्ण हो सकता है। +* कोड अधिक जटिल हो जाता है जितना होना चाहिए क्योंकि पैटर्न के साथ बहुत सारे नए इंटरफेस और कक्षाएं पेश की जाती हैं। + +## ट्यूटोरियल + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## ज्ञात उपयोग + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## संबंधित पैटर्न + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## श्रेय + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/hi/active-object/README.md b/localization/hi/active-object/README.md new file mode 100644 index 000000000000..2ba42a27f345 --- /dev/null +++ b/localization/hi/active-object/README.md @@ -0,0 +1,128 @@ +--- +title: Active Object +category: Concurrency +language: hi +tag: + - Performance +--- + + +## हेतु +सक्रिय ऑब्जेक्ट डिज़ाइन पैटर्न उन वस्तुओं के लिए विधि आमंत्रण से विधि निष्पादन को अलग करता है जो प्रत्येक अपने नियंत्रण के धागे में रहते हैं। लक्ष्य एसिंक्रोनस विधि आमंत्रण और अनुरोधों को संभालने के लिए शेड्यूलर का उपयोग करके समवर्तीता पेश करना है। + +## व्याख्या + +सक्रिय ऑब्जेक्ट पैटर्न को लागू करने वाली कक्षा में 'सिंक्रनाइज़' विधियों का उपयोग किए बिना एक स्व-सिंक्रनाइज़ेशन तंत्र होगा। + +वास्तविक दुनिया का उदाहरण + +> ओर्क्स अपने जंगलीपन और अदम्य आत्मा के लिए जाने जाते हैं। ऐसा लगता है जैसे उनके पास पिछले व्यवहार के आधार पर नियंत्रण का अपना सूत्र है। + +एक प्राणी को लागू करने के लिए जिसके पास नियंत्रण तंत्र का अपना धागा है और केवल अपने एपीआई का पर्दाफाश करता है न कि स्वयं निष्पादन, हम सक्रिय ऑब्जेक्ट पैटर्न का उपयोग कर सकते हैं। + + +**Programmatic Example** + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +हम देख सकते हैं कि कोई भी वर्ग जो ActiveCreature वर्ग का विस्तार करेगा, उसके पास तरीकों को लागू करने और निष्पादित करने के लिए नियंत्रण का अपना धागा होगा। + + +उदाहरण के लिए, Orc क्लास: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` + +अब, हम Orcs जैसे कई जीव बना सकते हैं, उन्हें खाने और घूमने के लिए कह सकते हैं, और वे इसे अपने नियंत्रण के thread पर क्रियान्वित करेंगे: + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## क्लास डायग्राम + +![alt text](../../../active-object/etc/active-object.urm.png "Active Object class diagram") + +## ट्यूटोरियल + +* [Android and Java Concurrency: The Active Object Pattern](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) \ No newline at end of file diff --git a/localization/hi/acyclic-visitor/README.md b/localization/hi/acyclic-visitor/README.md new file mode 100644 index 000000000000..ab06803796ae --- /dev/null +++ b/localization/hi/acyclic-visitor/README.md @@ -0,0 +1,167 @@ +--- +title: Acyclic Visitor +category: Behavioral +language: hi +tag: + - Extensibility +--- + +## हेतु + +उन पदानुक्रमों को प्रभावित किए बिना और बनाए बिना मौजूदा वर्ग पदानुक्रमों में नए कार्यों को जोड़ने की अनुमति दें +तकलीफ़देह निर्भरता चक्र जो GoF विज़िटर पैटर्न में अंतर्निहित हैं। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + + +> हमारे पास मॉडेम कक्षाओं का एक पदानुक्रम है। इस पदानुक्रम में मोडेम को बाहरी एल्गोरिथम आधारित द्वारा देखा जाना चाहिए +> फ़िल्टरिंग मानदंड पर (क्या यह यूनिक्स या डॉस संगत मॉडेम है)। + +सरल शब्दो मे + +> चक्रीय आगंतुक पदानुक्रम को संशोधित किए बिना कार्यों को मौजूदा वर्ग पदानुक्रम में जोड़ने की अनुमति देता है। + +[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) कहता है + + +> एसाइक्लिक विज़िटर पैटर्न मौजूदा वर्ग पदानुक्रमों को प्रभावित किए बिना नए कार्यों को जोड़ने की अनुमति देता है +> पदानुक्रम, और निर्भरता चक्र बनाए बिना जो GangOfFour विज़िटरपैटर्न में निहित हैं। + +**Programmatic Example** + +यहाँ `मॉडेम` पदानुक्रम है। + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + + +आगे हम `मॉडेमविज़िटर` पदानुक्रम का परिचय देते हैं। + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + ... + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + ... + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +अंत में, यहां आगंतुक कार्रवाई में हैं। + +```java + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + var zoom = new Zoom(); + var hayes = new Hayes(); + hayes.accept(conDos); + zoom.accept(conDos); + hayes.accept(conUnix); + zoom.accept(conUnix); +``` + +Program output: + +``` + // Hayes modem used with Dos configurator. + // Zoom modem used with Dos configurator. + // Only HayesVisitor is allowed to visit Hayes modem + // Zoom modem used with Unix configurator. +``` + +## क्लास डायग्राम + +![alt text](../../../acyclic-visitor/etc/acyclic-visitor.png "Acyclic Visitor") + +## प्रयोज्यता + +पैटर्न का उपयोग कब करें + +* जब आपको उस पदानुक्रम को बदलने या प्रभावित करने की आवश्यकता के बिना किसी मौजूदा पदानुक्रम में एक नया फ़ंक्शन जोड़ने की आवश्यकता होती है। +* जब ऐसे कार्य होते हैं जो एक पदानुक्रम पर काम करते हैं, लेकिन जो स्वयं पदानुक्रम में शामिल नहीं होते हैं। उदा. ConfigureForDOS / ConfigureForUnix / ConfigureForX समस्या। +* जब आपको किसी वस्तु के प्रकार के आधार पर बहुत भिन्न संचालन करने की आवश्यकता होती है। +* जब विज़िट किए गए वर्ग पदानुक्रम को तत्व वर्ग के नए डेरिवेटिव के साथ अक्सर विस्तारित किया जाएगा। +* जब एलिमेंट के डेरिवेटिव का पुनर्संकलन, रीलिंकिंग, रीटेस्टिंग या पुनर्वितरण बहुत महंगा हो। + +## ट्यूटोरियल + +* [Acyclic Visitor Pattern Example](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) + +## नतीजे + + +अच्छा: + +* वर्ग पदानुक्रमों के बीच कोई निर्भरता चक्र नहीं। +* यदि कोई नया जोड़ा जाता है तो सभी आगंतुकों को पुनः संकलित करने की आवश्यकता नहीं है। +* यदि वर्ग पदानुक्रम में एक नया सदस्य है तो मौजूदा आगंतुकों में संकलन विफलता का कारण नहीं बनता है। + + +खराब: + +* यह दिखाते हुए [लिस्कोव के प्रतिस्थापन सिद्धांत](https://java-design-patterns.com/principles/#liskov-substitution-principle) का उल्लंघन करता है कि यह सभी आगंतुकों को स्वीकार कर सकता है लेकिन वास्तव में केवल विशेष आगंतुकों में रुचि रखता है। +* विज़िट करने योग्य वर्ग पदानुक्रम में सभी सदस्यों के लिए आगंतुकों का समानांतर पदानुक्रम बनाया जाना है। + +## संबंधित पैटर्न + +* [Visitor Pattern](https://java-design-patterns.com/patterns/visitor/) + +## श्रेय + +* [Acyclic Visitor by Robert C. Martin](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor in WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) diff --git a/localization/hi/adapter/README.md b/localization/hi/adapter/README.md new file mode 100644 index 000000000000..6f761389a2d6 --- /dev/null +++ b/localization/hi/adapter/README.md @@ -0,0 +1,137 @@ +--- +title: Adapter +category: Structural +language: hi +tag: + - Gang of Four +--- + +## दूसरा नाम +आवरण + +## हेतु +किसी क्लास के इंटरफ़ेस को क्लाइंट द्वारा अपेक्षित किसी अन्य इंटरफ़ेस में कनवर्ट करें। एडाप्टर कक्षाओं को एक साथ काम करने देता है +असंगत इंटरफ़ेस के कारण अन्यथा नहीं हो सका। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> विचार करें कि आपके मेमोरी कार्ड पर कुछ चित्र हैं और आपको उन्हें अपने कंप्यूटर पर स्थानांतरित करने की आवश्यकता है। उन्हें स्थानांतरित करने के लिए, आपको किसी प्रकार के एडाप्टर की आवश्यकता होती है जो आपके कंप्यूटर पोर्ट के साथ संगत हो ताकि आप अपने कंप्यूटर में मेमोरी कार्ड संलग्न कर सकें। इस मामले में कार्ड रीडर एक एडाप्टर है। +> एक अन्य उदाहरण प्रसिद्ध पावर एडॉप्टर होगा; तीन-पैर वाले प्लग को दो-आयामी आउटलेट से नहीं जोड़ा जा सकता है, इसके लिए एक पावर एडाप्टर का उपयोग करने की आवश्यकता होती है जो इसे दो-आयामी आउटलेट के साथ संगत बनाता है। +> एक अन्य उदाहरण एक अनुवादक का होगा जो एक व्यक्ति द्वारा दूसरे व्यक्ति द्वारा बोले गए शब्दों का अनुवाद करेगा। + +सरल शब्दो मे + +> एडेप्टर पैटर्न आपको किसी अन्यथा असंगत ऑब्जेक्ट को किसी अन्य वर्ग के साथ संगत बनाने के लिए एडॉप्टर में लपेटने की सुविधा देता है। + +विकिपीडिया कहता है + +> सॉफ्टवेयर इंजीनियरिंग में, एडॉप्टर पैटर्न एक सॉफ्टवेयर डिज़ाइन पैटर्न है जो मौजूदा क्लास के इंटरफ़ेस को दूसरे इंटरफ़ेस के रूप में उपयोग करने की अनुमति देता है। इसका उपयोग अक्सर मौजूदा कक्षाओं को उनके स्रोत कोड को संशोधित किए बिना दूसरों के साथ काम करने के लिए किया जाता है। + +**प्रोग्रामेटिक उदाहरण** + +एक ऐसे कप्तान पर विचार करें जो केवल नाव चला सकता है और बिल्कुल भी नाव नहीं चला सकता। + +सबसे पहले, हमारे पास इंटरफ़ेस `RowingBoat` और `FishingBoat` हैं + +```java +public interface RowingBoat { + void row(); +} + +@Slf4j +public class FishingBoat { + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } +} +``` + +और कैप्टन को उम्मीद है कि `RowingBoat` इंटरफ़ेस का कार्यान्वयन आगे बढ़ने में सक्षम होगा + +```java +public class Captain { + + private final RowingBoat rowingBoat; + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +अब मान लीजिए कि समुद्री डाकू आ रहे हैं और हमारे कप्तान को भागने की जरूरत है लेकिन केवल मछली पकड़ने वाली नाव उपलब्ध है। हमें एक एडॉप्टर बनाने की आवश्यकता है जो कप्तान को नाव चलाने के अपने कौशल के साथ मछली पकड़ने वाली नाव को संचालित करने की अनुमति दे। + +```java +@Slf4j +public class FishingBoatAdapter implements RowingBoat { + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} +``` + +और अब `Captain` समुद्री डाकुओं से बचने के लिए `FishingBoat` का उपयोग कर सकता है + +```java +var captain = new Captain(new FishingBoatAdapter()); +captain.row(); +``` + +## क्लास डायग्राम +![alt text](../../../adapter/etc/adapter.urm.png "एडाप्टर क्लास डायग्राम") + +## प्रयोज्यता +जब एडॉप्टर पैटर्न का उपयोग करें + +* आप किसी मौजूदा कक्षा का उपयोग करना चाहते हैं, और इसका इंटरफ़ेस आपकी ज़रूरत से मेल नहीं खाता है। +* आप एक पुन: प्रयोज्य वर्ग बनाना चाहते हैं जो असंबद्ध या अप्रत्याशित वर्गों के साथ सहयोग करता है, अर्थात, ऐसे वर्ग जिनमें आवश्यक रूप से संगत इंटरफ़ेस नहीं है +* आपको कई मौजूदा उपवर्गों का उपयोग करने की आवश्यकता है, लेकिन सभी को उपवर्गित करके उनके इंटरफ़ेस को अनुकूलित करना अव्यावहारिक है। एक ऑब्जेक्ट एडाप्टर अपने मूल वर्ग के इंटरफ़ेस को अनुकूलित कर सकता है। +* तृतीय-पक्ष लाइब्रेरी का उपयोग करने वाले अधिकांश एप्लिकेशन लाइब्रेरी से एप्लिकेशन को अलग करने के लिए एप्लिकेशन और तृतीय पक्ष लाइब्रेरी के बीच मध्य परत के रूप में एडेप्टर का उपयोग करते हैं। यदि किसी अन्य लाइब्रेरी का उपयोग करना है तो एप्लिकेशन कोड को बदले बिना नई लाइब्रेरी के लिए केवल एक एडाप्टर की आवश्यकता होती है। + +## ट्यूटोरियल + +* [Dzone](https://dzone.com/articles/adapter-design-pattern-in-java) +* [Refactoring Guru](https://refactoring.guru/design-patterns/adapter/java/example) +* [Baeldung](https://www.baeldung.com/java-adapter-pattern) + +## नतीजे +क्लास और ऑब्जेक्ट एडेप्टर के अलग-अलग ट्रेड-ऑफ़ होते हैं। एक क्लास एडॉप्टर + +* एक ठोस एडाप्टी वर्ग के लिए प्रतिबद्ध होकर एडाप्टी को लक्ष्य के अनुसार अनुकूलित करता है। परिणामस्वरूप, जब हम किसी क्लास और उसके सभी उपवर्गों को अनुकूलित करना चाहते हैं तो क्लास एडॉप्टर काम नहीं करेगा। +* एडॉप्टर को एडैप्टी के कुछ व्यवहारों को ओवरराइड करने दें क्योंकि एडॉप्टर एडैप्टी का एक उपवर्ग है। +* केवल एक ऑब्जेक्ट का परिचय देता है, और एडाप्टी तक पहुंचने के लिए किसी अतिरिक्त सूचक संकेत की आवश्यकता नहीं होती है। + +एक ऑब्जेक्ट एडाप्टर + +* एक ही एडॉप्टर को कई एडाप्टीज़ के साथ काम करने देता है, यानी स्वयं एडाप्टी और उसके सभी उपवर्गों (यदि कोई हो) के साथ। एडॉप्टर एक साथ सभी एडेप्टीज़ में कार्यक्षमता भी जोड़ सकता है। +* एडाप्टी व्यवहार को ओवरराइड करना कठिन बना देता है। इसके लिए एडाप्टी को उपवर्गित करने और एडॉप्टर को एडाप्टी के बजाय उपवर्ग को संदर्भित करने की आवश्यकता होगी। + + +## वास्तविक दुनिया के उदाहरण + +* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +* [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +* [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + + +## श्रेय + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) \ No newline at end of file diff --git a/localization/hi/aggregator-microservices/README.md b/localization/hi/aggregator-microservices/README.md new file mode 100644 index 000000000000..1530d775d4b0 --- /dev/null +++ b/localization/hi/aggregator-microservices/README.md @@ -0,0 +1,107 @@ +--- +title: Aggregator Microservices +category: Architectural +language: hi +tag: +- Cloud distributed +- Decoupling +- Microservices +--- + +## हेतु + +उपयोगकर्ता एग्रीगेटर सेवा पर एक कॉल करता है, और एग्रीगेटर फिर प्रत्येक प्रासंगिक माइक्रोसर्विस को कॉल करता है। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> हमारे वेब बाज़ार को उत्पादों और उनकी वर्तमान सूची के बारे में जानकारी की आवश्यकता है। यह एक एग्रीगेटर को कॉल करता है +> सेवा जो बदले में उत्पाद जानकारी माइक्रोसर्विस और उत्पाद इन्वेंट्री माइक्रोसर्विस को कॉल करती है +> संयुक्त जानकारी. + +साफ़ शब्दों में + +> एग्रीगेटर माइक्रोसर्विस विभिन्न माइक्रोसर्विसेज से डेटा के टुकड़े एकत्र करता है और प्रसंस्करण के लिए एक समुच्चय लौटाता है। + +स्टैक ओवरफ्लो कहता है + +> एग्रीगेटर माइक्रोसर्विस एप्लिकेशन द्वारा आवश्यक कार्यक्षमता प्राप्त करने के लिए कई सेवाओं को आमंत्रित करता है। + +**प्रोग्रामेटिक उदाहरण** + +आइए डेटा मॉडल से शुरू करें। यहाँ हमारा `Product` है। + +```java +public class Product { + private String title; + private int productInventories; + // getters and setters -> + ... +} +``` + +आगे हम अपना `Aggregator` माइक्रोसर्विस पेश कर सकते हैं। इसमें क्लाइंट `ProductInformationClient` और शामिल हैं +संबंधित माइक्रोसर्विसेज़ को कॉल करने के लिए `ProductInventoryClient`। + +```java +@RestController +public class Aggregator { + + @Resource + private ProductInformationClient informationClient; + + @Resource + private ProductInventoryClient inventoryClient; + + @RequestMapping(path = "/product", method = RequestMethod.GET) + public Product getProduct() { + + var product = new Product(); + var productTitle = informationClient.getProductTitle(); + var productInventory = inventoryClient.getProductInventories(); + + //Fallback to error message + product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed")); + + //Fallback to default error inventory + product.setProductInventories(requireNonNullElse(productInventory, -1)); + + return product; + } +} +``` + +यहां सूचना माइक्रोसर्विस कार्यान्वयन का सार है। इन्वेंटरी माइक्रोसर्विस समान है, यह सिर्फ रिटर्न देता है +इन्वेंट्री मायने रखती है। + +```java +@RestController +public class InformationController { + @RequestMapping(value = "/information", method = RequestMethod.GET) + public String getProductTitle() { + return "The Product Title."; + } +} +``` + +अब हमारे `Aggregator` REST API को कॉल करने से उत्पाद की जानकारी मिलती है। + +```bash +curl http://localhost:50004/product +{"title":"The Product Title.","productInventories":5} +``` + +## क्लास डायग्राम + +![alt text](../../../aggregator-microservices/aggregator-service/etc/aggregator-service.png "एग्रीगेटर माइक्रोसर्विस") + +## प्रयोज्यता + +जब आपको क्लाइंट डिवाइस की परवाह किए बिना विभिन्न माइक्रोसर्विसेज के लिए एकीकृत एपीआई की आवश्यकता हो तो एग्रीगेटर माइक्रोसर्विसेज पैटर्न का उपयोग करें। + +## श्रेय + +* [Microservice Design Patterns](http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/) +* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=8b4e570267bc5fb8b8189917b461dc60) +* [Architectural Patterns: Uncover essential patterns in the most indispensable realm of enterprise architecture](https://www.amazon.com/gp/product/B077T7V8RC/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B077T7V8RC&linkId=c34d204bfe1b277914b420189f09c1a4) diff --git a/localization/hi/ambassador/README.md b/localization/hi/ambassador/README.md new file mode 100644 index 000000000000..b62870ab1060 --- /dev/null +++ b/localization/hi/ambassador/README.md @@ -0,0 +1,202 @@ +--- +title: Ambassador +category: Structural +language: hi +tag: + - Decoupling + - Cloud distributed +--- + +## हेतु + +क्लाइंट पर एक सहायक सेवा उदाहरण प्रदान करें और साझा संसाधन से सामान्य कार्यक्षमता को दूर रखें। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> एक दूरस्थ सेवा में कई ग्राहक उसके द्वारा प्रदान किए गए फ़ंक्शन तक पहुँच प्राप्त करते हैं। यह सेवा एक विरासती एप्लिकेशन है और है +> अद्यतन करना असंभव है. उपयोगकर्ताओं की ओर से बड़ी संख्या में अनुरोधों के कारण कनेक्टिविटी संबंधी समस्याएं उत्पन्न हो रही हैं। अनुरोध के लिए नए नियम +> आवृत्ति को विलंबता जांच और क्लाइंट-साइड लॉगिंग के साथ लागू किया जाना चाहिए। + +साफ़ शब्दों में + +> एंबेसेडर पैटर्न के साथ, हम विलंबता जांच के साथ-साथ ग्राहकों से कम-बार-बार मतदान लागू कर सकते हैं +> लॉगिंग. + +माइक्रोसॉफ्ट दस्तावेज़ बताता है + +> एक राजदूत सेवा को एक आउट-ऑफ-प्रोसेस प्रॉक्सी के रूप में सोचा जा सकता है जो क्लाइंट के साथ सह-स्थित होती है। यह पैटर्न +> मॉनिटरिंग, लॉगिंग, रूटिंग जैसे सामान्य क्लाइंट कनेक्टिविटी कार्यों को ऑफ़लोड करने के लिए उपयोगी हो सकता है। +> सुरक्षा (जैसे टीएलएस), और भाषा अज्ञेयवादी तरीके से लचीलापन पैटर्न। इसका उपयोग अक्सर पुराने अनुप्रयोगों के साथ किया जाता है, +> या अन्य एप्लिकेशन जिन्हें अपनी नेटवर्किंग क्षमताओं को बढ़ाने के लिए संशोधित करना मुश्किल है। यह भी हो सकता है +> उन सुविधाओं को लागू करने के लिए एक विशेष टीम को सक्षम करें। + +**प्रोग्रामेटिक उदाहरण** + +उपरोक्त परिचय को ध्यान में रखते हुए हम इस उदाहरण में कार्यक्षमता का अनुकरण करेंगे। हमने एक इंटरफ़ेस लागू किया है +दूरस्थ सेवा के साथ-साथ राजदूत सेवा द्वारा: + +```java +interface RemoteServiceInterface { + long doRemoteFunction(int value) throws Exception; +} +``` + +एक दूरस्थ सेवा को सिंगलटन के रूप में दर्शाया गया है। + +```java +@Slf4j +public class RemoteService implements RemoteServiceInterface { + private static RemoteService service = null; + + static synchronized RemoteService getRemoteService() { + if (service == null) { + service = new RemoteService(); + } + return service; + } + + private RemoteService() {} + + @Override + public long doRemoteFunction(int value) { + long waitTime = (long) Math.floor(Math.random() * 1000); + + try { + sleep(waitTime); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep interrupted", e); + } + + return waitTime >= 200 ? value * 10 : -1; + } +} +``` + +एक सेवा राजदूत लॉगिंग, विलंबता जांच जैसी अतिरिक्त सुविधाएं जोड़ रहा है + +```java +@Slf4j +public class ServiceAmbassador implements RemoteServiceInterface { + private static final int RETRIES = 3; + private static final int DELAY_MS = 3000; + + ServiceAmbassador() { + } + + @Override + public long doRemoteFunction(int value) { + return safeCall(value); + } + + private long checkLatency(int value) { + var startTime = System.currentTimeMillis(); + var result = RemoteService.getRemoteService().doRemoteFunction(value); + var timeTaken = System.currentTimeMillis() - startTime; + + LOGGER.info("Time taken (ms): " + timeTaken); + return result; + } + + private long safeCall(int value) { + var retries = 0; + var result = (long) FAILURE; + + for (int i = 0; i < RETRIES; i++) { + if (retries >= RETRIES) { + return FAILURE; + } + + if ((result = checkLatency(value)) == FAILURE) { + LOGGER.info("Failed to reach remote: (" + (i + 1) + ")"); + retries++; + try { + sleep(DELAY_MS); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep state interrupted", e); + } + } else { + break; + } + } + return result; + } +} +``` + +एक ग्राहक के पास एक स्थानीय सेवा राजदूत होता है जिसका उपयोग दूरस्थ सेवा के साथ बातचीत करने के लिए किया जाता है: + +```java +@Slf4j +public class Client { + private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador(); + + long useService(int value) { + var result = serviceAmbassador.doRemoteFunction(value); + LOGGER.info("Service result: " + result); + return result; + } +} +``` + +यहां दो ग्राहक सेवा का उपयोग कर रहे हैं। + +```java +public class App { + public static void main(String[] args) { + var host1 = new Client(); + var host2 = new Client(); + host1.useService(12); + host2.useService(73); + } +} +``` + +उदाहरण चलाने के लिए आउटपुट यहां दिया गया है: + +```java +Time taken (ms): 111 +Service result: 120 +Time taken (ms): 931 +Failed to reach remote: (1) +Time taken (ms): 665 +Failed to reach remote: (2) +Time taken (ms): 538 +Failed to reach remote: (3) +Service result: -1 +``` + +## क्लास डायग्राम + +![alt text](../../../ambassador/etc/ambassador.urm.png "Ambassador class diagram") + +## प्रयोज्यता + +एंबेसडर एक विरासती दूरस्थ सेवा के साथ काम करते समय लागू होता है जिसे संशोधित नहीं किया जा सकता है या अत्यधिक होगा +संशोधित करना कठिन. रिमोट पर बदलाव की आवश्यकता से बचते हुए क्लाइंट पर कनेक्टिविटी सुविधाएँ लागू की जा सकती हैं +सेवा। + +* राजदूत दूरस्थ सेवा के लिए एक स्थानीय इंटरफ़ेस प्रदान करता है। +* एंबेसडर क्लाइंट को लॉगिंग, सर्किट ब्रेकिंग, रिट्रीज़ और सुरक्षा प्रदान करता है। + +## विशिष्ट उपयोग का मामला + +* किसी अन्य वस्तु तक पहुंच को नियंत्रित करें +* लॉगिंग लागू करें +* सर्किट ब्रेकिंग लागू करें +* दूरस्थ सेवा कार्यों को ऑफलोड करें +* नेटवर्क कनेक्शन की सुविधा + +## ज्ञात उपयोग + +* [Kubernetes-native API gateway for microservices](https://github.com/datawire/ambassador) + +## संबंधित पैटर्न + +* [Proxy](https://java-design-patterns.com/patterns/proxy/) + +## श्रेय + +* [Ambassador pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador) +* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://www.amazon.com/s?k=designing+distributed+systems&sprefix=designing+distri%2Caps%2C156&linkCode=ll2&tag=javadesignpat-20&linkId=a12581e625462f9038557b01794e5341&language=en_US&ref_=as_li_ss_tl) diff --git a/localization/hi/api-gateway/README.md b/localization/hi/api-gateway/README.md new file mode 100644 index 000000000000..10638b553657 --- /dev/null +++ b/localization/hi/api-gateway/README.md @@ -0,0 +1,166 @@ +--- +title: API Gateway +category: Architectural +language: hi +tag: + - Cloud distributed + - Decoupling + - Microservices +--- + +## हेतु + +एक ही स्थान, एपीआई गेटवे पर माइक्रोसर्विसेज के लिए एकत्रित कॉल। उपयोगकर्ता एक ही कॉल करता है +एपीआई गेटवे पर, और एपीआई गेटवे फिर प्रत्येक प्रासंगिक माइक्रोसर्विस को कॉल करता है। + +## व्याख्या + +माइक्रोसर्विसेज पैटर्न के साथ, एक क्लाइंट को कई अलग-अलग माइक्रोसर्विसेज से डेटा की आवश्यकता हो सकती है। यदि +क्लाइंट ने प्रत्येक माइक्रोसर्विस को सीधे कॉल किया, जो लंबे समय तक लोड करने में योगदान दे सकता है +क्लाइंट को कॉल की गई प्रत्येक माइक्रोसर्विस के लिए नेटवर्क अनुरोध करना होगा। इसके अलावा, होने +क्लाइंट कॉल प्रत्येक माइक्रोसर्विस क्लाइंट को सीधे उस माइक्रोसर्विस से जोड़ती है - यदि आंतरिक है +माइक्रोसर्विसेज का कार्यान्वयन बदल जाता है (उदाहरण के लिए, यदि दो माइक्रोसर्विसेज को कभी-कभी संयोजित किया जाता है +भविष्य में) या यदि किसी माइक्रोसर्विस का स्थान (होस्ट और पोर्ट) बदलता है, तो प्रत्येक ग्राहक +उन माइक्रोसर्विसेज का उपयोग अद्यतन किया जाना चाहिए। + +एपीआई गेटवे पैटर्न का इरादा इनमें से कुछ मुद्दों को कम करना है। एपीआई गेटवे में +पैटर्न, एक अतिरिक्त इकाई (एपीआई गेटवे) क्लाइंट और माइक्रोसर्विसेज के बीच रखी गई है। +एपीआई गेटवे का काम माइक्रोसर्विसेज पर कॉल को एकत्रित करना है। ग्राहक के बजाय +प्रत्येक माइक्रोसर्विस को व्यक्तिगत रूप से कॉल करने पर, क्लाइंट एपीआई गेटवे को एक बार कॉल करता है। एपीआई +गेटवे फिर प्रत्येक माइक्रोसर्विसेज को कॉल करता है जिनकी ग्राहक को आवश्यकता होती है। + +वास्तविक दुनिया का उदाहरण + +> हम एक ई-कॉमर्स साइट के लिए माइक्रोसर्विसेज और एपीआई गेटवे पैटर्न लागू कर रहे हैं। इस व्यवस्था में +> एपीआई गेटवे इमेज और प्राइस माइक्रोसर्विसेज को कॉल करता है। + +साफ़ शब्दों में + +> माइक्रोसर्विसेज आर्किटेक्चर का उपयोग करके कार्यान्वित सिस्टम के लिए, एपीआई गेटवे एकल प्रवेश बिंदु है +> जो व्यक्तिगत माइक्रोसर्विसेज के लिए कॉलों को एकत्रित करता है। + +विकिपीडिया कहता है + +> एपीआई गेटवे एक सर्वर है जो एपीआई फ्रंट-एंड के रूप में कार्य करता है, एपीआई अनुरोध प्राप्त करता है, थ्रॉटलिंग लागू करता है +> और सुरक्षा नीतियां, अनुरोधों को बैक-एंड सेवा तक भेजती हैं और फिर प्रतिक्रिया को वापस भेजती हैं +> अनुरोधकर्ता को. एक गेटवे में अक्सर व्यवस्थित करने और संशोधित करने के लिए एक परिवर्तन इंजन शामिल होता है +> तुरंत अनुरोध और प्रतिक्रियाएँ। एक गेटवे संग्रहण जैसी कार्यक्षमता भी प्रदान कर सकता है +> एनालिटिक्स डेटा और कैशिंग प्रदान करना। गेटवे समर्थन के लिए कार्यक्षमता प्रदान कर सकता है +> प्रमाणीकरण, प्राधिकरण, सुरक्षा, ऑडिट और नियामक अनुपालन। + +**प्रोग्रामेटिक उदाहरण** + +यह कार्यान्वयन दिखाता है कि ई-कॉमर्स साइट के लिए एपीआई गेटवे पैटर्न कैसा दिख सकता है। +`ApiGateway` `ImageClientImpl` का उपयोग करके इमेज और प्राइस माइक्रोसर्विसेज को कॉल करता है और +क्रमशः `PriceClientImpl`। डेस्कटॉप डिवाइस पर साइट देखने वाले ग्राहक दोनों कीमतें देख सकते हैं +जानकारी और उत्पाद की एक छवि, इसलिए `ApiGateway` दोनों माइक्रोसर्विसेज को कॉल करता है +डेटा को `DesktopProduct` मॉडल में एकत्रित करता है। हालाँकि, मोबाइल उपयोगकर्ता केवल कीमत की जानकारी देखते हैं; +उन्हें उत्पाद की छवि नहीं दिखती. मोबाइल उपयोगकर्ताओं के लिए, `ApiGateway` केवल मूल्य प्राप्त करता है +जानकारी, जिसका उपयोग यह `MobileProduct` को पॉप्युलेट करने के लिए करता है। + +यहां इमेज माइक्रोसर्विस कार्यान्वयन है। + +```java +public interface ImageClient { + String getImagePath(); +} + +public class ImageClientImpl implements ImageClient { + @Override + public String getImagePath() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50005/image-path")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +यहां प्राइस माइक्रोसर्विस कार्यान्वयन है। + +```java +public interface PriceClient { + String getPrice(); +} + +public class PriceClientImpl implements PriceClient { + + @Override + public String getPrice() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50006/price")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +यहां हम देख सकते हैं कि एपीआई गेटवे माइक्रोसर्विसेज के अनुरोधों को कैसे मैप करता है। + +```java +public class ApiGateway { + + @Resource + private ImageClient imageClient; + + @Resource + private PriceClient priceClient; + + @RequestMapping(path = "/desktop", method = RequestMethod.GET) + public DesktopProduct getProductDesktop() { + var desktopProduct = new DesktopProduct(); + desktopProduct.setImagePath(imageClient.getImagePath()); + desktopProduct.setPrice(priceClient.getPrice()); + return desktopProduct; + } + + @RequestMapping(path = "/mobile", method = RequestMethod.GET) + public MobileProduct getProductMobile() { + var mobileProduct = new MobileProduct(); + mobileProduct.setPrice(priceClient.getPrice()); + return mobileProduct; + } +} +``` + +## क्लास डायग्राम +![alt text](../../../api-gateway/etc/api-gateway.png "API Gateway") + +## प्रयोज्यता + + एपीआई गेटवे पैटर्न का उपयोग करें जब + +* आप माइक्रोसर्विसेज आर्किटेक्चर का उपयोग कर रहे हैं और आपको अपने माइक्रोसर्विसेज कॉल के लिए एकत्रीकरण के एक बिंदु की आवश्यकता है। + +## ट्यूटोरियल + +* [Exploring the New Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway) +* [Spring Cloud - Gateway](https://www.tutorialspoint.com/spring_cloud/spring_cloud_gateway.htm) +* [Getting Started With Spring Cloud Gateway](https://dzone.com/articles/getting-started-with-spring-cloud-gateway) + +## श्रेय + +* [microservices.io - API Gateway](http://microservices.io/patterns/apigateway.html) +* [NGINX - Building Microservices: Using an API Gateway](https://www.nginx.com/blog/building-microservices-using-an-api-gateway/) +* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=ac7b6a57f866ac006a309d9086e8cfbd) +* [Building Microservices: Designing Fine-Grained Systems](https://www.amazon.com/gp/product/1491950358/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1491950358&linkId=4c95ca9831e05e3f0dadb08841d77bf1) diff --git a/localization/hi/arrange-act-assert/README.md b/localization/hi/arrange-act-assert/README.md new file mode 100644 index 000000000000..b26153e8de5c --- /dev/null +++ b/localization/hi/arrange-act-assert/README.md @@ -0,0 +1,143 @@ +--- +title: Arrange/Act/Assert +category: Idiom +language: hi +tag: + - Testing +--- + +## दूसरा नाम + +दिया/कब/तब + +## हेतु + +अरेंज/एक्ट/एसर्ट (एएए) यूनिट परीक्षणों के आयोजन के लिए एक पैटर्न है। +यह परीक्षणों को तीन स्पष्ट और विशिष्ट चरणों में विभाजित करता है: + +1. व्यवस्थित करें: परीक्षण के लिए आवश्यक सेटअप और आरंभीकरण करें। +2. अधिनियम: परीक्षण के लिए आवश्यक कार्रवाई करें। +3. दावा: परीक्षण के परिणाम सत्यापित करें। + +## व्याख्या + +इस पैटर्न के कई महत्वपूर्ण लाभ हैं. यह एक परीक्षण के बीच स्पष्ट अलगाव पैदा करता है +सेटअप, संचालन और परिणाम। यह संरचना कोड को पढ़ने और समझने में आसान बनाती है। अगर +आप चरणों को क्रम में रखते हैं और उन्हें अलग करने के लिए अपना कोड प्रारूपित करते हैं, आप एक परीक्षण स्कैन कर सकते हैं और +जल्दी से समझें कि यह क्या करता है। + +जब आप अपनी परीक्षाएँ लिखते हैं तो यह कुछ हद तक अनुशासन भी लागू करता है। आपको सोचना होगा +आपके परीक्षण द्वारा निष्पादित किए जाने वाले तीन चरणों के बारे में स्पष्ट रूप से बताएं। यह परीक्षणों को लिखने के लिए अधिक स्वाभाविक बनाता है +उसी समय, चूँकि आपके पास पहले से ही एक रूपरेखा है। + +वास्तविक दुनिया का उदाहरण + +> हमें एक कक्षा के लिए व्यापक और स्पष्ट यूनिट टेस्ट सूट लिखने की जरूरत है। + +साफ़ शब्दों में + +> अरेंज/एक्ट/एसर्ट एक परीक्षण पैटर्न है जो परीक्षणों को आसान बनाने के लिए तीन स्पष्ट चरणों में व्यवस्थित करता है +> रखरखाव। + +विकीविकीवेब कहता है + +> अरेंज/एक्ट/एसर्ट यूनिटटेस्ट विधियों में कोड को व्यवस्थित करने और फ़ॉर्मेट करने का एक पैटर्न है। + +**प्रोग्रामेटिक उदाहरण** + +आइए सबसे पहले इकाई परीक्षण के लिए अपने `Cash` वर्ग का परिचय दें। + +```java +public class Cash { + + private int amount; + + Cash(int amount) { + this.amount = amount; + } + + void plus(int addend) { + amount += addend; + } + + boolean minus(int subtrahend) { + if (amount >= subtrahend) { + amount -= subtrahend; + return true; + } else { + return false; + } + } + + int count() { + return amount; + } +} +``` + +फिर हम अपने यूनिट परीक्षण को अरेंज/एक्ट/एसर्ट पैटर्न के अनुसार लिखते हैं। स्पष्ट रूप से ध्यान दें +प्रत्येक इकाई परीक्षण के लिए अलग-अलग चरण। + +```java +class CashAAATest { + + @Test + void testPlus() { + //Arrange + var cash = new Cash(3); + //Act + cash.plus(4); + //Assert + assertEquals(7, cash.count()); + } + + @Test + void testMinus() { + //Arrange + var cash = new Cash(8); + //Act + var result = cash.minus(5); + //Assert + assertTrue(result); + assertEquals(3, cash.count()); + } + + @Test + void testInsufficientMinus() { + //Arrange + var cash = new Cash(1); + //Act + var result = cash.minus(6); + //Assert + assertFalse(result); + assertEquals(1, cash.count()); + } + + @Test + void testUpdate() { + //Arrange + var cash = new Cash(5); + //Act + cash.plus(6); + var result = cash.minus(3); + //Assert + assertTrue(result); + assertEquals(8, cash.count()); + } +} +``` + +## प्रयोज्यता + +जब अरेंज/एक्ट/एसर्ट पैटर्न का उपयोग करें + +* आपको अपने यूनिट परीक्षणों की संरचना करने की आवश्यकता है ताकि उन्हें पढ़ना, बनाए रखना और बढ़ाना आसान हो। + +## श्रेय + +* [Arrange, Act, Assert: What is AAA Testing?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx) +* [Bill Wake: 3A – Arrange, Act, Assert](https://xp123.com/articles/3a-arrange-act-assert/) +* [Martin Fowler: GivenWhenThen](https://martinfowler.com/bliki/GivenWhenThen.html) +* [xUnit Test Patterns: Refactoring Test Code](https://www.amazon.com/gp/product/0131495054/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0131495054&linkId=99701e8f4af2f7e8dd50d720c9b63dbf) +* [Unit Testing Principles, Practices, and Patterns](https://www.amazon.com/gp/product/1617296279/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617296279&linkId=74c75cf22a63c3e4758ae08aa0a0cc35) +* [Test Driven Development: By Example](https://www.amazon.com/gp/product/0321146530/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321146530&linkId=5c63a93d8c1175b84ca5087472ef0e05) diff --git a/localization/hi/async-method-invocation/README.md b/localization/hi/async-method-invocation/README.md new file mode 100644 index 000000000000..5984894dc584 --- /dev/null +++ b/localization/hi/async-method-invocation/README.md @@ -0,0 +1,170 @@ +--- +title: Async Method Invocation +category: Concurrency +language: hi +tag: + - Reactive +--- + +## हेतु + +एसिंक्रोनस विधि मंगलाचरण एक पैटर्न है जहां कॉलिंग थ्रेड होता है +कार्यों के परिणाम की प्रतीक्षा करते समय अवरुद्ध नहीं किया जाता है। पैटर्न समानांतर प्रदान करता है +अनेक स्वतंत्र कार्यों को संसाधित करना और इनके माध्यम से परिणाम प्राप्त करना +कॉलबैक या सब कुछ पूरा होने तक प्रतीक्षा करना। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +>अंतरिक्ष रॉकेट लॉन्च करना एक रोमांचक व्यवसाय है। मिशन कमांड लॉन्च करने का आदेश देता है और +> कुछ अनिश्चित समय के बाद, रॉकेट या तो सफलतापूर्वक लॉन्च होता है या बुरी तरह विफल हो जाता है। + +साफ़ शब्दों में + +> एसिंक्रोनस विधि मंगलाचरण कार्य प्रसंस्करण शुरू करता है और कार्य पूरा होने से तुरंत पहले वापस आ जाता है +> तैयार. कार्य प्रसंस्करण के परिणाम बाद में कॉल करने वाले को लौटा दिए जाते हैं। + +विकिपीडिया कहता है + +> मल्टीथ्रेडेड कंप्यूटर प्रोग्रामिंग में, एसिंक्रोनस मेथड इनवोकेशन (एएमआई) के रूप में भी जाना जाता है +> एसिंक्रोनस विधि कॉल या एसिंक्रोनस पैटर्न एक डिज़ाइन पैटर्न है जिसमें कॉल साइट +> कॉल किए गए कोड के समाप्त होने की प्रतीक्षा करते समय अवरुद्ध नहीं होता है। इसके बजाय, कॉलिंग थ्रेड है +> उत्तर आने पर सूचित किया जाएगा। उत्तर के लिए मतदान एक अवांछित विकल्प है। + +**प्रोग्रामेटिक उदाहरण** + +इस उदाहरण में, हम अंतरिक्ष रॉकेट लॉन्च कर रहे हैं और चंद्र रोवर्स तैनात कर रहे हैं। + +एप्लिकेशन एसिंक विधि मंगलाचरण पैटर्न प्रदर्शित करता है। पैटर्न के प्रमुख भाग हैं +`AsyncResult` जो अतुल्यकालिक रूप से मूल्यांकन किए गए मान के लिए एक मध्यवर्ती कंटेनर है, +`AsyncCallback` जिसे कार्य पूरा होने पर निष्पादित करने के लिए प्रदान किया जा सकता है और `AsyncExecutor` +async कार्यों के निष्पादन का प्रबंधन करता है। + +```java +public interface AsyncResult { + boolean isCompleted(); + T getValue() throws ExecutionException; + void await() throws InterruptedException; +} +``` + +```java +public interface AsyncCallback { + void onComplete(T value, Optional ex); +} +``` + +```java +public interface AsyncExecutor { + AsyncResult startProcess(Callable task); + AsyncResult startProcess(Callable task, AsyncCallback callback); + T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException; +} +``` + +`ThreadAsyncExecutor` is an implementation of `AsyncExecutor`. Some of its key parts are highlighted +next. + +```java +public class ThreadAsyncExecutor implements AsyncExecutor { + + @Override + public AsyncResult startProcess(Callable task) { + return startProcess(task, null); + } + + @Override + public AsyncResult startProcess(Callable task, AsyncCallback callback) { + var result = new CompletableResult<>(callback); + new Thread( + () -> { + try { + result.setValue(task.call()); + } catch (Exception ex) { + result.setException(ex); + } + }, + "executor-" + idx.incrementAndGet()) + .start(); + return result; + } + + @Override + public T endProcess(AsyncResult asyncResult) + throws ExecutionException, InterruptedException { + if (!asyncResult.isCompleted()) { + asyncResult.await(); + } + return asyncResult.getValue(); + } +} +``` + +फिर हम यह देखने के लिए कुछ रॉकेट लॉन्च करने के लिए तैयार हैं कि सब कुछ एक साथ कैसे काम करता है। + +```java +public static void main(String[] args) throws Exception { + // construct a new executor that will run async tasks + var executor = new ThreadAsyncExecutor(); + + // start few async tasks with varying processing times, two last with callback handlers + final var asyncResult1 = executor.startProcess(lazyval(10, 500)); + final var asyncResult2 = executor.startProcess(lazyval("test", 300)); + final var asyncResult3 = executor.startProcess(lazyval(50L, 700)); + final var asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Deploying lunar rover")); + final var asyncResult5 = + executor.startProcess(lazyval("callback", 600), callback("Deploying lunar rover")); + + // emulate processing in the current thread while async tasks are running in their own threads + Thread.sleep(350); // Oh boy, we are working hard here + log("Mission command is sipping coffee"); + + // wait for completion of the tasks + final var result1 = executor.endProcess(asyncResult1); + final var result2 = executor.endProcess(asyncResult2); + final var result3 = executor.endProcess(asyncResult3); + asyncResult4.await(); + asyncResult5.await(); + + // log the results of the tasks, callbacks log immediately when complete + log("Space rocket <" + result1 + "> launch complete"); + log("Space rocket <" + result2 + "> launch complete"); + log("Space rocket <" + result3 + "> launch complete"); +} +``` + +यहां प्रोग्राम कंसोल आउटपुट है। + +```java +21:47:08.227 [executor-2] INFO com.iluwatar.async.method.invocation.App - Space rocket launched successfully +21:47:08.269 [main] INFO com.iluwatar.async.method.invocation.App - Mission command is sipping coffee +21:47:08.318 [executor-4] INFO com.iluwatar.async.method.invocation.App - Space rocket <20> launched successfully +21:47:08.335 [executor-4] INFO com.iluwatar.async.method.invocation.App - Deploying lunar rover <20> +21:47:08.414 [executor-1] INFO com.iluwatar.async.method.invocation.App - Space rocket <10> launched successfully +21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - Space rocket launched successfully +21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - Deploying lunar rover +21:47:08.616 [executor-3] INFO com.iluwatar.async.method.invocation.App - Space rocket <50> launched successfully +21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - Space rocket <10> launch complete +21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - Space rocket launch complete +21:47:08.618 [main] INFO com.iluwatar.async.method.invocation.App - Space rocket <50> launch complete +``` + +# क्लास डायग्राम + +![alt text](../../../async-method-invocation/etc/async-method-invocation.png "Async Method Invocation") + +## प्रयोज्यता + +जब async विधि मंगलाचरण पैटर्न का उपयोग करें + +* आपके पास कई स्वतंत्र कार्य हैं जो समानांतर में चल सकते हैं +* आपको अनुक्रमिक कार्यों के समूह के प्रदर्शन में सुधार करने की आवश्यकता है +* आपके पास सीमित मात्रा में प्रसंस्करण क्षमता या लंबे समय तक चलने वाले कार्य हैं और कॉल करने वाले को कार्यों के तैयार होने का इंतजार नहीं करना चाहिए + +## वास्तविक दुनिया के उदाहरण + +* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html) +* [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) +* [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) +* [Task-based Asynchronous Pattern](https://msdn.microsoft.com/en-us/library/hh873175.aspx) diff --git a/localization/hi/balking/README.md b/localization/hi/balking/README.md new file mode 100644 index 000000000000..1365fc43c2fd --- /dev/null +++ b/localization/hi/balking/README.md @@ -0,0 +1,137 @@ +--- +title: Balking +category: Concurrency +language: hi +tag: + - Decoupling +--- + +## हेतु + +बाल्किंग पैटर्न का उपयोग किसी ऑब्जेक्ट को किसी निश्चित कोड को निष्पादित करने से रोकने के लिए किया जाता है यदि वह अधूरा है +या अनुचित स्थिति. + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> कपड़े धोने की मशीन में कपड़े धोने की शुरुआत करने के लिए एक स्टार्ट-बटन होता है। धोते समय +> मशीन निष्क्रिय है तो बटन अपेक्षानुसार काम करता है, लेकिन यदि वह पहले से ही धुलाई कर रहा है तो बटन काम करता है +> कुछ नहीं. + +साफ़ शब्दों में + +> बैल्किंग पैटर्न का उपयोग करते हुए, एक निश्चित कोड केवल तभी निष्पादित होता है जब ऑब्जेक्ट विशेष स्थिति में हो। + +विकिपीडिया कहता है + +> बैल्किंग पैटर्न एक सॉफ्टवेयर डिज़ाइन पैटर्न है जो किसी ऑब्जेक्ट पर केवल तभी क्रिया निष्पादित करता है +> वस्तु एक विशेष अवस्था में है। उदाहरण के लिए, यदि कोई ऑब्जेक्ट ज़िप फ़ाइलें और कॉलिंग पढ़ता है +> विधि ऑब्जेक्ट पर एक गेट विधि को लागू करती है जब ज़िप फ़ाइल खुली नहीं होती है, तो ऑब्जेक्ट "बाल्क" हो जाएगा +> अनुरोध पर. + +**प्रोग्रामेटिक उदाहरण** + +इस उदाहरण के कार्यान्वयन में, `WashingMachine` एक ऑब्जेक्ट है जिसमें दो स्थितियाँ हैं जिनमें यह हो सकता है +होना: सक्षम और धुलाई। यदि मशीन सक्षम है, तो थ्रेड-सेफ का उपयोग करके स्थिति वॉशिंग में बदल जाती है +तरीका। दूसरी ओर, यदि यह पहले से ही धुलाई कर रहा है और कोई अन्य थ्रेड `wash()` निष्पादित करता है +यह ऐसा नहीं करेगा और बिना कुछ किए वापस लौट आएगा। + +यहां `WashingMachine` वर्ग के प्रासंगिक भाग दिए गए हैं। + +```java +@Slf4j +public class WashingMachine { + + private final DelayProvider delayProvider; + private WashingMachineState washingMachineState; + + public WashingMachine(DelayProvider delayProvider) { + this.delayProvider = delayProvider; + this.washingMachineState = WashingMachineState.ENABLED; + } + + public WashingMachineState getWashingMachineState() { + return washingMachineState; + } + + public void wash() { + synchronized (this) { + var machineState = getWashingMachineState(); + LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState); + if (this.washingMachineState == WashingMachineState.WASHING) { + LOGGER.error("Cannot wash if the machine has been already washing!"); + return; + } + this.washingMachineState = WashingMachineState.WASHING; + } + LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); + this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing); + } + + public synchronized void endOfWashing() { + washingMachineState = WashingMachineState.ENABLED; + LOGGER.info("{}: Washing completed.", Thread.currentThread().getId()); + } +} +``` + +यहां `WashingMachine` द्वारा उपयोग किया जाने वाला सरल `DelayProvider` इंटरफ़ेस है। + +```java +public interface DelayProvider { + void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task); +} +``` + +अब हम `WashingMachine` का उपयोग करके एप्लिकेशन का परिचय देते हैं। + +```java + public static void main(String... args) { + final var washingMachine = new WashingMachine(); + var executorService = Executors.newFixedThreadPool(3); + for (int i = 0; i < 3; i++) { + executorService.execute(washingMachine::wash); + } + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + LOGGER.error("ERROR: Waiting on executor service shutdown!"); + Thread.currentThread().interrupt(); + } + } +``` + +यहां प्रोग्राम का कंसोल आउटपुट है। + +``` +14:02:52.268 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Actual machine state: ENABLED +14:02:52.272 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Doing the washing +14:02:52.272 [pool-1-thread-3] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-3: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-3] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.273 [pool-1-thread-1] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-1: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-1] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.324 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - 14: Washing completed. +``` + +## क्लास डायग्राम + +![alt text](../../../balking/etc/balking.png "Balking") + +## प्रयोज्यता + +जब बाल्किंग पैटर्न का प्रयोग करें + +* आप किसी वस्तु पर तभी कोई कार्रवाई करना चाहते हैं जब वह किसी विशेष स्थिति में हो +* वस्तुएँ आम तौर पर केवल ऐसी स्थिति में होती हैं जो अस्थायी रूप से लेकिन किसी अज्ञात के लिए झुकने की संभावना होती है + लगने वाला समय + +## संबंधित पैटर्न + +* [Guarded Suspension Pattern](https://java-design-patterns.com/patterns/guarded-suspension/) +* [Double Checked Locking Pattern](https://java-design-patterns.com/patterns/double-checked-locking/) + +## श्रेय + +* [Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML, 2nd Edition, Volume 1](https://www.amazon.com/gp/product/0471227293/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0471227293&linkId=0e39a59ffaab93fb476036fecb637b99) diff --git a/localization/hi/bridge/README.md b/localization/hi/bridge/README.md new file mode 100644 index 000000000000..1e5e4b6385ec --- /dev/null +++ b/localization/hi/bridge/README.md @@ -0,0 +1,214 @@ +--- +title: Bridge +category: Structural +language: hi +tag: + - Gang of Four +--- + +## दूसरा नाम + +हैंडल/बॉडी + +## हेतु + +इसके कार्यान्वयन से एक अमूर्त को अलग करें ताकि दोनों स्वतंत्र रूप से भिन्न हो सकें। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> विचार करें कि आपके पास विभिन्न जादूओं वाला एक हथियार है, और आपको मिश्रण की अनुमति देनी चाहिए +> अलग-अलग जादू वाले अलग-अलग हथियार। आप क्या करेंगे? प्रत्येक की एकाधिक प्रतिलिपियाँ बनाएँ +> प्रत्येक जादू के लिए हथियारों का या आप बस अलग-अलग जादू और सेट बनाएंगे +> क्या यह आवश्यकतानुसार हथियार के लिए है? ब्रिज पैटर्न आपको दूसरा करने की अनुमति देता है। + +सादे शब्दों में + +> ब्रिज पैटर्न वंशानुक्रम पर संरचना को प्राथमिकता देने के बारे में है। कार्यान्वयन विवरण आगे बढ़ाए गए हैं +> एक पदानुक्रम से दूसरे ऑब्जेक्ट पर एक अलग पदानुक्रम के साथ। + +विकिपीडिया कहता है + +> ब्रिज पैटर्न सॉफ्टवेयर इंजीनियरिंग में उपयोग किया जाने वाला एक डिज़ाइन पैटर्न है जिसका अर्थ है "इसके कार्यान्वयन से एक अमूर्तता को अलग करना ताकि दोनों स्वतंत्र रूप से भिन्न हो सकें" + +**प्रोग्रामेटिक उदाहरण** + +ऊपर से हमारे हथियार उदाहरण का अनुवाद। यहां हमारे पास `Weapon` पदानुक्रम है: + +```java +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; + } +} +``` + +यहां अलग मंत्रमुग्धता पदानुक्रम है: + +```java +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."); + } +} +``` + +यहां दोनों पदानुक्रम क्रियान्वित हैं: + +```java +LOGGER.info("The knight receives an enchanted sword."); +var enchantedSword = new Sword(new SoulEatingEnchantment()); +enchantedSword.wield(); +enchantedSword.swing(); +enchantedSword.unwield(); + +LOGGER.info("The valkyrie receives an enchanted hammer."); +var hammer = new Hammer(new FlyingEnchantment()); +hammer.wield(); +hammer.swing(); +hammer.unwield(); +``` + +यहाँ कंसोल आउटपुट है. + +``` +The knight receives an enchanted sword. +The sword is wielded. +The item spreads bloodlust. +The sword is swung. +The item eats the soul of enemies. +The sword is unwielded. +Bloodlust slowly disappears. +The valkyrie receives an enchanted hammer. +The hammer is wielded. +The item begins to glow faintly. +The hammer is swung. +The item flies and strikes the enemies finally returning to owner's hand. +The hammer is unwielded. +The item's glow fades. +``` + +## क्लास डायग्राम + +![alt text](../../../bridge/etc/bridge.urm.png "Bridge class diagram") + +## प्रयोज्यता + +जब ब्रिज पैटर्न का प्रयोग करें + +* आप किसी अमूर्तता और उसके कार्यान्वयन के बीच स्थायी बंधन से बचना चाहते हैं। यह मामला हो सकता है, उदाहरण के लिए, जब कार्यान्वयन को रन-टाइम पर चुना या स्विच किया जाना चाहिए। +* अमूर्तीकरण और उनके कार्यान्वयन दोनों को उपवर्गीकरण द्वारा विस्तार योग्य होना चाहिए। इस मामले में, ब्रिज पैटर्न आपको विभिन्न अमूर्तताओं और कार्यान्वयनों को संयोजित करने और उन्हें स्वतंत्र रूप से विस्तारित करने की सुविधा देता है। +* किसी अमूर्त के कार्यान्वयन में परिवर्तन का ग्राहकों पर कोई प्रभाव नहीं पड़ना चाहिए; अर्थात्, उनके कोड को पुनः संकलित नहीं करना पड़ेगा। +* आपके पास वर्गों का प्रसार है। ऐसा वर्ग पदानुक्रम किसी वस्तु को दो भागों में विभाजित करने की आवश्यकता को इंगित करता है। रुंबॉघ ऐसे वर्ग पदानुक्रमों को संदर्भित करने के लिए "नेस्टेड सामान्यीकरण" शब्द का उपयोग करता है। +* आप एक कार्यान्वयन को कई ऑब्जेक्ट्स के बीच साझा करना चाहते हैं (शायद संदर्भ गणना का उपयोग करके), और यह तथ्य क्लाइंट से छिपा होना चाहिए। एक सरल उदाहरण कोप्लियन का स्ट्रिंग क्लास है, जिसमें कई ऑब्जेक्ट एक ही स्ट्रिंग प्रतिनिधित्व साझा कर सकते हैं। + +## ट्यूटोरियल + +* [Bridge Pattern Tutorial](https://www.journaldev.com/1491/bridge-design-pattern-java) + +## श्रेय + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/hi/builder/README.md b/localization/hi/builder/README.md new file mode 100644 index 000000000000..61b5de7be6f9 --- /dev/null +++ b/localization/hi/builder/README.md @@ -0,0 +1,154 @@ +--- +title: Builder +category: Creational +language: hi +tag: + - Gang of Four +--- + +## हेतु + +किसी जटिल वस्तु के निर्माण को उसके प्रतिनिधित्व से अलग करें ताकि निर्माण समान हो +प्रक्रिया विभिन्न अभ्यावेदन बना सकती है। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> रोल-प्लेइंग गेम के लिए एक चरित्र जनरेटर की कल्पना करें। सबसे आसान विकल्प कंप्यूटर को चालू करना है +> अपने लिए चरित्र बनाएं. यदि आप मैन्युअल रूप से चरित्र विवरण का चयन करना चाहते हैं जैसे +> पेशा, लिंग, बालों का रंग आदि, चरित्र निर्माण एक चरण-दर-चरण प्रक्रिया बन जाती है +> सभी चयन तैयार होने पर पूरा होता है। + +साफ़ शब्दों में + +> कंस्ट्रक्टर प्रदूषण से बचते हुए आपको किसी वस्तु के विभिन्न स्वाद बनाने की अनुमति देता है। उपयोगी +>जब किसी वस्तु के कई स्वाद हो सकते हैं। या जब इसमें बहुत सारे चरण शामिल हों +> किसी वस्तु का निर्माण। + +विकिपीडिया कहता है + +> बिल्डर पैटर्न खोजने के इरादे से एक ऑब्जेक्ट निर्माण सॉफ़्टवेयर डिज़ाइन पैटर्न है +> टेलिस्कोपिंग कंस्ट्रक्टर एंटी-पैटर्न का समाधान। + +यह कहने के बाद, मैं इस बारे में थोड़ा जोड़ना चाहूंगा कि टेलीस्कोपिंग कंस्ट्रक्टर एंटी-पैटर्न क्या है। एक बिंदु पर +या अन्य, हम सभी ने नीचे जैसा एक कंस्ट्रक्टर देखा है: + +```java +public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) { +} +``` + +जैसा कि आप देख सकते हैं, कंस्ट्रक्टर मापदंडों की संख्या जल्दी से नियंत्रण से बाहर हो सकती है, और यह बन सकती है +मापदंडों की व्यवस्था को समझना कठिन है। साथ ही यह पैरामीटर सूची चालू रह सकती है +यदि आप भविष्य में और विकल्प जोड़ना चाहेंगे तो बढ़ रहा हूँ। इसे टेलिस्कोपिंग कंस्ट्रक्टर कहा जाता है +विरोधी पैटर्न. + +**प्रोग्रामेटिक उदाहरण** + +बिल्डर पैटर्न का उपयोग करना समझदारी भरा विकल्प है। सबसे पहले, हमारे पास अपना हीरो है जिसे हम चाहते हैं +बनाएं: + +```java +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; + } +} +``` + +फिर हमारे पास बिल्डर है: + +```java + 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); + } + } +``` + +तब इसका उपयोग इस प्रकार किया जा सकता है: + +```java +var mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build(); +``` + +## क्लास डायग्राम + +![alt text](../../../builder/etc/builder.urm.png "Builder class diagram") + +## प्रयोज्यता + +जब बिल्डर पैटर्न का उपयोग करें + +* एक जटिल वस्तु बनाने के लिए एल्गोरिदम उन हिस्सों से स्वतंत्र होना चाहिए जो वस्तु बनाते हैं और उन्हें कैसे इकट्ठा किया जाता है +* निर्माण प्रक्रिया में निर्मित वस्तु के लिए अलग-अलग प्रतिनिधित्व की अनुमति होनी चाहिए + +## ट्यूटोरियल + +* [Refactoring Guru](https://refactoring.guru/design-patterns/builder) +* [Oracle Blog](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) +* [Journal Dev](https://www.journaldev.com/1425/builder-design-pattern-in-java) + +## ज्ञात उपयोग + +* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) +* [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) साथ ही समान बफ़र्स जैसे फ़्लोटबफ़र, इंटबफ़र इत्यादि। +* [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) +* के सभी कार्यान्वयन [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) +* [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## श्रेय + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/hi/business-delegate/README.md b/localization/hi/business-delegate/README.md new file mode 100644 index 000000000000..bb8ae2664b78 --- /dev/null +++ b/localization/hi/business-delegate/README.md @@ -0,0 +1,162 @@ +--- +title: Business Delegate +category: Structural +language: hi +tag: + - Decoupling +--- + +## हेतु + +बिजनेस डेलीगेट पैटर्न बीच में एक अमूर्त परत जोड़ता है +प्रस्तुतिकरण और व्यावसायिक स्तर। पैटर्न का उपयोग करके हम ढीला युग्मन प्राप्त करते हैं +स्तरों के बीच और पता लगाने, कनेक्ट करने के तरीके के बारे में ज्ञान को समाहित करें, +और एप्लिकेशन बनाने वाली व्यावसायिक वस्तुओं के साथ इंटरैक्ट करें। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> एक मोबाइल फोन एप्लिकेशन आपके फोन पर मौजूदा किसी भी फिल्म को स्ट्रीम करने का वादा करता है। यह पकड़ लेता है +> उपयोगकर्ता की खोज स्ट्रिंग और इसे व्यवसाय प्रतिनिधि को भेजता है। व्यापार प्रतिनिधि +> सबसे उपयुक्त वीडियो स्ट्रीमिंग सेवा का चयन करता है और वहां से वीडियो चलाता है। + +सादे शब्दों में + +> व्यावसायिक प्रतिनिधि प्रस्तुतिकरण और व्यावसायिक स्तरों के बीच एक अमूर्त परत जोड़ता है। + +विकिपीडिया कहता है + +> बिजनेस डेलिगेट एक जावा ईई डिज़ाइन पैटर्न है। यह पैटर्न युग्मन को कम करने का निर्देश दे रहा है +> व्यावसायिक सेवाओं और कनेक्टेड प्रेजेंटेशन स्तर के बीच, और कार्यान्वयन को छिपाने के लिए +> सेवाओं का विवरण (ईजेबी आर्किटेक्चर की खोज और पहुंच सहित)। व्यापार प्रतिनिधि +> प्रेजेंटेशन स्तर से व्यावसायिक वस्तुओं को आमंत्रित करने के लिए एक एडाप्टर के रूप में कार्य करता है। + +**प्रोग्रामेटिक उदाहरण** + +सबसे पहले, हमारे पास वीडियो स्ट्रीमिंग सेवाओं और कुछ कार्यान्वयन के लिए एक सार है। + +```java +public interface VideoStreamingService { + void doProcessing(); +} + +@Slf4j +public class NetflixService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("NetflixService is now processing"); + } +} + +@Slf4j +public class YouTubeService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("YouTubeService is now processing"); + } +} +``` + +फिर हमारे पास एक लुकअप सेवा है जो यह तय करती है कि कौन सी वीडियो स्ट्रीमिंग सेवा का उपयोग किया जाए। + +```java +@Setter +public class BusinessLookup { + + private NetflixService netflixService; + private YouTubeService youTubeService; + + public VideoStreamingService getBusinessService(String movie) { + if (movie.toLowerCase(Locale.ROOT).contains("die hard")) { + return netflixService; + } else { + return youTubeService; + } + } +} +``` + +व्यवसाय प्रतिनिधि मूवी प्लेबैक अनुरोधों को उपयुक्त स्थान पर रूट करने के लिए व्यवसाय लुकअप का उपयोग करता है +वीडियो स्ट्रीमिंग सेवा. + +```java +@Setter +public class BusinessDelegate { + + private BusinessLookup lookupService; + + public void playbackMovie(String movie) { + VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie); + videoStreamingService.doProcessing(); + } +} +``` + +मोबाइल क्लाइंट व्यवसाय स्तर पर कॉल करने के लिए व्यवसाय प्रतिनिधि का उपयोग करता है। + +```java +public class MobileClient { + + private final BusinessDelegate businessDelegate; + + public MobileClient(BusinessDelegate businessDelegate) { + this.businessDelegate = businessDelegate; + } + + public void playbackMovie(String movie) { + businessDelegate.playbackMovie(movie); + } +} +``` + +अंत में, हम कार्रवाई में पूरा उदाहरण दिखा सकते हैं। + +```java + public static void main(String[] args) { + + // prepare the objects + var businessDelegate = new BusinessDelegate(); + var businessLookup = new BusinessLookup(); + businessLookup.setNetflixService(new NetflixService()); + businessLookup.setYouTubeService(new YouTubeService()); + businessDelegate.setLookupService(businessLookup); + + // create the client and use the business delegate + var client = new MobileClient(businessDelegate); + client.playbackMovie("Die Hard 2"); + client.playbackMovie("Maradona: The Greatest Ever"); + } +``` + +यहाँ कंसोल आउटपुट है. + +``` +21:15:33.790 [main] INFO com.iluwatar.business.delegate.NetflixService - NetflixService is now processing +21:15:33.794 [main] INFO com.iluwatar.business.delegate.YouTubeService - YouTubeService is now processing +``` + +## क्लास डायग्राम + +![alt text](../../../business-delegate/etc/business-delegate.urm.png "Business Delegate") + +## संबंधित पैटर्न + +* [Service locator pattern](https://java-design-patterns.com/patterns/service-locator/) + +## प्रयोज्यता + +बिजनेस डेलीगेट पैटर्न का उपयोग कब करें + +* आप प्रस्तुतिकरण और व्यावसायिक स्तरों के बीच ढीला युग्मन चाहते हैं +* आप एकाधिक व्यावसायिक सेवाओं के लिए कॉल व्यवस्थित करना चाहते हैं +* आप सेवा लुकअप और सेवा कॉल को समाहित करना चाहते हैं + +## ट्यूटोरियल + +* [Business Delegate Pattern at TutorialsPoint](https://www.tutorialspoint.com/design_pattern/business_delegate_pattern.htm) + +## Credits + +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Core J2EE Patterns: Best Practices and Design Strategies](https://www.amazon.com/gp/product/0130648841/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0130648841&linkId=a0100de2b28c71ede8db1757fb2b5947) diff --git a/localization/hi/bytecode/README.md b/localization/hi/bytecode/README.md new file mode 100644 index 000000000000..65eee72580d3 --- /dev/null +++ b/localization/hi/bytecode/README.md @@ -0,0 +1,241 @@ +--- +title: Bytecode +category: Behavioral +language: hi +tag: + - Game programming +--- + +## हेतु + +वर्चुअल मशीन के लिए निर्देशों के रूप में एन्कोडिंग व्यवहार की अनुमति देता है। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> एक टीम एक नए गेम पर काम कर रही है जहां जादूगर एक-दूसरे के खिलाफ लड़ते हैं। जादूगर का व्यवहार +> प्लेटेस्टिंग के माध्यम से सैकड़ों बार सावधानीपूर्वक समायोजित और पुनरावृत्त करने की आवश्यकता है। यह +> हर बार जब गेम डिजाइनर बदलाव करना चाहता है तो प्रोग्रामर से बदलाव करने के लिए कहना सबसे अच्छा है +> व्यवहार, इसलिए विज़ार्ड व्यवहार को डेटा-संचालित वर्चुअल मशीन के रूप में कार्यान्वित किया जाता है। + +साफ़ शब्दों में + +> बाइटकोड पैटर्न कोड के बजाय डेटा द्वारा संचालित व्यवहार को सक्षम बनाता है। + +[Gameprogrammingpatterns.com](https://gameprogrammingpatterns.com/bytecode.html) प्रलेखन +बताता है: + +> एक निर्देश सेट निम्न-स्तरीय संचालन को परिभाषित करता है जिन्हें निष्पादित किया जा सकता है। की एक श्रृंखला +> निर्देश बाइट्स के अनुक्रम के रूप में एन्कोड किया गया है। एक वर्चुअल मशीन इन निर्देशों को एक-एक करके क्रियान्वित करती है +> एक समय में, मध्यवर्ती मानों के लिए स्टैक का उपयोग करना। अनुदेशों के संयोजन से, जटिल उच्च-स्तरीय +> व्यवहार को परिभाषित किया जा सकता है। + +**प्रोग्रामेटिक उदाहरण** + +सबसे महत्वपूर्ण गेम ऑब्जेक्ट में से एक `Wizard` वर्ग है। + +```java +@AllArgsConstructor +@Setter +@Getter +@Slf4j +public class Wizard { + + private int health; + private int agility; + private int wisdom; + private int numberOfPlayedSounds; + private int numberOfSpawnedParticles; + + public void playSound() { + LOGGER.info("Playing sound"); + numberOfPlayedSounds++; + } + + public void spawnParticles() { + LOGGER.info("Spawning particles"); + numberOfSpawnedParticles++; + } +} +``` + +इसके बाद, हम अपनी वर्चुअल मशीन के लिए उपलब्ध निर्देश दिखाते हैं। प्रत्येक निर्देश का अपना है +यह स्टैक डेटा के साथ कैसे संचालित होता है, इसका अपना शब्दार्थ। उदाहरण के लिए, ADD निर्देश शीर्ष पर है +स्टैक से दो आइटम, उन्हें एक साथ जोड़ता है और परिणाम को स्टैक पर भेजता है। + +```java +@AllArgsConstructor +@Getter +public enum Instruction { + + LITERAL(1), // e.g. "LITERAL 0", push 0 to stack + SET_HEALTH(2), // e.g. "SET_HEALTH", pop health and wizard number, call set health + SET_WISDOM(3), // e.g. "SET_WISDOM", pop wisdom and wizard number, call set wisdom + SET_AGILITY(4), // e.g. "SET_AGILITY", pop agility and wizard number, call set agility + PLAY_SOUND(5), // e.g. "PLAY_SOUND", pop value as wizard number, call play sound + SPAWN_PARTICLES(6), // e.g. "SPAWN_PARTICLES", pop value as wizard number, call spawn particles + GET_HEALTH(7), // e.g. "GET_HEALTH", pop value as wizard number, push wizard's health + GET_AGILITY(8), // e.g. "GET_AGILITY", pop value as wizard number, push wizard's agility + GET_WISDOM(9), // e.g. "GET_WISDOM", pop value as wizard number, push wizard's wisdom + ADD(10), // e.g. "ADD", pop 2 values, push their sum + DIVIDE(11); // e.g. "DIVIDE", pop 2 values, push their division + // ... +} +``` + +हमारे उदाहरण के केंद्र में `VirtualMachine` वर्ग है। यह निर्देशों को इनपुट के रूप में लेता है और +गेम ऑब्जेक्ट व्यवहार प्रदान करने के लिए उन्हें निष्पादित करता है। + +```java +@Getter +@Slf4j +public class VirtualMachine { + + private final Stack stack = new Stack<>(); + + private final Wizard[] wizards = new Wizard[2]; + + public VirtualMachine() { + wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), + 0, 0); + wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), + 0, 0); + } + + public VirtualMachine(Wizard wizard1, Wizard wizard2) { + wizards[0] = wizard1; + wizards[1] = wizard2; + } + + public void execute(int[] bytecode) { + for (var i = 0; i < bytecode.length; i++) { + Instruction instruction = Instruction.getInstruction(bytecode[i]); + switch (instruction) { + case LITERAL: + // Read the next byte from the bytecode. + int value = bytecode[++i]; + // Push the next value to stack + stack.push(value); + break; + case SET_AGILITY: + var amount = stack.pop(); + var wizard = stack.pop(); + setAgility(wizard, amount); + break; + case SET_WISDOM: + amount = stack.pop(); + wizard = stack.pop(); + setWisdom(wizard, amount); + break; + case SET_HEALTH: + amount = stack.pop(); + wizard = stack.pop(); + setHealth(wizard, amount); + break; + case GET_HEALTH: + wizard = stack.pop(); + stack.push(getHealth(wizard)); + break; + case GET_AGILITY: + wizard = stack.pop(); + stack.push(getAgility(wizard)); + break; + case GET_WISDOM: + wizard = stack.pop(); + stack.push(getWisdom(wizard)); + break; + case ADD: + var a = stack.pop(); + var b = stack.pop(); + stack.push(a + b); + break; + case DIVIDE: + a = stack.pop(); + b = stack.pop(); + stack.push(b / a); + break; + case PLAY_SOUND: + wizard = stack.pop(); + getWizards()[wizard].playSound(); + break; + case SPAWN_PARTICLES: + wizard = stack.pop(); + getWizards()[wizard].spawnParticles(); + break; + default: + throw new IllegalArgumentException("Invalid instruction value"); + } + LOGGER.info("Executed " + instruction.name() + ", Stack contains " + getStack()); + } + } + + public void setHealth(int wizard, int amount) { + wizards[wizard].setHealth(amount); + } + // other setters -> + // ... +} +``` + +अब हम वर्चुअल मशीन का उपयोग करके पूरा उदाहरण दिखा सकते हैं। + +```java + public static void main(String[] args) { + + var vm = new VirtualMachine( + new Wizard(45, 7, 11, 0, 0), + new Wizard(36, 18, 8, 0, 0)); + + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_HEALTH")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_AGILITY")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_WISDOM")); + vm.execute(InstructionConverterUtil.convertToByteCode("ADD")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 2")); + vm.execute(InstructionConverterUtil.convertToByteCode("DIVIDE")); + vm.execute(InstructionConverterUtil.convertToByteCode("ADD")); + vm.execute(InstructionConverterUtil.convertToByteCode("SET_HEALTH")); + } +``` + +यहाँ कंसोल आउटपुट है. + +``` +16:20:10.193 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0] +16:20:10.196 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_HEALTH, Stack contains [0, 45] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_AGILITY, Stack contains [0, 45, 7] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 7, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_WISDOM, Stack contains [0, 45, 7, 11] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 45, 18] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 18, 2] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed DIVIDE, Stack contains [0, 45, 9] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 54] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed SET_HEALTH, Stack contains [] +``` + +## क्लास डायग्राम + +![alt text](../../../bytecode/etc/bytecode.urm.png "Bytecode class diagram") + +## प्रयोज्यता + +जब आपके पास बहुत सारे व्यवहार हों जिन्हें आपको परिभाषित करने की आवश्यकता हो तो बाइटकोड पैटर्न का उपयोग करें +गेम की कार्यान्वयन भाषा उपयुक्त नहीं है क्योंकि: + +* यह बहुत निम्न स्तर का है, जिससे इसे प्रोग्राम करना कठिन या त्रुटि-प्रवण हो जाता है। +* धीमे संकलन समय या अन्य टूलींग समस्याओं के कारण इस पर पुनरावृत्ति करने में बहुत अधिक समय लगता है। +* इस पर बहुत ज्यादा भरोसा है. यदि आप यह सुनिश्चित करना चाहते हैं कि परिभाषित किया जा रहा व्यवहार गेम को तोड़ न सके, तो आपको इसे शेष कोडबेस से सैंडबॉक्स करना होगा। + +## संबंधित पैटर्न + +* [Interpreter](https://java-design-patterns.com/patterns/interpreter/) + +## श्रेय + +* [Game programming patterns](http://gameprogrammingpatterns.com/bytecode.html) diff --git a/localization/hi/caching/README.md b/localization/hi/caching/README.md new file mode 100644 index 000000000000..967be7dca43f --- /dev/null +++ b/localization/hi/caching/README.md @@ -0,0 +1,342 @@ +--- +title: Caching +category: Behavioral +language: hi +tag: + - Performance + - Cloud distributed +--- + +## हेतु + +कैशिंग पैटर्न संसाधनों को तुरंत जारी न करके उनके महंगे पुन: अधिग्रहण से बचाता है +उपयोग के बाद। संसाधन अपनी पहचान बनाए रखते हैं, कुछ तेज़-पहुँच वाले भंडारण में रखे जाते हैं, और हैं +उन्हें दोबारा प्राप्त करने से बचने के लिए पुन: उपयोग किया जाता है। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> एक टीम एक ऐसी वेबसाइट पर काम कर रही है जो परित्यक्त बिल्लियों के लिए नए घर उपलब्ध कराती है। लोग अपनी पोस्ट कर सकते हैं +> पंजीकरण के बाद वेबसाइट पर बिल्लियाँ, लेकिन सभी नए पोस्ट के लिए इनमें से किसी एक से अनुमोदन की आवश्यकता होती है +> साइट मॉडरेटर. साइट मॉडरेटर के उपयोगकर्ता खातों में एक विशिष्ट ध्वज और डेटा होता है +> MongoDB डेटाबेस में संग्रहीत है। हर बार पोस्ट देखे जाने पर मॉडरेटर फ़्लैग की जाँच करना +> महंगा हो जाता है और यहां कैशिंग का उपयोग करना एक अच्छा विचार है। + +साफ़ शब्दों में + +> कैशिंग पैटर्न प्रदर्शन को बेहतर बनाने के लिए अक्सर आवश्यक डेटा को फास्ट-एक्सेस स्टोरेज में रखता है। + +विकिपीडिया कहता है: + +> कंप्यूटिंग में, कैश एक हार्डवेयर या सॉफ़्टवेयर घटक है जो भविष्य में डेटा संग्रहीत करता है +> उस डेटा के लिए अनुरोध तेजी से प्रस्तुत किए जा सकते हैं; कैश में संग्रहीत डेटा का परिणाम हो सकता है +> पहले की गणना या अन्यत्र संग्रहीत डेटा की एक प्रति। अनुरोध किए जाने पर कैश हिट होता है +> डेटा कैश में पाया जा सकता है, जबकि कैश मिस तब होता है जब ऐसा नहीं हो पाता। कैश हिट द्वारा परोसे जाते हैं +> कैश से डेटा पढ़ना, जो किसी परिणाम की पुन: गणना करने या धीमी गति से पढ़ने की तुलना में तेज़ है +> डेटा स्टोर; इस प्रकार, कैश से जितने अधिक अनुरोध दिए जा सकेंगे, सिस्टम उतना ही तेज़ होगा +> प्रदर्शन करता है. + +**प्रोग्रामेटिक उदाहरण** + +आइए सबसे पहले हमारे एप्लिकेशन के डेटा स्तर को देखें। दिलचस्प कक्षाएं `UserAccount` हैं +जो एक सरल जावा ऑब्जेक्ट है जिसमें उपयोगकर्ता खाता विवरण और `DbManager` इंटरफ़ेस शामिल है जो संभालता है +डेटाबेस से/इन ऑब्जेक्ट को पढ़ना और लिखना। + +```java +@Data +@AllArgsConstructor +@ToString +@EqualsAndHashCode +public class UserAccount { + private String userId; + private String userName; + private String additionalInfo; +} + +public interface DbManager { + + void connect(); + void disconnect(); + + UserAccount readFromDb(String userId); + UserAccount writeToDb(UserAccount userAccount); + UserAccount updateDb(UserAccount userAccount); + UserAccount upsertDb(UserAccount userAccount); +} +``` + +उदाहरण में, हम विभिन्न कैशिंग नीतियों का प्रदर्शन कर रहे हैं + +* राइट-थ्रू एक ही लेनदेन में कैश और डीबी में डेटा लिखता है +* राइट-अराउंड डेटा को कैश के बजाय तुरंत डीबी में लिखता है +* राइट-बैक शुरू में डेटा को कैश में लिखता है जबकि डेटा केवल डीबी में लिखा जाता है + जब कैश भर जाए +* कैश-साइड दोनों डेटा स्रोतों में डेटा को सिंक्रनाइज़ रखने की ज़िम्मेदारी को आगे बढ़ाता है + आवेदन ही +* उपरोक्त रणनीतियों में रीड-थ्रू रणनीति भी शामिल है और यह डेटा लौटाती है + यदि यह मौजूद है तो कॉल करने वाले को कैश, अन्यथा डीबी से क्वेरी करता है और इसे कैश में संग्रहीत करता है + भविष्य के काम। + +`LruCache` में कैश कार्यान्वयन एक डबल के साथ एक हैश तालिका है +लिंक्ड सूची। लिंक्ड-लिस्ट कैश में एलआरयू डेटा को कैप्चर करने और बनाए रखने में मदद करती है। कब +डेटा को क्वेरी किया जाता है (कैश से), जोड़ा जाता है (कैश में), या अपडेट किया जाता है, डेटा को सामने ले जाया जाता है +सूची में खुद को सबसे हाल ही में उपयोग किए गए डेटा के रूप में दर्शाया गया है। एलआरयू डेटा हमेशा अंत में होता है +सूची। + +```java +@Slf4j +public class LruCache { + + static class Node { + String userId; + UserAccount userAccount; + Node previous; + Node next; + + public Node(String userId, UserAccount userAccount) { + this.userId = userId; + this.userAccount = userAccount; + } + } + + /* ... omitted details ... */ + + public LruCache(int capacity) { + this.capacity = capacity; + } + + public UserAccount get(String userId) { + if (cache.containsKey(userId)) { + var node = cache.get(userId); + remove(node); + setHead(node); + return node.userAccount; + } + return null; + } + + public void set(String userId, UserAccount userAccount) { + if (cache.containsKey(userId)) { + var old = cache.get(userId); + old.userAccount = userAccount; + remove(old); + setHead(old); + } else { + var newNode = new Node(userId, userAccount); + if (cache.size() >= capacity) { + LOGGER.info("# Cache is FULL! Removing {} from cache...", end.userId); + cache.remove(end.userId); // remove LRU data from cache. + remove(end); + setHead(newNode); + } else { + setHead(newNode); + } + cache.put(userId, newNode); + } + } + + public boolean contains(String userId) { + return cache.containsKey(userId); + } + + public void remove(Node node) { /* ... */ } + public void setHead(Node node) { /* ... */ } + public void invalidate(String userId) { /* ... */ } + public boolean isFull() { /* ... */ } + public UserAccount getLruData() { /* ... */ } + public void clear() { /* ... */ } + public List getCacheDataInListForm() { /* ... */ } + public void setCapacity(int newCapacity) { /* ... */ } +} +``` + +अगली परत जिसे हम देखने जा रहे हैं वह `CacheStore` है जो विभिन्न कैशिंग को लागू करती है +रणनीतियाँ। + +```java +@Slf4j +public class CacheStore { + + private static final int CAPACITY = 3; + private static LruCache cache; + private final DbManager dbManager; + + /* ... details omitted ... */ + + public UserAccount readThrough(final String userId) { + if (cache.contains(userId)) { + LOGGER.info("# Found in Cache!"); + return cache.get(userId); + } + LOGGER.info("# Not found in cache! Go to DB!!"); + UserAccount userAccount = dbManager.readFromDb(userId); + cache.set(userId, userAccount); + return userAccount; + } + + public void writeThrough(final UserAccount userAccount) { + if (cache.contains(userAccount.getUserId())) { + dbManager.updateDb(userAccount); + } else { + dbManager.writeToDb(userAccount); + } + cache.set(userAccount.getUserId(), userAccount); + } + + public void writeAround(final UserAccount userAccount) { + if (cache.contains(userAccount.getUserId())) { + dbManager.updateDb(userAccount); + // Cache data has been updated -- remove older + cache.invalidate(userAccount.getUserId()); + // version from cache. + } else { + dbManager.writeToDb(userAccount); + } + } + + public static void clearCache() { + if (cache != null) { + cache.clear(); + } + } + + public static void flushCache() { + LOGGER.info("# flushCache..."); + Optional.ofNullable(cache) + .map(LruCache::getCacheDataInListForm) + .orElse(List.of()) + .forEach(DbManager::updateDb); + } + + /* ... omitted the implementation of other caching strategies ... */ + +} +``` + +`AppManager` मुख्य वर्ग और एप्लिकेशन के बीच संचार में अंतर को पाटने में मदद करता है +पिछला भाग। इस वर्ग के माध्यम से DB कनेक्शन प्रारंभ किया जाता है। चुनी गई कैशिंग रणनीति/नीति है +यहाँ भी आरंभ किया गया। कैश का उपयोग करने से पहले, कैश का आकार सेट करना होगा। निर्भर करता है +चुनी गई कैशिंग नीति पर, `AppManager` `CacheStore` में उपयुक्त फ़ंक्शन को कॉल करेगा +कक्षा। + +```java +@Slf4j +public final class AppManager { + + private static CachingPolicy cachingPolicy; + private final DbManager dbManager; + private final CacheStore cacheStore; + + private AppManager() { + } + + public void initDb() { /* ... */ } + + public static void initCachingPolicy(CachingPolicy policy) { /* ... */ } + + public static void initCacheCapacity(int capacity) { /* ... */ } + + public UserAccount find(final String userId) { + LOGGER.info("Trying to find {} in cache", userId); + if (cachingPolicy == CachingPolicy.THROUGH + || cachingPolicy == CachingPolicy.AROUND) { + return cacheStore.readThrough(userId); + } else if (cachingPolicy == CachingPolicy.BEHIND) { + return cacheStore.readThroughWithWriteBackPolicy(userId); + } else if (cachingPolicy == CachingPolicy.ASIDE) { + return findAside(userId); + } + return null; + } + + public void save(final UserAccount userAccount) { + LOGGER.info("Save record!"); + if (cachingPolicy == CachingPolicy.THROUGH) { + cacheStore.writeThrough(userAccount); + } else if (cachingPolicy == CachingPolicy.AROUND) { + cacheStore.writeAround(userAccount); + } else if (cachingPolicy == CachingPolicy.BEHIND) { + cacheStore.writeBehind(userAccount); + } else if (cachingPolicy == CachingPolicy.ASIDE) { + saveAside(userAccount); + } + } + + public static String printCacheContent() { + return CacheStore.print(); + } + + /* ... details omitted ... */ +} +``` + +एप्लिकेशन के मुख्य वर्ग में हम यही करते हैं। + +```java +@Slf4j +public class App { + + public static void main(final String[] args) { + boolean isDbMongo = isDbMongo(args); + if(isDbMongo){ + LOGGER.info("Using the Mongo database engine to run the application."); + } else { + LOGGER.info("Using the 'in Memory' database to run the application."); + } + App app = new App(isDbMongo); + app.useReadAndWriteThroughStrategy(); + String splitLine = "=============================================="; + LOGGER.info(splitLine); + app.useReadThroughAndWriteAroundStrategy(); + LOGGER.info(splitLine); + app.useReadThroughAndWriteBehindStrategy(); + LOGGER.info(splitLine); + app.useCacheAsideStategy(); + LOGGER.info(splitLine); + } + + public void useReadAndWriteThroughStrategy() { + LOGGER.info("# CachingPolicy.THROUGH"); + appManager.initCachingPolicy(CachingPolicy.THROUGH); + + var userAccount1 = new UserAccount("001", "John", "He is a boy."); + + appManager.save(userAccount1); + LOGGER.info(appManager.printCacheContent()); + appManager.find("001"); + appManager.find("001"); + } + + public void useReadThroughAndWriteAroundStrategy() { /* ... */ } + + public void useReadThroughAndWriteBehindStrategy() { /* ... */ } + + public void useCacheAsideStategy() { /* ... */ } +} +``` + +## क्लास डायग्राम + +![alt text](../../../caching/etc/caching.png "Caching") + +## प्रयोज्यता + +जब कैशिंग पैटर्न का उपयोग करें + +* एक ही संसाधन का बार-बार अधिग्रहण, आरंभीकरण और जारी करना अनावश्यक कारण बनता है + प्रदर्शन उपरि. + +## संबंधित पैटर्न + +* [Proxy](https://java-design-patterns.com/patterns/proxy/) + +## श्रेय + +* [Write-through, write-around, write-back: Cache explained](http://www.computerweekly.com/feature/Write-through-write-around-write-back-Cache-explained) +* [Read-Through, Write-Through, Write-Behind, and Refresh-Ahead Caching](https://docs.oracle.com/cd/E15357_01/coh.360/e15723/cache_rtwtwbra.htm#COHDG5177) +* [Cache-Aside pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/cache-aside) +* [Java EE 8 High Performance: Master techniques such as memory optimization, caching, concurrency, and multithreading to achieve maximum performance from your enterprise applications](https://www.amazon.com/gp/product/178847306X/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=178847306X&linkId=e948720055599f248cdac47da9125ff4) +* [Java Performance: In-Depth Advice for Tuning and Programming Java 8, 11, and Beyond](https://www.amazon.com/gp/product/1492056111/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1492056111&linkId=7e553581559b9ec04221259e52004b08) +* [Effective Java](https://www.amazon.com/gp/product/B078H61SCH/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B078H61SCH&linkId=f06607a0b48c76541ef19c5b8b9e7882) +* [Java Performance: The Definitive Guide: Getting the Most Out of Your Code](https://www.amazon.com/gp/product/1449358454/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1449358454&linkId=475c18363e350630cc0b39ab681b2687) diff --git a/localization/hi/callback/README.md b/localization/hi/callback/README.md new file mode 100644 index 000000000000..3d68338b0ead --- /dev/null +++ b/localization/hi/callback/README.md @@ -0,0 +1,84 @@ +--- +title: Callback +category: Idiom +language: hi +tag: + - Reactive +--- + +## हेतु + +कॉलबैक निष्पादन योग्य कोड का एक टुकड़ा है जिसे अन्य कोड के तर्क के रूप में पारित किया जाता है +किसी सुविधाजनक समय पर तर्क को वापस बुलाने (निष्पादित) करने की अपेक्षा की जाती है। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +>कार्य निष्पादन समाप्त होने के बाद हमें सूचित किया जाना आवश्यक है। हम इसके लिए कॉलबैक विधि पास करते हैं +> निष्पादक और उसके हमें वापस बुलाने की प्रतीक्षा करें। + +साफ़ शब्दों में + +> कॉलबैक निष्पादक को दी गई एक विधि है जिसे निर्धारित समय पर कॉल किया जाएगा। + +विकिपीडिया कहता है + +> कंप्यूटर प्रोग्रामिंग में, कॉलबैक, जिसे "कॉल-आफ्टर" फ़ंक्शन के रूप में भी जाना जाता है, कोई भी निष्पादन योग्य है +> वह कोड जो अन्य कोड के तर्क के रूप में पारित किया जाता है; उस अन्य कोड को कॉल करने की उम्मीद है +> किसी निश्चित समय पर तर्क को वापस (निष्पादित) करें। + +**प्रोग्रामेटिक उदाहरण** + +कॉलबैक एकल विधि वाला एक सरल इंटरफ़ेस है। + +```java +public interface Callback { + + void call(); +} +``` + +आगे हम एक कार्य को परिभाषित करते हैं जो कार्य निष्पादन समाप्त होने के बाद कॉलबैक निष्पादित करेगा। + +```java +public abstract class Task { + + final void executeWith(Callback callback) { + execute(); + Optional.ofNullable(callback).ifPresent(Callback::call); + } + + public abstract void execute(); +} + +@Slf4j +public final class SimpleTask extends Task { + + @Override + public void execute() { + LOGGER.info("Perform some important activity and after call the callback method."); + } +} +``` + +अंत में, यहां बताया गया है कि हम किसी कार्य को कैसे निष्पादित करते हैं और उसके समाप्त होने पर कॉलबैक प्राप्त करते हैं। + +```java + var task = new SimpleTask(); + task.executeWith(() -> LOGGER.info("I'm done now.")); +``` + +## क्लास डायग्राम + +![alt text](../../../callback/etc/callback.png "Callback") + +## प्रयोज्यता + +जब कॉलबैक पैटर्न का उपयोग करें + +* जब कुछ परिभाषित गतिविधि के निष्पादन के बाद कुछ मनमाना सिंक्रोनस या एसिंक्रोनस क्रिया निष्पादित की जानी चाहिए। + +## वास्तविक दुनिया के उदाहरण + +* [CyclicBarrier](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) कंस्ट्रक्टर एक कॉलबैक स्वीकार कर सकता है जो हर बार बैरियर ट्रिप होने पर ट्रिगर हो जाएगा। diff --git a/localization/hi/chain-of-responsibility/README.md b/localization/hi/chain-of-responsibility/README.md new file mode 100644 index 000000000000..c058484d4216 --- /dev/null +++ b/localization/hi/chain-of-responsibility/README.md @@ -0,0 +1,173 @@ +--- +title: Chain of responsibility +category: Behavioral +language: hi +tag: + - Gang of Four +--- + +## हेतु + +एक से अधिक ऑब्जेक्ट को मौका देकर अनुरोध भेजने वाले को उसके प्राप्तकर्ता से जोड़ने से बचें +अनुरोध संभालें. प्राप्त वस्तुओं को श्रृंखलाबद्ध करें और किसी वस्तु तक श्रृंखला के साथ अनुरोध को पास करें +इसे संभालता है. + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> ऑर्क किंग अपनी सेना को ऊंचे स्वर में आदेश देता है। फिर, प्रतिक्रिया देने वाला सबसे करीबी व्यक्ति कमांडर होता है +> एक अधिकारी, और फिर एक सैनिक। कमांडर, अधिकारी और सैनिक जिम्मेदारी की एक श्रृंखला बनाते हैं। + +साफ़ शब्दों में + +> यह वस्तुओं की श्रृंखला बनाने में मदद करता है। एक अनुरोध एक छोर से प्रवेश करता है और एक वस्तु से जाता रहता है +> दूसरे को तब तक भेजें जब तक उसे कोई उपयुक्त हैंडलर न मिल जाए। + +विकिपीडिया कहता है + +> ऑब्जेक्ट-ओरिएंटेड डिज़ाइन में, श्रृंखला-की-जिम्मेदारी पैटर्न एक डिज़ाइन पैटर्न है जिसमें शामिल है +> कमांड ऑब्जेक्ट का एक स्रोत और प्रोसेसिंग ऑब्जेक्ट की एक श्रृंखला। प्रत्येक प्रोसेसिंग ऑब्जेक्ट में शामिल है +> तर्क जो कमांड ऑब्जेक्ट के प्रकार को परिभाषित करता है जिसे वह संभाल सकता है; बाकी को पास कर दिया गया है +> श्रृंखला में अगली प्रसंस्करण वस्तु। + +**प्रोग्रामेटिक उदाहरण** + +ऊपर से ओर्क्स के साथ हमारे उदाहरण का अनुवाद करना। सबसे पहले, हमारे पास `Request` वर्ग है: + +```java +public class Request { + + private final RequestType requestType; + private final String requestDescription; + private boolean handled; + + public Request(final RequestType requestType, final String requestDescription) { + this.requestType = Objects.requireNonNull(requestType); + this.requestDescription = Objects.requireNonNull(requestDescription); + } + + public String getRequestDescription() { return requestDescription; } + + public RequestType getRequestType() { return requestType; } + + public void markHandled() { this.handled = true; } + + public boolean isHandled() { return this.handled; } + + @Override + public String toString() { return getRequestDescription(); } +} + +public enum RequestType { + DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX +} +``` + +इसके बाद, हम अनुरोध हैंडलर पदानुक्रम दिखाते हैं। + +```java +public interface RequestHandler { + + boolean canHandleRequest(Request req); + + int getPriority(); + + void handle(Request req); + + String name(); +} + +@Slf4j +public class OrcCommander implements RequestHandler { + @Override + public boolean canHandleRequest(Request req) { + return req.getRequestType() == RequestType.DEFEND_CASTLE; + } + + @Override + public int getPriority() { + return 2; + } + + @Override + public void handle(Request req) { + req.markHandled(); + LOGGER.info("{} handling request \"{}\"", name(), req); + } + + @Override + public String name() { + return "Orc commander"; + } +} + +// OrcOfficer and OrcSoldier are defined similarly as OrcCommander + +``` + +ऑर्क किंग आदेश देता है और श्रृंखला बनाता है। + +```java +public class OrcKing { + + private List handlers; + + public OrcKing() { + buildChain(); + } + + private void buildChain() { + handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier()); + } + + public void makeRequest(Request req) { + handlers + .stream() + .sorted(Comparator.comparing(RequestHandler::getPriority)) + .filter(handler -> handler.canHandleRequest(req)) + .findFirst() + .ifPresent(handler -> handler.handle(req)); + } +} +``` + +कार्रवाई में जिम्मेदारी की श्रृंखला. + +```java +var king = new OrcKing(); +king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); +king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); +king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); +``` + +कंसोल आउटपुट. + +``` +Orc commander handling request "defend castle" +Orc officer handling request "torture prisoner" +Orc soldier handling request "collect tax" +``` + +## क्लास डायग्राम + +![alt text](../../../chain-of-responsibility/etc/chain-of-responsibility.urm.png "Chain of Responsibility class diagram") + +## प्रयोज्यता + +जिम्मेदारी की श्रृंखला का प्रयोग कब करें + +* एक से अधिक ऑब्जेक्ट एक अनुरोध को संभाल सकते हैं, और हैंडलर को पहले से ज्ञात नहीं है। हैंडलर का स्वचालित रूप से पता लगाया जाना चाहिए। +* आप रिसीवर को स्पष्ट रूप से निर्दिष्ट किए बिना कई ऑब्जेक्ट में से एक के लिए अनुरोध जारी करना चाहते हैं। +* ऑब्जेक्ट का सेट जो अनुरोध को संभाल सकता है उसे गतिशील रूप से निर्दिष्ट किया जाना चाहिए। + +## ज्ञात उपयोग + +* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) +* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) +* [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-) + +## श्रेय + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/hi/circuit-breaker/README.md b/localization/hi/circuit-breaker/README.md new file mode 100644 index 000000000000..5c2faca7e7ef --- /dev/null +++ b/localization/hi/circuit-breaker/README.md @@ -0,0 +1,326 @@ +--- +title: Circuit Breaker +category: Behavioral +language: hi +tag: + - Performance + - Decoupling + - Cloud distributed +--- + +## हेतु + +महँगी दूरस्थ सेवा कॉलों को इस प्रकार संभालें कि किसी एक सेवा/घटक की विफलता हो +संपूर्ण एप्लिकेशन को नीचे नहीं लाया जा सकता है, और हम यथाशीघ्र सेवा से पुनः कनेक्ट कर सकते हैं। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> एक ऐसे वेब एप्लिकेशन की कल्पना करें जिसमें स्थानीय फ़ाइलें/छवियां और दूरस्थ सेवाएं दोनों हैं जिनका उपयोग किया जाता है +> डेटा लाया जा रहा है। ये दूरस्थ सेवाएँ कभी-कभी स्वस्थ और उत्तरदायी हो सकती हैं, या बन सकती हैं +> विभिन्न कारणों से किसी समय धीमी और अनुत्तरदायी। तो अगर रिमोट में से एक +> सेवाएँ धीमी हैं या सफलतापूर्वक प्रतिक्रिया नहीं दे रही हैं, हमारा एप्लिकेशन प्रतिक्रिया प्राप्त करने का प्रयास करेगा +> कई थ्रेड्स/प्रक्रियाओं का उपयोग करने वाली दूरस्थ सेवा, जल्द ही वे सभी हैंग हो जाएंगी (जिन्हें भी कहा जाता है)। +> [Thread starvation](https://en.wikipedia.org/wiki/Starvation_(computer_science)) जिसके कारण हमारा संपूर्ण वेब एप्लिकेशन क्रैश हो गया है। हमें पता लगाने में सक्षम होना चाहिए +> यह स्थिति और उपयोगकर्ता को एक उपयुक्त संदेश दिखाएं ताकि वह इसके अन्य हिस्सों का पता लगा सके +> ऐप दूरस्थ सेवा विफलता से अप्रभावित है। इस बीच, अन्य सेवाएँ जो काम कर रही हैं +> सामान्यतः, इस विफलता से अप्रभावित रहकर कार्य करते रहना चाहिए। + +साफ़ शब्दों में + +> सर्किट ब्रेकर विफल दूरस्थ सेवाओं को शानदार ढंग से संभालने की अनुमति देता है। यह विशेष रूप से तब उपयोगी होता है जब +> हमारे एप्लिकेशन के सभी हिस्से एक-दूसरे से अत्यधिक अलग हैं, और एक घटक विफल हो गया है +> इसका मतलब यह नहीं है कि अन्य हिस्से काम करना बंद कर देंगे। + +विकिपीडिया कहता है + +> सर्किट ब्रेकर आधुनिक सॉफ्टवेयर विकास में उपयोग किया जाने वाला एक डिज़ाइन पैटर्न है। इसका उपयोग पता लगाने के लिए किया जाता है +> विफलताएं और विफलता को लगातार दोहराए जाने से रोकने के तर्क को समाहित करती है +> रखरखाव, अस्थायी बाहरी सिस्टम विफलता या अप्रत्याशित सिस्टम कठिनाइयाँ। + +## प्रोग्रामेटिक उदाहरण + +तो, यह सब एक साथ कैसे आता है? उपरोक्त उदाहरण को ध्यान में रखते हुए हम इसका अनुकरण करेंगे +एक सरल उदाहरण में कार्यक्षमता. एक निगरानी सेवा वेब ऐप की नकल करती है और स्थानीय और दोनों बनाती है +दूरस्थ कॉल. + +सेवा वास्तुकला इस प्रकार है: + +![alt text](../../../circuit-breaker/etc/ServiceDiagram.png "Service Diagram") + +कोड के संदर्भ में, अंतिम उपयोगकर्ता एप्लिकेशन है: + +```java +@Slf4j +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) { + + var serverStartTime = System.nanoTime(); + + var delayedService = new DelayedRemoteService(serverStartTime, 5); + var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2, + 2000 * 1000 * 1000); + + var quickService = new QuickRemoteService(); + var quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, 2, + 2000 * 1000 * 1000); + + //Create an object of monitoring service which makes both local and remote calls + var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, + quickServiceCircuitBreaker); + + //Fetch response from local resource + LOGGER.info(monitoringService.localResourceResponse()); + + //Fetch response from delayed service 2 times, to meet the failure threshold + LOGGER.info(monitoringService.delayedServiceResponse()); + LOGGER.info(monitoringService.delayedServiceResponse()); + + //Fetch current state of delayed service circuit breaker after crossing failure threshold limit + //which is OPEN now + LOGGER.info(delayedServiceCircuitBreaker.getState()); + + //Meanwhile, the delayed service is down, fetch response from the healthy quick service + LOGGER.info(monitoringService.quickServiceResponse()); + LOGGER.info(quickServiceCircuitBreaker.getState()); + + //Wait for the delayed service to become responsive + try { + LOGGER.info("Waiting for delayed service to become responsive"); + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //Check the state of delayed circuit breaker, should be HALF_OPEN + LOGGER.info(delayedServiceCircuitBreaker.getState()); + + //Fetch response from delayed service, which should be healthy by now + LOGGER.info(monitoringService.delayedServiceResponse()); + //As successful response is fetched, it should be CLOSED again. + LOGGER.info(delayedServiceCircuitBreaker.getState()); + } +} +``` + +निगरानी सेवा: + +```java +public class MonitoringService { + + private final CircuitBreaker delayedService; + + private final CircuitBreaker quickService; + + public MonitoringService(CircuitBreaker delayedService, CircuitBreaker quickService) { + this.delayedService = delayedService; + this.quickService = quickService; + } + + //Assumption: Local service won't fail, no need to wrap it in a circuit breaker logic + public String localResourceResponse() { + return "Local Service is working"; + } + + /** + * Fetch response from the delayed service (with some simulated startup time). + * + * @return response string + */ + public String delayedServiceResponse() { + try { + return this.delayedService.attemptRequest(); + } catch (RemoteServiceException e) { + return e.getMessage(); + } + } + + /** + * Fetches response from a healthy service without any failure. + * + * @return response string + */ + public String quickServiceResponse() { + try { + return this.quickService.attemptRequest(); + } catch (RemoteServiceException e) { + return e.getMessage(); + } + } +} +``` +जैसा कि देखा जा सकता है, यह स्थानीय संसाधनों को सीधे प्राप्त करने के लिए कॉल करता है, लेकिन यह कॉल को लपेट देता है +सर्किट ब्रेकर ऑब्जेक्ट में रिमोट (महंगी) सेवा, जो निम्नानुसार दोषों को रोकती है: + +```java +public class DefaultCircuitBreaker implements CircuitBreaker { + + private final long timeout; + private final long retryTimePeriod; + private final RemoteService service; + long lastFailureTime; + private String lastFailureResponse; + int failureCount; + private final int failureThreshold; + private State state; + private final long futureTime = 1000 * 1000 * 1000 * 1000; + + /** + * Constructor to create an instance of Circuit Breaker. + * + * @param timeout Timeout for the API request. Not necessary for this simple example + * @param failureThreshold Number of failures we receive from the depended service before changing + * state to 'OPEN' + * @param retryTimePeriod Time period after which a new request is made to remote service for + * status check. + */ + DefaultCircuitBreaker(RemoteService serviceToCall, long timeout, int failureThreshold, + long retryTimePeriod) { + this.service = serviceToCall; + // We start in a closed state hoping that everything is fine + this.state = State.CLOSED; + this.failureThreshold = failureThreshold; + // Timeout for the API request. + // Used to break the calls made to remote resource if it exceeds the limit + this.timeout = timeout; + this.retryTimePeriod = retryTimePeriod; + //An absurd amount of time in future which basically indicates the last failure never happened + this.lastFailureTime = System.nanoTime() + futureTime; + this.failureCount = 0; + } + + // Reset everything to defaults + @Override + public void recordSuccess() { + this.failureCount = 0; + this.lastFailureTime = System.nanoTime() + futureTime; + this.state = State.CLOSED; + } + + @Override + public void recordFailure(String response) { + failureCount = failureCount + 1; + this.lastFailureTime = System.nanoTime(); + // Cache the failure response for returning on open state + this.lastFailureResponse = response; + } + + // Evaluate the current state based on failureThreshold, failureCount and lastFailureTime. + protected void evaluateState() { + if (failureCount >= failureThreshold) { //Then something is wrong with remote service + if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) { + //We have waited long enough and should try checking if service is up + state = State.HALF_OPEN; + } else { + //Service would still probably be down + state = State.OPEN; + } + } else { + //Everything is working fine + state = State.CLOSED; + } + } + + @Override + public String getState() { + evaluateState(); + return state.name(); + } + + /** + * Break the circuit beforehand if it is known service is down Or connect the circuit manually if + * service comes online before expected. + * + * @param state State at which circuit is in + */ + @Override + public void setState(State state) { + this.state = state; + switch (state) { + case OPEN -> { + this.failureCount = failureThreshold; + this.lastFailureTime = System.nanoTime(); + } + case HALF_OPEN -> { + this.failureCount = failureThreshold; + this.lastFailureTime = System.nanoTime() - retryTimePeriod; + } + default -> this.failureCount = 0; + } + } + + /** + * Executes service call. + * + * @return Value from the remote resource, stale response or a custom exception + */ + @Override + public String attemptRequest() throws RemoteServiceException { + evaluateState(); + if (state == State.OPEN) { + // return cached response if the circuit is in OPEN state + return this.lastFailureResponse; + } else { + // Make the API request if the circuit is not OPEN + try { + //In a real application, this would be run in a thread and the timeout + //parameter of the circuit breaker would be utilized to know if service + //is working. Here, we simulate that based on server response itself + var response = service.call(); + // Yay!! the API responded fine. Let's reset everything. + recordSuccess(); + return response; + } catch (RemoteServiceException ex) { + recordFailure(ex.getMessage()); + throw ex; + } + } + } +} +``` + +उपरोक्त पैटर्न विफलताओं को कैसे रोकता है? आइए इस परिमित राज्य मशीन के माध्यम से समझें +इसके द्वारा कार्यान्वित किया गया। + +![alt text](../../../circuit-breaker/etc/StateDiagram.png "State Diagram") + +- हम सर्किट ब्रेकर ऑब्जेक्ट को कुछ मापदंडों के साथ आरंभ करते हैं: `timeout`, `failureThreshold` और `retryTimePeriod` जो यह निर्धारित करने में मदद करते हैं कि एपीआई कितना लचीला है। +- प्रारंभ में, हम `closed` स्थिति में हैं और एपीआई पर कोई दूरस्थ कॉल नहीं हुई है। +- हर बार जब कॉल सफल हो जाती है, तो हम स्थिति को उसी स्थिति में रीसेट कर देते हैं जैसी वह शुरुआत में थी। +- यदि विफलताओं की संख्या एक निश्चित सीमा को पार कर जाती है, तो हम `open` स्थिति में चले जाते हैं, जो एक ओपन सर्किट की तरह कार्य करता है और दूरस्थ सेवा कॉल को करने से रोकता है, इस प्रकार संसाधनों की बचत होती है। (यहां, हम ```stale response from API``` नामक प्रतिक्रिया लौटाते हैं) +- एक बार जब हम पुन: प्रयास की समय-सीमा पार कर लेते हैं, तो हम `half-open` स्थिति में चले जाते हैं और यह जांचने के लिए दूरस्थ सेवा पर दोबारा कॉल करते हैं कि सेवा काम कर रही है या नहीं ताकि हम ताजा सामग्री पेश कर सकें। एक विफलता इसे वापस `open` स्थिति में सेट कर देती है और दूसरा प्रयास पुनः प्रयास की समयावधि के बाद किया जाता है, जबकि एक सफलता इसे `closed` स्थिति में सेट कर देती है ताकि सब कुछ फिर से सामान्य रूप से काम करना शुरू कर दे। + +## क्लास डायग्राम + +![alt text](../../../circuit-breaker/etc/circuit-breaker.urm.png "Circuit Breaker class diagram") + +## प्रयोज्यता + +जब सर्किट ब्रेकर पैटर्न का उपयोग करें + +- एक दोष-सहिष्णु एप्लिकेशन का निर्माण जहां कुछ सेवाओं की विफलता से संपूर्ण एप्लिकेशन बंद नहीं होना चाहिए। +- लगातार चलने वाले (हमेशा चालू रहने वाले) एप्लिकेशन का निर्माण करना, ताकि इसके घटकों को पूरी तरह से बंद किए बिना अपग्रेड किया जा सके। + +## संबंधित पैटर्न + +- [Retry Pattern](https://github.com/iluwatar/java-design-patterns/tree/master/retry) + +## वास्तविक दुनिया के उदाहरण + +* [Spring Circuit Breaker module](https://spring.io/guides/gs/circuit-breaker) +* [Netflix Hystrix API](https://github.com/Netflix/Hystrix) + +## श्रेय + +* [Understanding Circuit Breaker Pattern](https://itnext.io/understand-circuitbreaker-design-pattern-with-simple-practical-example-92a752615b42) +* [Martin Fowler on Circuit Breaker](https://martinfowler.com/bliki/CircuitBreaker.html) +* [Fault tolerance in a high volume, distributed system](https://medium.com/netflix-techblog/fault-tolerance-in-a-high-volume-distributed-system-91ab4faae74a) +* [Circuit Breaker pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker) diff --git a/localization/hi/client-session/README.md b/localization/hi/client-session/README.md new file mode 100644 index 000000000000..ad9a19443bb2 --- /dev/null +++ b/localization/hi/client-session/README.md @@ -0,0 +1,114 @@ +--- +title: Client Session Pattern +category: Architectural +language: hi +tags: +- Decoupling +--- + +## नाम + +[Client Session pattern](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client) + +## हेतु + +- स्टेटलेस सर्वर बनाएं जो क्लस्टरिंग की समस्या को दूर करता है, क्योंकि उपयोगकर्ता सर्वर के बीच निर्बाध रूप से स्विच कर सकते हैं। +- सर्वर फेल-ओवर की स्थिति में डेटा को अधिक लचीला बनाता है। +- छोटे डेटा आकार के साथ अच्छा काम करता है। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> आप एक डेटा प्रबंधन ऐप बनाना चाह रहे हैं जो उपयोगकर्ताओं को सर्वर पर अनुरोध भेजने की अनुमति दे +> अपने उपकरणों पर संग्रहीत डेटा को संशोधित और परिवर्तित करें। ये अनुरोध आकार में छोटे हैं और +> बड़े पैमाने पर डेटाबेस कार्यान्वयन की आवश्यकता को नकारते हुए, डेटा प्रत्येक उपयोगकर्ता के लिए अलग-अलग होता है। +> क्लाइंट सत्र पैटर्न का उपयोग करके, आप एकाधिक समवर्ती अनुरोधों, लोड को संभालने में सक्षम हैं +> सर्वर के स्टेटलेस रहने के कारण विभिन्न सर्वरों पर क्लाइंट को आसानी से संतुलित करना। आप भी ना +> क्लाइंट द्वारा सभी सुविधाएं प्रदान करने के कारण सर्वर साइड पर सत्र आईडी संग्रहीत करने की आवश्यकता को हटा दें +> वह जानकारी जो सर्वर को अपनी प्रक्रिया निष्पादित करने के लिए आवश्यक होती है। + +साफ़ शब्दों में + +> मौजूदा क्लाइंट और उस पर एक्सेस की जा रही जानकारी के बारे में जानकारी संग्रहीत करने के बजाय +> सर्वर, इसे केवल क्लाइंट साइड में ही बनाए रखा जाता है। क्लाइंट को प्रत्येक अनुरोध के साथ सत्र डेटा भेजना होगा +> सर्वर को क्लाइंट को एक अद्यतन स्थिति वापस भेजनी होती है, जो क्लाइंट पर संग्रहीत होती है +> मशीन. सर्वर को क्लाइंट जानकारी संग्रहीत करने की आवश्यकता नहीं है। +> ([ref](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client)) + +**प्रोग्रामेटिक उदाहरण** + +क्लाइंट-सत्र पैटर्न का वर्णन करने के लिए नमूना कोड यहां दिया गया है। नीचे दिए गए कोड में हम पहले हैं +सर्वर का एक उदाहरण बनाना। इस सर्वर इंस्टेंस का उपयोग सत्र ऑब्जेक्ट प्राप्त करने के लिए किया जाएगा +दो ग्राहकों के लिए. जैसा कि आप नीचे दिए गए कोड से देख सकते हैं, सेशन ऑब्जेक्ट का उपयोग किसी भी चीज़ को स्टोर करने के लिए किया जा सकता है +प्रासंगिक जानकारी जो क्लाइंट अनुरोध को संसाधित करने के लिए सर्वर द्वारा आवश्यक है। ये सत्र +फिर प्रत्येक अनुरोध के साथ ऑब्जेक्ट को सर्वर पर भेज दिया जाएगा। अनुरोध में सत्र होगा +ऑब्जेक्ट जो प्रसंस्करण के लिए आवश्यक डेटा के साथ प्रासंगिक ग्राहक विवरण संग्रहीत करता है +अनुरोध। प्रत्येक अनुरोध में सत्र की जानकारी सर्वर को क्लाइंट और प्रक्रिया की पहचान करने में मदद करती है +तदनुसार अनुरोध. + +```java +public class App { + + public static void main(String[] args) { + var server = new Server("localhost", 8080); + var session1 = server.getSession("Session1"); + var session2 = server.getSession("Session2"); + var request1 = new Request("Data1", session1); + var request2 = new Request("Data2", session2); + server.process(request1); + server.process(request2); + } +} + +@Data +@AllArgsConstructor +public class Session { + + /** + * Session id. + */ + private String id; + + /** + * Client name. + */ + private String clientName; + +} + +@Data +@AllArgsConstructor +public class Request { + + private String data; + + private Session session; + +} +``` + +## वास्तुकला आरेख + +![alt text](../../../client-session/etc/session_state_pattern.png "Session State Pattern") + +## प्रयोज्यता + +क्लाइंट स्थिति पैटर्न का उपयोग तब करें जब: + +- बड़े अनुरोधों और प्रतिक्रिया आकारों को रोकने के लिए छोटी मात्रा में डेटा संसाधित करना। +- क्लाइंट स्थिति को सहेजने के लिए सर्वर की आवश्यकता को हटा दें। ऐसा करने से सत्र आईडी संग्रहीत करने की आवश्यकता भी समाप्त हो जाती है। +- क्लस्टरिंग एक मुद्दा है और इससे बचा जाना चाहिए। स्टेटलेस सर्वर क्लाइंट को सर्वर पर आसानी से वितरित करने की अनुमति देते हैं। +- सर्वर विफलता के कारण डेटा हानि से लचीलापन बनाता है। + +## नतीजे + +- सर्वर स्टेटलेस है. कोई भी कंप्यूट एपीआई कोई डेटा संग्रहीत नहीं करेगा। +- बड़ी मात्रा में डेटा से निपटने के लिए संघर्ष करना पड़ता है। प्रबंधित करने के लिए सत्र डेटा की बड़ी मात्रा के कारण भेजने और प्राप्त करने में अधिक समय लगता है। +- सुरक्षा। सारा डेटा क्लाइंट की मशीन पर संग्रहीत होता है। इसका मतलब यह है कि क्लाइंट की ओर से कोई भी भेद्यता सर्वर द्वारा भेजे और प्राप्त किए जा रहे सभी डेटा को उजागर कर सकती है। + + +## श्रेय + +- [Dzone - Practical PHP patterns](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client) +- [Client Session State Design Pattern - Ram N Java](https://www.youtube.com/watch?v=ycOSj9g41pc) diff --git a/localization/hi/collecting-parameter/README.md b/localization/hi/collecting-parameter/README.md new file mode 100644 index 000000000000..0c56a9742664 --- /dev/null +++ b/localization/hi/collecting-parameter/README.md @@ -0,0 +1,196 @@ +--- +title: Collecting Parameter +category: Idiom +language: hi +tag: +- Generic +--- + +## नाम +पैरामीटर एकत्रित करना + +## हेतु +एक संग्रह के भीतर अनेक विधियों के सहयोगात्मक परिणाम को संग्रहीत करना। + +## व्याख्या +### वास्तविक दुनिया का उदाहरण +एक बड़े कॉर्पोरेट भवन के भीतर, एक वैश्विक प्रिंटर कतार मौजूद है जो सभी मुद्रण कार्यों का एक संग्रह है +जो फिलहाल लंबित हैं। विभिन्न मंजिलों पर प्रिंटर के अलग-अलग मॉडल होते हैं, प्रत्येक की अलग-अलग प्रिंटिंग होती है +नीति। हमें एक ऐसे प्रोग्राम का निर्माण करना चाहिए जो किसी संग्रह में लगातार उपयुक्त मुद्रण कार्य जोड़ सके, जिसे *कलेक्टिंग पैरामीटर* कहा जाता है। + +### साफ़ शब्दों में +एक विशाल विधि के बजाय जिसमें एक चर में जानकारी एकत्र करने के लिए कई नीतियां शामिल हैं, हम ऐसा कर सकते हैं +कई छोटे फ़ंक्शन बनाएं जो प्रत्येक पैरामीटर लें, और नई जानकारी जोड़ें। हम पैरामीटर को पास कर सकते हैं +ये सभी छोटे कार्य और अंत तक, हमें वही मिलेगा जो हम मूल रूप से चाहते थे। इस बार, कोड साफ़ है +और समझने में आसान है. क्योंकि बड़े फ़ंक्शन को तोड़ दिया गया है, परिवर्तन के रूप में कोड को संशोधित करना भी आसान है +छोटे कार्यों के लिए स्थानीयकृत हैं। + +### विकिपीडिया कहता है +कलेक्टिंग पैरामीटर मुहावरे में एक संग्रह (सूची, मानचित्र, आदि) को एक विधि के पैरामीटर के रूप में बार-बार पारित किया जाता है जो संग्रह में आइटम जोड़ता है। + +### प्रोग्रामेटिक उदाहरण +ऊपर से हमारे उदाहरण को कोड करते हुए, हम संग्रह `result` को एक संग्रहण पैरामीटर के रूप में उपयोग कर सकते हैं। निम्नलिखित प्रतिबंध +कार्यान्वित हैं: +- यदि A4 कागज रंगीन है, तो वह भी एक तरफा होना चाहिए। अन्य सभी गैर-रंगीन कागज स्वीकार किए जाते हैं +- A3 कागज़ गैर-रंगीन और एक तरफा होने चाहिए +- A2 पेपर एकल-पृष्ठ, एकल-पक्षीय और गैर-रंगीन होने चाहिए + +```java +package com.iluwatar.collectingparameter; +import java.util.LinkedList; +import java.util.Queue; +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + /* + Initialising the printer queue with jobs + */ + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A2, 5, false, false)); + + /* + This variable is the collecting parameter. + */ + var result = new LinkedList(); + + /* + * Using numerous sub-methods to collaboratively add information to the result collecting parameter + */ + addA4Papers(result); + addA3Papers(result); + addA2Papers(result); + } +} +``` +हम `result` संग्रहण पैरामीटर को पॉप्युलेट करने के लिए `addA4Paper`, `addA3Paper`, और `addA2Paper` विधियों का उपयोग करते हैं +पहले वर्णित नीति के अनुसार उपयुक्त मुद्रण कार्य। तीन नीतियां नीचे एन्कोड की गई हैं, + +```java +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + /** + * Adds A4 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA4Papers(Queue printerItemsCollection) { + /* + Iterate through the printer queue, and add A4 papers according to the correct policy to the collecting parameter, + which is 'printerItemsCollection' in this case. + */ + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A4)) { + var isColouredAndSingleSided = nextItem.isColour && !nextItem.isDoubleSided; + if (isColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } else if (!nextItem.isColour) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A3 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate + * the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA3Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A3)) { + + // Encoding the policy into a Boolean: the A3 paper cannot be coloured and double-sided at the same time + var isNotColouredAndSingleSided = !nextItem.isColour && !nextItem.isDoubleSided; + if (isNotColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A2 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate + * the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA2Papers(Queue printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A2)) { + + // Encoding the policy into a Boolean: the A2 paper must be single page, single-sided, and non-coloured. + var isNotColouredSingleSidedAndOnePage = nextItem.pageCount == 1 && !nextItem.isDoubleSided + && !nextItem.isColour; + if (isNotColouredSingleSidedAndOnePage) { + printerItemsCollection.add(nextItem); + } + } + } + } +} +``` + +प्रत्येक विधि एक संग्रह पैरामीटर को तर्क के रूप में लेती है। इसके बाद यह वैश्विक चर से लिए गए तत्वों को जोड़ता है, +यदि प्रत्येक तत्व किसी दिए गए मानदंड को पूरा करता है तो इस संग्रहण पैरामीटर पर। इन विधियों में ग्राहक की इच्छानुसार कोई भी नीति हो सकती है। + +इस प्रोग्रामेटिक उदाहरण में, तीन प्रिंट कार्य कतार में जोड़े गए हैं। केवल पहले दो प्रिंट कार्य ही जोड़े जाने चाहिए +नीति के अनुसार संग्रहण पैरामीटर। निष्पादन के बाद `result` चर के तत्व हैं, + +| paperSize | pageCount | isDoubleSided | isColour | +|-----------|-----------|---------------|----------| +| A4 | 5 | false | false | +| A3 | 2 | false | false | + +जिसकी हमें अपेक्षा थी। + +## क्लास डायग्राम +![alt text](../../../collecting-parameter/etc/collecting-parameter.urm.png "Collecting Parameter") + +## प्रयोज्यता +जब कलेक्टिंग पैरामीटर डिज़ाइन पैटर्न का उपयोग करें +- आप एक संग्रह या ऑब्जेक्ट वापस करना चाहते हैं जो कई विधियों का सहयोगात्मक परिणाम है +- आप एक ऐसी विधि को सरल बनाना चाहते हैं जो डेटा जमा करती है क्योंकि मूल विधि बहुत जटिल है + +## ट्यूटोरियल +इस विधि के लिए ट्यूटोरियल यहां पाए जाते हैं: +- [रिफैक्टरिंग टू पैटर्न्स](http://www.tarrani.net/RefactoringToPatterns.pdf) जोशुआ केरिवस्की द्वारा +- [स्मॉलटॉक सर्वोत्तम अभ्यास पैटर्न] (https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf) केंट बेक द्वारा + +## ज्ञात उपयोग +जोशुआ केरिव्स्की ने अपनी पुस्तक 'रिफैक्टरिंग टू पैटर्न्स' में वास्तविक दुनिया का उदाहरण दिया है। वह इसका उपयोग करने का एक उदाहरण देता है +XML ट्री के लिए `toString()` विधि बनाने के लिए पैरामीटर डिज़ाइन पैटर्न एकत्रित करना। इस डिज़ाइन पैटर्न का उपयोग किए बिना, +इसके लिए सशर्त और संयोजन के साथ एक भारी फ़ंक्शन की आवश्यकता होगी जो कोड पठनीयता को खराब कर देगा। ऐसी विधि +इसे छोटी-छोटी विधियों में विभाजित किया जा सकता है, जिनमें से प्रत्येक जानकारी के अपने स्वयं के सेट को संग्रहण पैरामीटर में जोड़ता है। + +इसे [रिफैक्टरिंग टू पैटर्न](http://www.tarrani.net/RefactoringToPatterns.pdf) में देखें। + +## नतीजे +पेशेवर: +- कोड को अधिक पठनीय बनाता है +- 'लिंकेज' से बचें, जहां कई विधियां एक ही वैश्विक चर का संदर्भ देती हैं +- बड़े कार्यों को विघटित करके रखरखाव बढ़ाता है + +दोष: +- कोड की लंबाई बढ़ सकती है +- तरीकों की 'परतें' जोड़ता है + +## संबंधित पैटर्न +- [Compose Methods](https://www.geeksforgeeks.org/composite-design-pattern/) + +## श्रेय +निम्नलिखित पुस्तकों का उपयोग किया गया: +- [Refactoring To Patterns](http://www.tarrani.net/RefactoringToPatterns.pdf) जोशुआ केरिवस्की द्वारा +- [Smalltalk Best Practice Patterns](https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf) केंट बेक द्वारा + साइटें: +- [Wiki](https://wiki.c2.com/?CollectingParameter) diff --git a/localization/hi/collection-pipeline/README.md b/localization/hi/collection-pipeline/README.md new file mode 100644 index 000000000000..70717d4dcde1 --- /dev/null +++ b/localization/hi/collection-pipeline/README.md @@ -0,0 +1,27 @@ +--- +title: Collection Pipeline +category: Functional +language: hi +tag: + - Reactive +--- + +## हेतु +कलेक्शन पाइपलाइन फ़ंक्शन कंपोज़िशन और कलेक्शन पाइपलाइन पेश करती है, दो कार्यात्मक-शैली पैटर्न जिन्हें आप अपने कोड में संग्रहों को पुनरावृत्त करने के लिए जोड़ सकते हैं। +कार्यात्मक प्रोग्रामिंग में, छोटे मॉड्यूलर कार्यों या संचालन की एक श्रृंखला के माध्यम से जटिल संचालन को अनुक्रमित करना आम बात है। श्रृंखला को फ़ंक्शंस की संरचना, या फ़ंक्शंस संरचना कहा जाता है। जब डेटा का संग्रह किसी फ़ंक्शन संरचना के माध्यम से प्रवाहित होता है, तो यह एक संग्रह पाइपलाइन बन जाता है। फ़ंक्शन संरचना और संग्रह पाइपलाइन दो डिज़ाइन पैटर्न हैं जिनका उपयोग अक्सर कार्यात्मक-शैली प्रोग्रामिंग में किया जाता है। + +## क्लास डायग्राम +![alt text](../../../collection-pipeline/etc/collection-pipeline.png "Collection Pipeline") + +## प्रयोज्यता +जब संग्रह पाइपलाइन पैटर्न का उपयोग करें + +* जब आप ऑपरेशनों का एक क्रम निष्पादित करना चाहते हैं जहां एक ऑपरेशन का एकत्रित आउटपुट अगले में फीड किया जाता है +* जब आप अपने कोड में बहुत सारे स्टेटमेंट का उपयोग करते हैं +* जब आप अपने कोड में बहुत सारे लूप का उपयोग करते हैं + +## श्रेय + +* [Function composition and the Collection Pipeline pattern](https://www.ibm.com/developerworks/library/j-java8idioms2/index.html) +* [Martin Fowler](https://martinfowler.com/articles/collection-pipeline/) +* [Java8 Streams](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html) diff --git a/localization/hi/combinator/README.md b/localization/hi/combinator/README.md new file mode 100644 index 000000000000..d898cb48fe77 --- /dev/null +++ b/localization/hi/combinator/README.md @@ -0,0 +1,208 @@ +--- +title: Combinator +category: Idiom +language: hi +tag: + - Reactive +--- + +## दूसरा नाम + +संयोजन पैटर्न + +## हेतु + +कार्यों के संयोजन के विचार पर केंद्रित पुस्तकालयों को व्यवस्थित करने की शैली का प्रतिनिधित्व करने वाला कार्यात्मक पैटर्न। +इसे सीधे शब्दों में कहें तो, कुछ प्रकार टी हैं, प्रकार टी के "आदिम" मूल्यों के निर्माण के लिए कुछ कार्य हैं, और कुछ "कॉम्बिनेटर" हैं जो प्रकार टी के अधिक जटिल मूल्यों को बनाने के लिए विभिन्न तरीकों से प्रकार टी के मूल्यों को जोड़ सकते हैं। + +## व्याख्या + +वास्तविक दुनिया का उदाहरण + +> कंप्यूटर विज्ञान में, कॉम्बिनेटरी लॉजिक का उपयोग गणना के सरलीकृत मॉडल के रूप में किया जाता है, जिसका उपयोग कंप्यूटेबिलिटी सिद्धांत और प्रूफ सिद्धांत में किया जाता है। अपनी सरलता के बावजूद, संयोजनात्मक तर्क गणना की कई आवश्यक विशेषताओं को पकड़ लेता है। +> + +साफ़ शब्दों में + +> कॉम्बिनेटर आपको पहले से परिभाषित "things" से नई "things" बनाने की अनुमति देता है। +> + +विकिपीडिया कहता है + +> कॉम्बिनेटर एक उच्च-क्रम वाला फ़ंक्शन है जो अपने तर्कों से परिणाम को परिभाषित करने के लिए केवल फ़ंक्शन एप्लिकेशन और पहले से परिभाषित कॉम्बिनेटर का उपयोग करता है। +> + +**प्रोग्रामेटिक उदाहरण** + +उपरोक्त कॉम्बिनेटर उदाहरण का अनुवाद करना। सबसे पहले, हमारे पास एक इंटरफ़ेस है जिसमें कई विधियाँ `contains`, `not`, `or`, `and` शामिल हैं। + +```java +// Functional interface to find lines in text. +public interface Finder { + + // The function to find lines in text. + List find(String text); + + // Simple implementation of function {@link #find(String)}. + static Finder contains(String word) { + return txt -> Stream.of(txt.split("\n")) + .filter(line -> line.toLowerCase().contains(word.toLowerCase())) + .collect(Collectors.toList()); + } + + // combinator not. + default Finder not(Finder notFinder) { + return txt -> { + List res = this.find(txt); + res.removeAll(notFinder.find(txt)); + return res; + }; + } + + // combinator or. + default Finder or(Finder orFinder) { + return txt -> { + List res = this.find(txt); + res.addAll(orFinder.find(txt)); + return res; + }; + } + + // combinator and. + default Finder and(Finder andFinder) { + return + txt -> this + .find(txt) + .stream() + .flatMap(line -> andFinder.find(line).stream()) + .collect(Collectors.toList()); + } + ... +} +``` + +फिर हमारे पास कुछ जटिल खोजकों `advancedFinder`, `filteredFinder`, `specializedFinder` and `expandedFinder` के लिए एक और कॉम्बिनेटर भी है। + +```java +// Complex finders consisting of simple finder. +public class Finders { + + private Finders() { + } + + // Finder to find a complex query. + public static Finder advancedFinder(String query, String orQuery, String notQuery) { + return + Finder.contains(query) + .or(Finder.contains(orQuery)) + .not(Finder.contains(notQuery)); + } + + // Filtered finder looking a query with excluded queries as well. + public static Finder filteredFinder(String query, String... excludeQueries) { + var finder = Finder.contains(query); + + for (String q : excludeQueries) { + finder = finder.not(Finder.contains(q)); + } + return finder; + } + + // Specialized query. Every next query is looked in previous result. + public static Finder specializedFinder(String... queries) { + var finder = identMult(); + + for (String query : queries) { + finder = finder.and(Finder.contains(query)); + } + return finder; + } + + // Expanded query. Looking for alternatives. + public static Finder expandedFinder(String... queries) { + var finder = identSum(); + + for (String query : queries) { + finder = finder.or(Finder.contains(query)); + } + return finder; + } + ... +} +``` + +अब हमने कॉम्बिनेटरों के लिए इंटरफ़ेस और विधियाँ बना ली हैं। अब हमारे पास इन कॉम्बिनेटरों पर काम करने वाला एक एप्लिकेशन है। + +```java +var queriesOr = new String[]{"many", "Annabel"}; +var finder = Finders.expandedFinder(queriesOr); +var res = finder.find(text()); +LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res); + +var queriesAnd = new String[]{"Annabel", "my"}; +finder = Finders.specializedFinder(queriesAnd); +res = finder.find(text()); +LOGGER.info("the result of specialized(and) query[{}] is {}", queriesAnd, res); + +finder = Finders.advancedFinder("it was", "kingdom", "sea"); +res = finder.find(text()); +LOGGER.info("the result of advanced query is {}", res); + +res = Finders.filteredFinder(" was ", "many", "child").find(text()); +LOGGER.info("the result of filtered query is {}", res); + +private static String text() { + return + "It was many and many a year ago,\n" + + "In a kingdom by the sea,\n" + + "That a maiden there lived whom you may know\n" + + "By the name of ANNABEL LEE;\n" + + "And this maiden she lived with no other thought\n" + + "Than to love and be loved by me.\n" + + "I was a child and she was a child,\n" + + "In this kingdom by the sea;\n" + + "But we loved with a love that was more than love-\n" + + "I and my Annabel Lee;\n" + + "With a love that the winged seraphs of heaven\n" + + "Coveted her and me."; + } +``` + +**प्रोग्राम आउटपुट:** + +```java +the result of expanded(or) query[[many, Annabel]] is [It was many and many a year ago,, By the name of ANNABEL LEE;, I and my Annabel Lee;] +the result of specialized(and) query[[Annabel, my]] is [I and my Annabel Lee;] +the result of advanced query is [It was many and many a year ago,] +the result of filtered query is [But we loved with a love that was more than love-] +``` + +अब हम अपने ऐप को `expandedFinder`, `specializedFinder`, `advancedFinder`, `filteredFinder` खोजने वाले प्रश्नों के साथ डिज़ाइन कर सकते हैं, जो सभी `contains`, `or`, `not`, `and` से प्राप्त होते हैं। + + +## क्लास डायग्राम +![alt text](../../../combinator/etc/combinator.urm.png "Combinator class diagram") + +## प्रयोज्यता +कॉम्बिनेटर पैटर्न का उपयोग तब करें जब: + +- आप अधिक सादे मानों से अधिक जटिल मान बनाने में सक्षम हैं, लेकिन उनका प्रकार समान है (उनका संयोजन) + +## फ़ायदे + +- डेवलपर्स के नजरिए से एपीआई डोमेन के शब्दों से बना है। +- संयोजन और अनुप्रयोग चरण के बीच स्पष्ट अंतर है। +- पहले एक इंस्टेंस बनाता है और फिर उसे निष्पादित करता है। +- यह पैटर्न को समानांतर वातावरण में लागू बनाता है। + + +## वास्तविक दुनिया के उदाहरण + +- java.util.function.Function#compose +- java.util.function.Function#andThen + +## श्रेय + +- [Example for java](https://gtrefs.github.io/code/combinator-pattern/) +- [Combinator pattern](https://wiki.haskell.org/Combinator_pattern) +- [Combinatory logic](https://wiki.haskell.org/Combinatory_logic) diff --git a/localization/hi/command/README.md b/localization/hi/command/README.md new file mode 100644 index 000000000000..56db248ff621 --- /dev/null +++ b/localization/hi/command/README.md @@ -0,0 +1,236 @@ +--- +title: Command +category: Behavioral +language: hi +tag: + - Gang of Four +--- + +## दूसरा नाम + +क्रिया, लेन-देन + +## हेतु + +एक अनुरोध को एक ऑब्जेक्ट के रूप में इनकैप्सुलेट करें, जिससे आपको क्लाइंट को अलग-अलग पैरामीटराइज़ करने की सुविधा मिलती है +अनुरोध, कतार या लॉग अनुरोध, और पूर्ववत संचालन का समर्थन करते हैं। + +## व्याख्या +वास्तविक दुनिया का उदाहरण + +> एक जादूगर भूत पर जादू कर रहा है। मंत्रों को एक-एक करके भूत पर क्रियान्वित किया जाता है। +> पहला जादू भूत को सिकोड़ देता है और दूसरा उसे अदृश्य बना देता है। फिर विज़ार्ड उलट जाता है +> मंत्र एक-एक करके। यहां प्रत्येक मंत्र एक कमांड ऑब्जेक्ट है जिसे पूर्ववत किया जा सकता है। + +साफ़ शब्दों में + +> अनुरोधों को कमांड ऑब्जेक्ट के रूप में संग्रहीत करने से कोई कार्रवाई करने या बाद में उसे पूर्ववत करने की अनुमति मिलती है। + +विकिपीडिया कहता है + +> ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग में, कमांड पैटर्न एक व्यवहारिक डिज़ाइन पैटर्न है जिसमें a +> ऑब्जेक्ट का उपयोग किसी क्रिया को करने या किसी ईवेंट को ट्रिगर करने के लिए आवश्यक सभी जानकारी को समाहित करने के लिए किया जाता है +> बाद में। + +**प्रोग्रामेटिक उदाहरण** + +यहां विज़ार्ड और गॉब्लिन के साथ नमूना कोड दिया गया है। आइए `Wizard` वर्ग से शुरू करें। + +```java +@Slf4j +public class Wizard { + + private final Deque undoStack = new LinkedList<>(); + private final Deque redoStack = new LinkedList<>(); + + public Wizard() {} + + public void castSpell(Runnable runnable) { + runnable.run(); + undoStack.offerLast(runnable); + } + + public void undoLastSpell() { + if (!undoStack.isEmpty()) { + var previousSpell = undoStack.pollLast(); + redoStack.offerLast(previousSpell); + previousSpell.run(); + } + } + + public void redoLastSpell() { + if (!redoStack.isEmpty()) { + var previousSpell = redoStack.pollLast(); + undoStack.offerLast(previousSpell); + previousSpell.run(); + } + } + + @Override + public String toString() { + return "Wizard"; + } +} +``` + +इसके बाद, हमारे पास वह भूत है जो मंत्रों का लक्ष्य है। + +```java +@Slf4j +public abstract class Target { + + private Size size; + + private Visibility visibility; + + public Size getSize() { + return size; + } + + public void setSize(Size size) { + this.size = size; + } + + public Visibility getVisibility() { + return visibility; + } + + public void setVisibility(Visibility visibility) { + this.visibility = visibility; + } + + @Override + public abstract String toString(); + + public void printStatus() { + LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); + } +} + +public class Goblin extends Target { + + public Goblin() { + setSize(Size.NORMAL); + setVisibility(Visibility.VISIBLE); + } + + @Override + public String toString() { + return "Goblin"; + } + + public void changeSize() { + var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL; + setSize(oldSize); + } + + public void changeVisibility() { + var visible = getVisibility() == Visibility.INVISIBLE + ? Visibility.VISIBLE : Visibility.INVISIBLE; + setVisibility(visible); + } +} +``` + +अंत में, हमारे पास मुख्य फ़ंक्शन कास्टिंग मंत्र में विज़ार्ड है। + +```java +public static void main(String[] args) { + var wizard = new Wizard(); + var goblin = new Goblin(); + + // casts shrink/unshrink spell + wizard.castSpell(goblin::changeSize); + + // casts visible/invisible spell + wizard.castSpell(goblin::changeVisibility); + + // undo and redo casts + wizard.undoLastSpell(); + wizard.redoLastSpell(); +``` + +यहाँ कार्रवाई में पूरा उदाहरण है। + +```java +var wizard = new Wizard(); +var goblin = new Goblin(); + +goblin.printStatus(); +wizard.castSpell(goblin::changeSize); +goblin.printStatus(); + +wizard.castSpell(goblin::changeVisibility); +goblin.printStatus(); + +wizard.undoLastSpell(); +goblin.printStatus(); + +wizard.undoLastSpell(); +goblin.printStatus(); + +wizard.redoLastSpell(); +goblin.printStatus(); + +wizard.redoLastSpell(); +goblin.printStatus(); +``` + +यहाँ प्रोग्राम आउटपुट है: + +```java +Goblin, [size=normal] [visibility=visible] +Goblin, [size=small] [visibility=visible] +Goblin, [size=small] [visibility=invisible] +Goblin, [size=small] [visibility=visible] +Goblin, [size=normal] [visibility=visible] +Goblin, [size=small] [visibility=visible] +Goblin, [size=small] [visibility=invisible] +``` + +## क्लास डायग्राम + +![alt text](../../../command/etc/command.png "Command") + +## प्रयोज्यता + +जब आप चाहें तो कमांड पैटर्न का उपयोग करें: + +* निष्पादित की जाने वाली क्रिया द्वारा वस्तुओं का मापन करें। आप ऐसे मानकीकरण को a में व्यक्त कर सकते हैं + कॉलबैक फ़ंक्शन के साथ प्रक्रियात्मक भाषा, यानी, एक फ़ंक्शन जो कहीं पंजीकृत है + बाद में बुलाया गया। कमांड कॉलबैक के लिए ऑब्जेक्ट-ओरिएंटेड प्रतिस्थापन हैं। +* अलग-अलग समय पर अनुरोध निर्दिष्ट करें, कतारबद्ध करें और निष्पादित करें। एक कमांड ऑब्जेक्ट में जीवन हो सकता है + मूल अनुरोध से स्वतंत्र. यदि किसी अनुरोध के प्राप्तकर्ता को किसी पते में दर्शाया जा सकता है + अंतरिक्ष-स्वतंत्र तरीके से, फिर आप अनुरोध के लिए एक कमांड ऑब्जेक्ट को एक अलग प्रक्रिया में स्थानांतरित कर सकते हैं + और वहां अनुरोध पूरा करें। +* समर्थन पूर्ववत करें। कमांड का निष्पादन ऑपरेशन इसके प्रभावों को उलटने के लिए स्थिति को संग्रहीत कर सकता है + स्वयं आदेश दें. कमांड इंटरफ़ेस में एक अतिरिक्त अन-एक्ज़िक्यूट ऑपरेशन होना चाहिए जो उलट देता है + निष्पादित करने के लिए पिछली कॉल के प्रभाव। निष्पादित आदेश इतिहास सूची में संग्रहीत होते हैं। + इस सूची को आगे और पीछे घुमाकर असीमित स्तर की पूर्ववत और पुनः करें कार्यक्षमता प्राप्त की जाती है + क्रमशः अन-एक्ज़ीक्यूट और एक्ज़िक्यूट को कॉल करना। +* लॉगिंग परिवर्तनों का समर्थन करें ताकि सिस्टम क्रैश होने की स्थिति में उन्हें फिर से लागू किया जा सके। को बढ़ाकर + लोड और स्टोर संचालन के साथ कमांड इंटरफ़ेस, आप परिवर्तनों का लगातार लॉग रख सकते हैं। + क्रैश से उबरने में डिस्क से लॉग किए गए कमांड को फिर से लोड करना और उन्हें फिर से निष्पादित करना शामिल है + निष्पादित ऑपरेशन. +* उच्च-स्तरीय संचालन के आसपास एक प्रणाली की संरचना करें जो आदिम संचालन पर आधारित हो। ऐसी संरचना है + लेनदेन का समर्थन करने वाली सूचना प्रणालियों में आम है। एक लेन-देन डेटा के एक सेट को समाहित करता है + परिवर्तन। कमांड पैटर्न लेनदेन को मॉडल करने का एक तरीका प्रदान करता है। कमांड का एक सामान्य इंटरफ़ेस होता है, + आपको सभी लेन-देन एक ही तरीके से शुरू करने देता है। यह पैटर्न विस्तार करना भी आसान बनाता है + नए लेनदेन के साथ प्रणाली. +* अनुरोधों का इतिहास रखें। +* कॉलबैक कार्यक्षमता लागू करें। +* पूर्ववत कार्यक्षमता लागू करें। + +## ज्ञात उपयोग + +* [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) +* [org.junit.runners.model.Statement](https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/model/Statement.java) +* [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki) +* [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html) + +## श्रेय + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/hi/factory-method/README.md b/localization/hi/factory-method/README.md new file mode 100644 index 000000000000..e8b5b46127de --- /dev/null +++ b/localization/hi/factory-method/README.md @@ -0,0 +1,103 @@ +--- +title: Factory Method +category: Creational +language: hi +tag: + - Extensibility + - Gang Of Four +--- + +## वर्चुअल कन्स्ट्रक्टर के रूप में भी जाना जाता + +## हेतु + +एक इंटरफ़ेस को परिभाषित करें जो एक ऑब्जेक्ट बनाने की अनुमति देता है, लेकिन उपवर्गों को यह तय करने देता है कि किस वर्ग को तत्काल बनाया जाए। +फ़ैक्टरी मेथड एक वर्ग को उपवर्गों में तत्कालिकता स्थगित करने देता है। + +## स्पष्टीकरण + +वास्तविक दुनिया का उदाहरण + +लोहार हथियार बनाता है। कल्पित बौनों को एल्विश हथियारों की आवश्यकता होती है और orcs को Orcish हथियारों की आवश्यकता होती है। +ग्राहक के हाथ पर निर्भर करता है कि सही प्रकार के लोहार को बुलाया जाता है। + +साधारण शब्दों में + +यह चाइल्ड क्लासेस को इंस्टेंटिएशन लॉजिक को डेलिगेट करने का एक तरीका प्रदान करता है। + +विकिपीडिया का कहना है कि + +क्लास-आधारित प्रोग्रामिंग में, फैक्ट्री मेथड पैटर्न एक क्रिएशनल पैटर्न है जो फैक्ट्री मेथड का उपयोग उस ऑब्जेक्ट को बनाने की समस्या से निपटने के लिए करता है जो उस ऑब्जेक्ट के सटीक वर्ग को निर्दिष्ट किए बिना बनाया जाएगा। यह एक फैक्ट्री मेथड को कॉल करके ऑब्जेक्ट बनाकर किया जाता है - या तो एक इंटरफ़ेस में निर्दिष्ट और चाइल्ड कक्षाओं द्वारा कार्यान्वित किया जाता है, या एक बेस क्लास में कार्यान्वित किया जाता है और वैकल्पिक रूप से व्युत्पन्न कक्षाओं द्वारा ओवरराइड किया जाता है - बजाय कंस्ट्रक्टर को कॉल करने के। + +प्रोग्रामेटिक उदाहरण + +हमारे ब्लैकस्मिथ उदाहरण को ऊपर लेते हुए, पहले हमारे पास एक 'ब्लैकस्मिथ' इंटरफेस होता है और इसके लिए कुछ अंगीकरण होते हैं: + +```java +public interface Blacksmith { + Weapon manufactureWeapon(WeaponType weaponType); +} + +public class ElfBlacksmith implements Blacksmith { + public Weapon manufactureWeapon(WeaponType weaponType) { + return ELFARSENAL.get(weaponType); + } +} + +public class OrcBlacksmith implements Blacksmith { + public Weapon manufactureWeapon(WeaponType weaponType) { + return ORCARSENAL.get(weaponType); + } +} +``` +जब ग्राहक आते हैं, तो सही प्रकार के ब्लैकस्मिथ को बुलाया जाता है और अनुरोधित हथियार निर्मित किए जाते हैं + +```java +Blacksmith blacksmith = new OrcBlacksmith(); +Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); +LOGGER.info("{} manufactured {}", blacksmith, weapon); +weapon = blacksmith.manufactureWeapon(WeaponType.AXE); +LOGGER.info("{} manufactured {}", blacksmith, weapon); + +blacksmith = new ElfBlacksmith(); +weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); +LOGGER.info("{} manufactured {}", blacksmith, weapon); +weapon = blacksmith.manufactureWeapon(WeaponType.AXE); +LOGGER.info("{} manufactured {}", blacksmith, weapon); + +``` +प्रोग्राम का आउटपुट : +```text +The orc blacksmith manufactured an orcish spear +The orc blacksmith manufactured an orcish axe +The elf blacksmith manufactured an elven spear +The elf blacksmith manufactured an elven axe + +``` +## क्लास डायग्राम + +![alt text](./etc/factory-method.urm.png "Factory Method pattern class diagram") + +## प्रयोज्यता + +निम्नलिखित स्थितियों में फैक्टरी मेथड पैटर्न का उपयोग करें: + +* क्लास उन ऑब्जेक्ट्स के वर्ग का अनुमान नहीं लगा सकता है जिन्हें उसे बनाना चाहिए। +* क्लास चाहता है कि उसके उपवर्ग उन ऑब्जेक्ट्स को निर्दिष्ट करें जो वह बनाता है। +* कक्षाएं कई सहायक उपवर्गों में से एक को जिम्मेदारी सौंपती हैं, और आप यह जानना चाहते हैं कि कौन सा सहायक उपवर्ग प्रतिनिधि है। + +## ज्ञात उपयोग + +* [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +* [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +* [java.text.NumberFormat](http://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +* [java.nio.charset.Charset](http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +* [java.net.URLStreamHandlerFactory](http://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html#createURLStreamHandler-java.lang.String-) +* [java.util.EnumSet](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of-E-) +* [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) + +## श्रेय + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/hi/module/README.md b/localization/hi/module/README.md new file mode 100644 index 000000000000..8d8a78ae4aa3 --- /dev/null +++ b/localization/hi/module/README.md @@ -0,0 +1,27 @@ +--- +title: Module +category: Structural +language: hi +tag: + - Decoupling + - Cloud distributed +--- + +## हेतु + +मॉड्यूल पैटर्न का उपयोग सॉफ़्टवेयर मॉड्यूल की अवधारणा को लागू करने के लिए किया जाता है, जिसे मॉड्यूलर प्रोग्रामिंग द्वारा परिभाषित किया जाता है, एक प्रोग्रामिंग भाषा में जो अवधारणा के लिए अपूर्ण प्रत्यक्ष समर्थन प्रदान करती है। + +## क्लास डायग्राम + + +![alt text](../../../module/etc/module.png "Module class diagram") + +## प्रयोज्यता + +मॉड्यूल पैटर्न को एक क्रिएशनल पैटर्न और एक स्ट्रक्चरल पैटर्न माना जा सकता है। यह अन्य तत्वों के निर्माण और संगठन को प्रबंधित करता है, और उन्हें स्ट्रक्चरल पैटर्न की तरह समूहों में विभाजित करता है। + +इस पैटर्न को लागू करने वाली कोई वस्तु एक नामस्थान के समकक्ष प्रदान कर सकती है, जो एक स्थैतिक वर्ग या स्थैतिक सदस्यों वाले वर्ग के आरंभीकरण और अंतिमकरण प्रक्रिया को क्लीनर, अधिक संक्षिप्त वाक्यविन्यास और अर्थशास्त्र के साथ प्रदान करती है। + +## श्रेय + +* [Module](https://en.wikipedia.org/wiki/Module_pattern) diff --git a/localization/id/README.md b/localization/id/README.md new file mode 100644 index 000000000000..e371b20b824a --- /dev/null +++ b/localization/id/README.md @@ -0,0 +1,57 @@ + + +# Implementasi design patterns pada Java + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-176-orange.svg?style=flat-square)](#contributors-) + + +
    + +Baca dalam bahasa lain : [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md) + +
    + +# Pengenalan + +Design patterns adalah best practice yang dapat digunakan programmer untuk memecahkan masalah umum saat merancang aplikasi atau sistem. + +Design patterns dapat mempercepat proses pengembangan dengan menyediakan kode yang teruji, terbukti paradigma pengembangan. + +Menggunakan kembali design patterns membantu mencegah masalah-masalah kecil yang dapat menyebabkan masalah yang lebih besar, dan juga meningkatkan keterbacaan kode untuk programmer dan arsitek yang +familiar dengan pola. + + +# Mulai + +Situs ini menampilkan Design Patterns pada Java. Solusi-solusi yang terdapat pada situs ini telah dikembangkan oleh programmer dan arsitek yang berpengalaman dari komunitas open source. Pola-polanya dapat dilihat pada deskripsi atau dengan melihat source code mereka. Contoh-contoh source code memiliki komentar yang baik dan dapat dianggap sebagai tutorial pemrograman tentang cara menerapkan pola tertentu. Kami menggunakan teknologi Java open source yang populer dan telah terbukti. + +Sebelum anda masuk kedalam materinya, anda harus familiar dengan macam-macam [Software Design Principles](https://java-design-patterns.com/principles/). + +Semua desain seharusnya sesimpel mungkin. Anda harus mulai dengan KISS, YAGNI, dan prinsip Do The Simples Thing That Could Possibly Work. hanya boleh diperkenalkan ketika dibutuhkan untuk praktik +kemungkinan diperpanjang. + +Setelah Anda terbiasa dengan konsep-konsep ini, Anda dapat mulai belajar +[design patterns yang tersedia](https://java-design-patterns.com/patterns/) menggunakan cara-cara berikut + + - Cari spesifik pattern berdasarkan namanya. Apabila tidak menemukannya tolong lapor pattern baru [disini](https://github.com/iluwatar/java-design-patterns/issues). + - Gunakan tag-tag seperti `Performance`, `Gang of Four` atau `Data access`. + - Gunakan kategori dari pattern, `Creational`, `Behavioral`, dan sebagainya. + +Semoga Anda menemukan solusi Object-Oriented yang bermanfaat untuk arsitektur Anda dari yang disajikan di situs ini dan mempelajarinya dengan senang seperti kami mengembangkannya. + +# Cara berkontribusi + +Jika anda memiliki keinginan untuk berkontribusi pada proyek ini anda akan menemukan informasi yang revelan pada halaman [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). Kami akan membantu anda dan menjawab pertanyaan anda pada [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns). + +# License + +Proyek ini dilisensikan di bawah ketentuan lisensi MIT. + diff --git a/localization/id/decorator/README.md b/localization/id/decorator/README.md new file mode 100644 index 000000000000..1fe3d89241ba --- /dev/null +++ b/localization/id/decorator/README.md @@ -0,0 +1,169 @@ +--- +title: Decorator +category: Structural +language: id +tag: + - Gang of Four + - Extensibility +--- + +## Juga dikenal sebagai + +Pembungkus + +## Tujuan + +Menyematkan tanggung jawab tambahan ke suatu objek secara dinamis. Dekorator memberikan alternatif yang fleksibel terhadap subkelas untuk memperluas fungsionalitas. + +## Penjelasan + +Contoh dunia nyata + +> Ada troll pemarah yang tinggal di perbukitan terdekat. Biasanya ia pergi dengan tangan kosong, tetapi terkadang ia +> punya senjata. Untuk mempersenjatai troll, Anda tidak perlu membuat troll baru, melainkan mendekorasinya +> secara dinamis dengan senjata yang sesuai. + +Dengan kata sederhana + +> Pola dekorator memungkinkan Anda mengubah perilaku objek secara dinamis saat run time dengan membungkus +> mereka dalam objek kelas dekorator. + +Wikipedia(en) mengatakan + +> Dalam pemrograman berorientasi objek, pola dekorator adalah pola desain yang memungkinkan perilaku +> ditambahkan ke objek individual, baik secara statis maupun dinamis, tanpa memengaruhi perilaku +> objek lain dari kelas yang sama. Pola dekorator sering kali berguna untuk mematuhi Prinsip Tanggung +> Jawab Tunggal, karena memungkinkan fungsionalitas dibagi antara kelas-kelas dengan area perhatian yang +> unik serta Prinsip Terbuka-Tertutup, dengan memungkinkan fungsionalitas suatu kelas diperluas tanpa diubah. + +**Contoh Program** + +Mari kita ambil contoh troll. Pertama-tama kita memiliki `SimpleTroll` yang mengimplementasikan antarmuka +`Troll`: + +```java +public interface Troll { + void attack(); + int getAttackPower(); + void fleeBattle(); +} + +@Slf4j +public class SimpleTroll implements Troll { + + @Override + public void attack() { + LOGGER.info("Troll itu mencoba menangkapmu!"); + } + + @Override + public int getAttackPower() { + return 10; + } + + @Override + public void fleeBattle() { + LOGGER.info("Troll itu menjerit ketakutan dan melarikan diri!"); + } +} +``` + +Kemudian kita ingin menambahkan gada untuk troll tersebut. Kita dapat melakukannya secara dinamis dengan menggunakan dekorator: + +```java +@Slf4j +public class ClubbedTroll implements Troll { + + private final Troll decorated; + + public ClubbedTroll(Troll decorated) { + this.decorated = decorated; + } + + @Override + public void attack() { + decorated.attack(); + LOGGER.info("Troll itu mengayunkan gada ke arahmu!"); + } + + @Override + public int getAttackPower() { + return decorated.getAttackPower() + 10; + } + + @Override + public void fleeBattle() { + decorated.fleeBattle(); + } +} +``` + +Berikut aksi troll tersebut: + +```java +// simple troll +LOGGER.info("Troll biasa mendekat."); +var troll = new SimpleTroll(); +troll.attack(); +troll.fleeBattle(); +LOGGER.info("Kekuatan troll sederhana: {}.\n", troll.getAttackPower()); + +// change the behavior of the simple troll by adding a decorator +LOGGER.info("Troll dengan gada besar mengejutkanmu."); +var clubbedTroll = new ClubbedTroll(troll); +clubbedTroll.attack(); +clubbedTroll.fleeBattle(); +LOGGER.info("Kekuatan troll dengan gada: {}.\n", clubbedTroll.getAttackPower()); +``` + +Output program: + +```java +Troll biasa mendekat. +Troll itu mencoba menangkapmu! +Troll itu menjerit ketakutan dan melarikan diri! +Kekuatan troll sederhana: 10. + +Troll dengan gada besar mengejutkanmu. +Troll itu mencoba menangkapmu! +Troll itu mengayunkan gada ke arahmu! +Troll itu menjerit ketakutan dan melarikan diri! +Kekuatan troll dengan gada: 20. +``` + +## Diagram kelas + +![alt text](./etc/decorator.urm.png "Diagram kelas pola dekorator") + +## Penerapan + +Dekorator digunakan untuk: + +* Tambahkan tanggung jawab ke objek individual secara dinamis dan transparan, tanpa +memengaruhi objek lain. +* Untuk tanggung jawab yang dapat ditarik/dihapus. +* Dimana ekstensi dengan subkelas tidak praktis; Ketika sejumlah besar ekstensi independen +mungkin dilakukan dan akan menghasilkan ledakan subkelas untuk mendukung setiap kombinasi, atau definisi +kelas mungkin tersembunyi dan/atau tidak tersedia untuk subkelas. + +## Tutorial + +* [Tutorial Pola Dekorator](https://www.journaldev.com/1540/decorator-design-pattern-in-java-example) + +## Kegunaan yang diketahui + + * [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), + [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) dan [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) + * [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-) + * [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-) + * [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-) + + +## Kredit + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/id/decorator/etc/decorator.urm.png b/localization/id/decorator/etc/decorator.urm.png new file mode 100644 index 000000000000..141c0563f0c6 Binary files /dev/null and b/localization/id/decorator/etc/decorator.urm.png differ diff --git a/localization/it/README.md b/localization/it/README.md new file mode 100644 index 000000000000..c6a218f437c8 --- /dev/null +++ b/localization/it/README.md @@ -0,0 +1,64 @@ + + +# Modelli di progettazione in Java + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-233-orange.svg?style=flat-square)](#contributors-) + + +
    + +Leggi in lingue diverse: [**it**](localization/it/README.md), [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md), [**vi**](localization/vi/README.md), [**bn**](localization/bn/README.md), [**np**](localization/np/README.md) +
    + +# Introduzione + +I design patterns sono le migliori pratiche di programmazione che uno sviluppatore puó usare per +risolvere problemi durante il design di un'applicazione o di un sistema. + +I design patterns possono velocizzare lo sviluppo fornendo paradigmi di +sviluppo testati e approvati. + +Riutilizzare i design patterns aiuta a prevenire problematiche che possono causare maggiori problemi, inoltre migliorano la leggibilità del codice per gli sviluppatori e ingegneri che hanno familiarità con questi patterns. + +# Come iniziare + +Il sito mostra i design patterns sviluppati utilizzando il linguaggio Java. Le soluzioni sono state +sviluppate da programmatori e ingegneri esperti provenienti dalla community open-source. Questi patterns possono essere compresi attraverso descrizioni dettagliate o guardando +il codice sorgente. Gli esempi di codice sono ben commentati e possono essere +visti come dei tutorial di programmazione su come implementare uno specifico pattern. Per fare ciò utiliziamo le migliori tecnologie open-source di Java. + +Prima di cimentarti nel materiale proposto, dovresti prima familiarizzare con i vari +[Principi di Software Design](https://java-design-patterns.com/principles/). + +Tutti i patterns dovrebbero essere i più semplici possibili. Ti consigliamo di cominiciare +con i principi KISS, YAGNI e Do The Simplest Thing That Could Possibly Work. Complessità +e patterns dovrebbero essere introdotti solamente quando sono necessari per motivi pratici. + +Quando hai familiarizzato con questi concetti puoi cominciare a immergerti nei +[design patterns disponibili](https://java-design-patterns.com/patterns/) utilizzando +uno dei seguenti approcci: + + - Cercando uno specifico pattern tramite il nome. Non riesci a trovarlo? Allora comunicacelo [qui](https://github.com/iluwatar/java-design-patterns/issues). + - Usando tags come `Performance`, `Gang of four` o `Data access`. + - Usando categorie appartenenti ai patterns come `Creational`, `Behavioral`, etc. + +Speriamo che le soluzioni object-oriented mostrate ti siano utili per i tuoi progetti e che tu +ti diverta a impararle come abbiamo fatto noi nell' implementarle. + +# Come contribuire + +Se desideri contribuire al progetto puoi trovare le informazioni necessarie nella nostra pagina +[wiki](https://github.com/iluwatar/java-design-patterns/wiki). Ti aiuteremo a rispondere a +ogni tua domanda nella [chatroom Gitter](https://gitter.im/iluwatar/java-design-patterns). + +# Licenza + +Questo progetto è licanziato nei termini della licenza MIT. diff --git a/localization/it/abstract-document/README.md b/localization/it/abstract-document/README.md new file mode 100644 index 000000000000..0e78d18e7109 --- /dev/null +++ b/localization/it/abstract-document/README.md @@ -0,0 +1,197 @@ +--- +title: Abstract Document +category: Structural +language: it +tag: + - Extensibility +--- + +## Intento + +Il design pattern "Abstract Document" è un design pattern strutturale che mira a fornire un modo coerente per gestire strutture dati gerarchiche e ad albero, definendo un'interfaccia comune per vari tipi di documenti. + +## Spiegazione + +Il pattern Abstract Document consente di gestire proprietà aggiuntive e non statiche. Questo pattern utilizza il concetto di trait per consentire la sicurezza dei tipi e separare le proprietà delle diverse classi in un insieme di interfacce. + +Esempio del mondo reale + +> Prendiamo ad esempio un'auto composta da diverse parti. Tuttavia, non sappiamo se l'auto ha tutte le parti o solo alcune di esse. Le nostre auto sono dinamiche ed estremamente flessibili. + +In parole semplici + +> Il pattern Abstract Document permette di associare proprietà agli oggetti senza che gli oggetti ne siano a conoscenza. + +Wikipedia dice + +> Un design pattern strutturale orientato agli oggetti per organizzare gli oggetti in archivi chiave-valore con +> tipizzazione debole ed esporre i dati utilizzando viste tipizzate. Lo scopo del pattern è ottenere un alto grado di +> flessibilità tra i componenti in un linguaggio fortemente tipizzato in cui nuove proprietà possono essere aggiunte +> all'albero degli oggetti al volo, senza perdere il supporto della sicurezza dei tipi. Il pattern fa uso di trait per +> separare diverse proprietà di una classe in diverse interfacce. Il termine "documento" è ispirato dai database +> orientati ai documenti. _(Testo tradotto dalla voce Abstract Document Pattern da Wikipedia in lingua inglese)._ + +**Esempio di codice** + +Per prima cosa definiamo le classi di base `Document` e `AbstractDocument`. Essenzialmente, queste classi fanno sì che l'oggetto contenga una mappa di proprietà e una qualunque quantità di oggetti figlio. + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + ... +} +``` +Successivamente definiamo un enum `Property` e un insieme di interfacce per tipo, prezzo, modello e parti. Questo ci permette di creare interfacce dall'aspetto statico per la nostra classe `Car`. + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} +``` + +Ora siamo pronti per introdurre la classe `Car`. + +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` + +E infine, costruiamo e usiamo la classe `Car` in un esempio completo. + +```java + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); + + // Constructing parts and car + // Here is our car: + // model: 300SL + // price: 10000 + // parts: + // wheel/15C/100 + // door/Lambo/300 +``` + +## Diagramma delle classi + +![alt text](../../../abstract-document/etc/abstract-document.png "Abstract Document Traits and Domain") + +## Applicabilità + +Questo pattern è particolarmente utile in scenari in cui si hanno diversi tipi di documenti che condividono alcune proprietà o comportamenti comuni, ma hanno anche proprietà o comportamenti unici specifici per i rispettivi tipi. Ecco alcuni scenari in cui il pattern Abstract Document può essere applicabile: + +* Sistemi di Gestione dei Contenuti (CMS): In un CMS, potresti avere vari tipi di contenuti, come articoli, immagini, video, ecc. Ogni tipo di contenuto potrebbe condividere attributi comuni come la data di creazione, l'autore e i tag, ma potrebbe anche avere attributi specifici come le dimensioni dell'immagine per le immagini o la durata del video per i video. + +* File System: Se stai progettando un file system in cui è necessario gestire diversi tipi di file, come documenti, immagini, file audio e directory, il pattern Abstract Document può aiutare a fornire un modo coerente per accedere agli attributi come la dimensione del file, la data di creazione, ecc., consentendo allo stesso tempo attributi specifici come la risoluzione dell'immagine o la durata dell'audio. + +* Sistemi di E-commerce: Una piattaforma di e-commerce potrebbe avere diversi tipi di prodotti, come prodotti fisici, download digitali e abbonamenti. Ogni tipo potrebbe condividere attributi comuni come il nome, il prezzo e la descrizione, ma avere attributi unici come il peso di spedizione per i prodotti fisici o il link di download per i prodotti digitali. + +* Sistemi di Gestione delle Cartelle Cliniche: Nel settore sanitario, le cartelle cliniche dei pazienti potrebbero includere vari tipi di dati come dati demografici, storia clinica, risultati dei test e prescrizioni. Il pattern Abstract Document può aiutare a gestire attributi condivisi come l'ID del paziente e la data di nascita, consentendo allo stesso tempo di gestire attributi specializzati come i risultati dei test o le prescrizioni. + +* Gestione delle Configurazioni: Quando si tratta di impostazioni di configurazione per applicazioni software, possono esserci diversi tipi di elementi di configurazione, ciascuno con il proprio insieme di attributi. Il pattern Abstract Document può essere utilizzato per gestire questi elementi di configurazione, garantendo un modo coerente per accedere e manipolare i loro attributi. + +* Piattaforme Educative: I sistemi educativi potrebbero avere vari tipi di materiali didattici come contenuti basati su testo, video, quiz e compiti. Attributi comuni come il titolo, l'autore e la data di pubblicazione possono essere condivisi, mentre attributi unici come la durata del video o le scadenze degli esercizi possono essere specifici per ciascun tipo. + +* Strumenti di Gestione dei Progetti: Nelle applicazioni di gestione dei progetti, potresti avere diversi tipi di attività come attività specifiche, fasi e problemi. Il pattern Abstract Document potrebbe essere utilizzato per gestire attributi generali come il nome dell'attività specifica e l'assegnatario, consentendo allo stesso tempo attributi specifici come la data della fase o la priorità del problema. + +L'idea chiave alla base del design pattern Abstract Document è fornire un modo flessibile ed estensibile per gestire diversi tipi di documenti o entità con attributi comuni e distinti. Definendo un'interfaccia comune e implementandola in vari tipi di documenti, è possibile ottenere un approccio più organizzato e coerente alla gestione di strutture dati complesse. + +## Collegamenti esterni + +* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492) \ No newline at end of file diff --git a/localization/it/abstract-factory/README.md b/localization/it/abstract-factory/README.md new file mode 100644 index 000000000000..beebef9560eb --- /dev/null +++ b/localization/it/abstract-factory/README.md @@ -0,0 +1,227 @@ +--- +title: Abstract Factory +category: Creational +language: it +tag: + - Gang of Four +--- + +## Anche conosciuto come + +Kit + +## Intento + +Fornire un'interfaccia per la creazione di famiglie di oggetti correlati o dipendenti senza specificarne le classi concrete. + +## Spiegazione + +Esempio del mondo reale + +> Per creare un regno, abbiamo bisogno di oggetti con un tema comune. Il regno elfico ha bisogno di un re elfico, di un castello elfico e di un esercito elfico, mentre il regno degli orchi ha bisogno di un re degli orchi, di un castello degli orchi e di un esercito degli orchi. Esiste una dipendenza tra gli oggetti all'interno del regno. + +In parole semplici + +> Una fabbrica di fabbriche; una fabbrica che raggruppa le singole fabbriche correlate o dipendenti senza specificare le loro classi concrete. + +Wikipedia dice + +> L'Abstract Factory fornisce un'interfaccia per creare famiglie di oggetti connessi o dipendenti tra loro, in modo che non ci sia necessità da parte dei client di specificare i nomi delle classi concrete all'interno del proprio codice. + +**Esempio di codice** + +Traducendo l'esempio del regno sopra. Prima di tutto, abbiamo alcune interfacce e implementazioni per gli oggetti all'interno del regno. + +```java +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 -> ... + +``` + +Successivamente, abbiamo l'astrazione e le implementazioni per la fabbrica del regno. + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +Ora abbiamo la fabbrica astratta che ci consente di creare una famiglia di oggetti correlati, ad esempio la fabbrica del regno elfico crea il castello elfico, il re elfico e l'esercito elfico, ecc. + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +Output del programma: + +```java +This is the elven castle! +This is the elven king! +This is the elven Army! +``` + +Ora possiamo progettare una fabbrica per le nostre diverse fabbriche di regni. In questo esempio, abbiamo creato `FactoryMaker`, responsabile di restituire un'istanza di `ElfKingdomFactory` o `OrcKingdomFactory`. +Il client può utilizzare `FactoryMaker` per creare la fabbrica concreta desiderata, che a sua volta produrrà diversi oggetti concreti (derivati da `Army`, `King`, `Castle`). +In questo esempio, abbiamo anche utilizzato un enum per parametrizzare il tipo di fabbrica di regno richiesto dal client. + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + default -> throw new IllegalArgumentException("KingdomType not supported."); + }; + } +} + + public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + --similar use of the orc factory + } +``` + +## Diagramma delle classi + +![alt text](../../../abstract-factory/etc/abstract-factory.urm.png "Abstract Factory class diagram") + + +## Applicabilità + +Utilizza il pattern Abstract Factory quando + +* Il sistema deve essere indipendente dal modo in cui i suoi prodotti vengono creati, composti e rappresentati. +* Il sistema deve essere configurato con una delle molteplici famiglie di prodotti. +* La famiglia di oggetti di prodotto correlati è progettata per essere utilizzata interamente, e hai bisogno di imporre questo presupposto. +* Vuoi fornire una libreria di classi di prodotto e vuoi esporre solo le loro interfacce, non le loro implementazioni. +* Il tempo di vita della dipendenza è concettualmente più breve di quella del consumer. +* Hai bisogno di un valore di runtime per costruire una particolare dipendenza. +* Vuoi decidere quale prodotto chiamare da una famiglia a runtime. +* Devi fornire uno o più parametri conosciuti solo a runtime prima di poter risolvere una dipendenza. +* Hai bisogno di coerenza tra i prodotti. +* Non vuoi modificare il codice esistente quando aggiungi nuovi prodotti o famiglie di prodotti al programma. + +Esempi di casi d'uso + +* Selezionare la chiamata all'implementazione appropriata di FileSystemAcmeService o DatabaseAcmeService o NetworkAcmeService in fase di esecuzione. +* La scrittura di casi di unit test diventa molto più semplice. +* Strumenti UI per diversi sistemi operativi. + +## Conseguenze + +* La dependency injection in Java nasconde le dipendenze delle classi di servizio, il che può portare a errori a runtime che sarebbero stati rilevati in fase di compilazione. +* Se da un lato il pattern è ottimo per la creazione di oggetti predefiniti, l'aggiunta di nuovi oggetti potrebbe essere complicato. +* Il codice diventa più complesso di quanto dovrebbe essere, poiché vengono introdotte molte nuove interfacce e classi insieme al pattern. + +## Tutorial + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## Usi noti + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## Pattern correlati + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## Collegamenti esterni + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/it/active-object/README.md b/localization/it/active-object/README.md new file mode 100644 index 000000000000..2cab348e1ee6 --- /dev/null +++ b/localization/it/active-object/README.md @@ -0,0 +1,127 @@ +--- +title: Active Object +category: Concurrency +language: it +tag: + - Performance +--- + + +## Intento +Il design pattern active object disaccoppia l'esecuzione del metodo dall'invocazione del metodo per gli oggetti che risiedono ciascuno nel proprio thread di controllo. L'obiettivo è introdurre la concorrenza utilizzando l'invocazione asincrona dei metodi e uno scheduler per gestire le richieste. + +## Spiegazione + +La classe che implementa il pattern active object conterrà un meccanismo di autosincronizzazione senza utilizzare metodi 'synchronized'. + +Esempio del mondo reale + +>Gli Orchi sono noti per la loro natura selvaggia e la loro anima indomabile. Sembra che abbiano il loro proprio thread di controllo basato su comportamenti precedenti. + +Per implementare una creatura che ha il suo meccanismo di thread di controllo e che esponga solo la sua API e non l'esecuzione stessa, possiamo utilizzare il pattern Active Object. + + +**Esempio di codice** + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +Possiamo vedere che qualsiasi classe che estenderà la classe ActiveCreature avrà il proprio thread di controllo per invocare ed eseguire i metodi. + +Ad esempio, la classe Orc: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` + +Ora possiamo creare diverse creature come gli Orchi, dir loro di mangiare e vagabondare, e loro eseguiranno queste azioni nel proprio thread di controllo: + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## Diagramma delle classi + +![alt text](../../../active-object/etc/active-object.urm.png "Active Object class diagram") + +## Tutorial + +* [Android and Java Concurrency: The Active Object Pattern](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) \ No newline at end of file diff --git a/localization/it/acyclic-visitor/README.md b/localization/it/acyclic-visitor/README.md new file mode 100644 index 000000000000..af54a46e97aa --- /dev/null +++ b/localization/it/acyclic-visitor/README.md @@ -0,0 +1,160 @@ +--- +title: Acyclic Visitor +category: Behavioral +language: it +tag: + - Extensibility +--- + +## Intento + +Permette di aggiungere nuove funzioni alle gerarchie di classi esistenti senza influire su tali gerarchie e senza creare i cicli di dipendenza problematici che sono intrinseci al pattern Visitor dei GoF. + +## Spiegazione + +Esempio del mondo reale + +> Abbiamo una gerarchia di classi di modem. I modem in questa gerarchia devono essere visitati da un algoritmo esterno basato su criteri di filtraggio (ad esempio, se si tratta di un modem compatibile con Unix o DOS). + +In parole semplici + +> L'Acyclic Visitor consente di aggiungere funzioni alle gerarchie di classi esistenti senza modificarle. + +[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) dice + +>Il pattern Acyclic Visitor consente di aggiungere nuove funzioni alle gerarchie di classi esistenti senza influire su tali gerarchie e senza creare i cicli di dipendenza che sono intrinseci al pattern Visitor dei Gang of Four. _(Testo tradotto dalla voce Acyclic Visitor da WikiWikiWeb in lingua inglese)._ + +**Esempio di codice** + +Ecco la gerarchia delle classi `Modem`. + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + + +Successivamente introduciamo la gerarchia delle classi `ModemVisitor`. + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + ... + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + ... + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +Infine, ecco i visitatori in azione. + +```java + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + var zoom = new Zoom(); + var hayes = new Hayes(); + hayes.accept(conDos); + zoom.accept(conDos); + hayes.accept(conUnix); + zoom.accept(conUnix); +``` + +Output del programma: + +``` + // Hayes modem used with Dos configurator. + // Zoom modem used with Dos configurator. + // Only HayesVisitor is allowed to visit Hayes modem + // Zoom modem used with Unix configurator. +``` + +## Diagramma delle classi + +![alt text](../../../acyclic-visitor/etc/acyclic-visitor.png "Acyclic Visitor") + +## Applicabilità + +Questo pattern può essere utilizzato nei seguenti casi: + +* Quando è necessario aggiungere una nuova funzione a una gerarchia esistente senza la necessità di modificarla o influenzarla. +* Quando ci sono funzioni che operano su una gerarchia, ma che non appartengono alla gerarchia stessa, ad esempio, il problema di ConfigureForDOS / ConfigureForUnix / ConfigureForX. +* Quando è necessario eseguire operazioni molto diverse su un oggetto a seconda del suo tipo. +* Quando la gerarchia delle classi visitate sarà frequentemente estesa con nuovi derivati dalla classe Element. +* Quando la ricompilazione, il relinking, il ritestare o la ridistribuzione dei derivati da Element è molto costoso. + +## Tutorial + +* [Acyclic Visitor Pattern Example](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) + +## Conseguenze + +Aspetti positivi: + +* Assenza di cicli di dipendenza tra le gerarchie di classi. +* Non è necessario ricompilare tutti i visitatori se se ne aggiunge uno nuovo. +* Non causa errori di compilazione nei visitatori esistenti se la gerarchia delle classi ha un nuovo membro. + +Aspetti negativi: + +* Viola il [Principio di sostituzione di Liskov](https://java-design-patterns.com/principles/#liskov-substitution-principle) mostrando di poter accettare tutti i visitatori ma essendo solo interessato a visitatori specifici. +* Deve essere creata una gerarchia parallela di visitatori per tutti i membri della gerarchia di classi visitabili. + +## Pattern correlati + +* [Visitor Pattern](https://java-design-patterns.com/patterns/visitor/) + +## Collegamenti esterni + +* [Acyclic Visitor by Robert C. Martin](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor in WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) diff --git a/localization/it/adapter/README.md b/localization/it/adapter/README.md new file mode 100644 index 000000000000..520799f12b1a --- /dev/null +++ b/localization/it/adapter/README.md @@ -0,0 +1,136 @@ +--- +title: Adapter +category: Structural +language: it +tag: + - Gang of Four +--- + +## Anche conosciuto come +Wrapper + +## Intento +Convertire l'interfaccia di una classe in un'altra interfaccia attesa dal cliente. Il pattern Adapter consente a classi di collaborare con altre classi con cui altrimenti non potrebbero farlo a causa di problemi di compatibilità. + +## Spiegazione + +Esempio del mondo reale + +> Immagina di avere delle immagini su una scheda di memoria e desideri trasferirle sul tuo computer. Per effettuare il trasferimento, hai bisogno di un tipo di adattatore compatibile con le porte del tuo computer, in modo da poter inserire la tua scheda. In questo caso, il lettore di schede è un adattatore (adapter). +> Un altro esempio potrebbe essere l'ampiamente noto adattatore di corrente; una spina con tre pin non può essere collegata a una presa con due fori, è necessario un adattatore per renderla compatibile con la presa di corrente. +> Un altro esempio sarebbe un traduttore simultaneo che traduce le parole pronunciate da una persona a un'altra. + +In parole semplici + +> Il pattern Adapter permette di incapsulare un oggetto in un adattatore per renderlo compatibile con una classe con cui sarebbe altrimenti incompatibile. + +Wikipedia dice + +> In ingegneria del software, il pattern Adapter è un design pattern del software che consente all'interfaccia di una classe esistente di essere utilizzata come un'altra interfaccia. Spesso viene utilizzato per far sì che classi esistenti possano collaborare con altre senza dover modificare il loro codice sorgente. _(Testo tradotto dalla voce Adapter Pattern da Wikipedia in lingua inglese)._ + +**Esempio di codice** + +Immagina un capitano che sa utilizzare solo barche a remi e non sa navigare affatto. + +Innanzitutto, abbiamo le interfacce `RowingBoat` e `FishingBoat` + +```java +public interface RowingBoat { + void row(); +} + +@Slf4j +public class FishingBoat { + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } +} +``` + +E il capitano si aspetta che ci sia un'implementazione dell'interfaccia `RowingBoat` per potersi muovere. + +```java +public class Captain { + + private final RowingBoat rowingBoat; + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +Ora immaginiamo che i pirati stiano arrivando e il nostro capitano debba scappare, ma è disponibile solo una barca da pesca. Dobbiamo creare un adattatore che consenta al capitano di navigare con la barca da pesca con le sue abilità di saper utilizzare le barche a remi. +```java +@Slf4j +public class FishingBoatAdapter implements RowingBoat { + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} +``` + +E ora il `Captain` può usare la `FishingBoat` per sfuggire ai pirati. + +```java +var captain = new Captain(new FishingBoatAdapter()); +captain.row(); +``` + +## Diagramma delle classi +![alt text](../../../adapter/etc/adapter.urm.png "Adapter class diagram") + +## Applicabilità +Utilizza il pattern Adapter quando + +* Vuoi utilizzare una classe esistente, ma la sua interfaccia non corrisponde a quella di cui hai bisogno +* Desideri creare una classe riutilizzabile che collabori con classi non correlate o non previste, ovvero classi che non necessariamente hanno interfacce compatibili. +* Hai bisogno di utilizzare diverse sottoclassi esistenti, ma sarebbe impraticabile adattare la loro interfaccia mediante la creazione di sottoclassi per ognuna di esse. Un adapter può adattare l'interfaccia della sua classe padre. +* Nella maggior parte delle applicazioni che utilizzano librerie di terze parti, si utilizzano adapter come strato intermedio tra l'applicazione e la libreria di terze parti per disaccoppiare l'applicazione dalla libreria stessa. Se è necessario utilizzare un'altra libreria, è sufficiente creare un nuovo adapter per la nuova libreria senza dover modificare il codice dell'applicazione. + +## Tutorial + +* [Dzone](https://dzone.com/articles/adapter-design-pattern-in-java) +* [Refactoring Guru](https://refactoring.guru/design-patterns/adapter/java/example) +* [Baeldung](https://www.baeldung.com/java-adapter-pattern) +* [GeeksforGeeks](https://www.geeksforgeeks.org/adapter-pattern/) + + +## Conseguenze +Gli adapter di classe e oggetti comportano scelte diverse. Un adapter di classe + +* Effettua l'adattamento rimanendo legato a una classe adattata specifica. Di conseguenza, un adapter di classe non funzionerà quando desideriamo adattare una classe e le sue sottoclassi. +* Permette all'Adapater di modificare il comportamento della classe adattata perché l'adpater è una sottoclasse della classe adattata. +* Utilizza un solo oggetto e non richiede l'uso di puntatori aggiuntivi per fare riferimento alla classe adattata. + +Un adapter di oggetto + +* Permette a un singolo Adapter di lavorare con diverse classi adattate, ovvero con la classe adattata e tutte le sue sottoclassi (se ne ha). L'Adapter può anche aggiungere funzionalità a tutte le classi adattate contemporaneamente. +* Rende più complicata la modifica del comportamento della classe adattata. Sarebbe necessario creare una sottoclasse della classe da adattare e far sì che l'Adapter faccia riferimento alla sottoclasse anziché alla classe da adattare. + +## Esempi del mondo reale + +* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +* [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +* [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + + +## Collegamenti esterni + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/it/iterator/README.md b/localization/it/iterator/README.md new file mode 100644 index 000000000000..f5cbde101fc0 --- /dev/null +++ b/localization/it/iterator/README.md @@ -0,0 +1,152 @@ +--- +title: Iterator +category: Behavioral +language: it +tag: + - Gang of Four +--- + +## Anche conosciuto come + +Cursor + +## Intento +Fornire un modo per accedere agli elementi di un oggetto aggregato in modo sequenziale senza esporre la sua rappresentazione sottostante. + +## Spiegazione + +Esempio del mondo reale + +> Lo scrigno del tesoro contiene una serie di oggetti magici. Ci sono diversi tipi di oggetti, come anelli, +> pozioni e armi. Gli oggetti possono essere esaminati per tipo utilizzando un iteratore fornito dalla cassa +> del tesoro. + +In parole semplici + +> I contenitori possono fornire un'interfaccia di iterazione agnostica alla rappresentazione per consentire l'accesso agli +> elementi. + +Wikipedia dice + +> Nella programmazione orientata agli oggetti, il pattern iterator è un design pattern in cui un iteratore viene +> utilizzato per attraversare un contenitore e accedere agli elementi del contenitore stesso. _(Testo tradotto dalla voce Iterator Pattern da Wikipedia in lingua inglese)._ + +**Esempio di codice** + +La classe principale nel nostro esempio è `TreasureChest`, che contiene gli oggetti. + +```java +public class TreasureChest { + + private final List items; + + public TreasureChest() { + items = List.of( + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); + } + + public Iterator iterator(ItemType itemType) { + return new TreasureChestItemIterator(this, itemType); + } + + public List getItems() { + return new ArrayList<>(items); + } +} +``` + +Ecco la classe `Item`: + +```java +public class Item { + + private ItemType type; + private final String name; + + public Item(ItemType type, String name) { + this.setType(type); + this.name = name; + } + + @Override + public String toString() { + return name; + } + + public ItemType getType() { + return type; + } + + public final void setType(ItemType type) { + this.type = type; + } +} + +public enum ItemType { + + ANY, WEAPON, RING, POTION + +} +``` + +L'interfaccia `Iterator` è estremamente semplice. + +```java +public interface Iterator { + + boolean hasNext(); + + T next(); +} +``` + +Nell'esempio seguente, si iterano gli oggetti di tipo anello che si trovano nel forziere. + +```java +var itemIterator = TREASURE_CHEST.iterator(ItemType.RING); +while (itemIterator.hasNext()) { + LOGGER.info(itemIterator.next().toString()); +} +``` + +Output del programma: + +```java +Ring of shadows +Ring of armor +``` + +## Diagramma delle classi + +![alt text](../../../iterator/etc/iterator_1.png "Iterator") + +## Applicabilità + +Usa il pattern Iterator + +* Per accedere ai contenuti di un oggetto aggregato senza esporre la sua rappresentazione interna. +* Per supportare più attraversamenti di oggetti aggregati. +* Per fornire un'interfaccia uniforme per l'attraversamento di diverse strutture aggregate. + +## Tutorial + +* [How to Use Iterator?](http://www.tutorialspoint.com/java/java_using_iterator.htm) + +## Usi noti + +* [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html) +* [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html) + +## Collegamenti esterni + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/it/observer/README.md b/localization/it/observer/README.md new file mode 100644 index 000000000000..cfc0d675de70 --- /dev/null +++ b/localization/it/observer/README.md @@ -0,0 +1,160 @@ +--- +title: Observer +category: Behavioral +language: it +tag: + - Gang Of Four + - Reactive +--- + +## Anche conosciuto come + +Dependents, Publish-Subscribe + +## Intento + +Stabilire una dipendenza uno-a-molti tra gli oggetti in modo che quando un oggetto cambia stato, tutti i suoi dipendenti vengano avvisati e aggiornati automaticamente. + +## Spiegazione + +Esempio del mondo reale + +> In una terra lontana vivono le razze degli hobbit e degli orchi. Entrambi trascorrono la maggior parte del tempo all'aperto, quindi +> seguono attentamente i cambiamenti del tempo. Si potrebbe dire che osservano costantemente le +> condizioni meteorologiche. + +In parole semplici + +> Registrarsi come osservatore per ricevere notifiche di cambiamenti di stato nell'oggetto. + +Wikipedia dice + +> Il pattern observer è un design pattern in cui un oggetto, chiamato soggetto, +> mantiene una lista dei suoi dipendenti, chiamati osservatori, e li avvisa automaticamente di eventuali cambiamenti di stato, +> di solito chiamando uno dei loro metodi. _(Testo tradotto dalla voce Observer Pattern da Wikipedia in lingua inglese)._ + +**Esempio di codice** + +Iniziamo introducendo l'interfaccia `WeatherObserver` e le nostre razze, `Orcs` e `Hobbits`. + +```java +public interface WeatherObserver { + + void update(WeatherType currentWeather); +} + +@Slf4j +public class Orcs implements WeatherObserver { + + @Override + public void update(WeatherType currentWeather) { + LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now"); + } +} + +@Slf4j +public class Hobbits implements WeatherObserver { + + @Override + public void update(WeatherType currentWeather) { + switch (currentWeather) { + LOGGER.info("The hobbits are facing " + currentWeather.getDescription() + " weather now"); + } + } +} +``` + +Poi c'è il `Weather` che cambia continuamente. + +```java +@Slf4j +public class Weather { + + private WeatherType currentWeather; + private final List observers; + + public Weather() { + observers = new ArrayList<>(); + currentWeather = WeatherType.SUNNY; + } + + public void addObserver(WeatherObserver obs) { + observers.add(obs); + } + + public void removeObserver(WeatherObserver obs) { + observers.remove(obs); + } + + /** + * Makes time pass for weather. + */ + public void timePasses() { + var enumValues = WeatherType.values(); + currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; + LOGGER.info("The weather changed to {}.", currentWeather); + notifyObservers(); + } + + private void notifyObservers() { + for (var obs : observers) { + obs.update(currentWeather); + } + } +} +``` + +Ecco l'esempio completo in azione. + +```java + var weather = new Weather(); + weather.addObserver(new Orcs()); + weather.addObserver(new Hobbits()); + weather.timePasses(); + weather.timePasses(); + weather.timePasses(); + weather.timePasses(); +``` + +Output del programma: + +``` +The weather changed to rainy. +The orcs are facing rainy weather now +The hobbits are facing rainy weather now +The weather changed to windy. +The orcs are facing windy weather now +The hobbits are facing windy weather now +The weather changed to cold. +The orcs are facing cold weather now +The hobbits are facing cold weather now +The weather changed to sunny. +The orcs are facing sunny weather now +The hobbits are facing sunny weather now +``` + +## Diagramma delle classi + +![alt text](../../../observer/etc/observer.png "Observer") + +## Applicabilità + +Usa il pattern Observer in una qualsiasi delle seguenti situazioni: + +* Quando un'astrazione ha due aspetti, uno dipendente dall'altro. L'incapsulamento di questi aspetti in oggetti separati ti permette di variarli e riutilizzarli in modo indipendente. +* Quando una modifica a un oggetto richiede la modifica di altri oggetti, e non sai quanti oggetti devono essere modificati. +* Quando un oggetto dovrebbe essere in grado di avvisare altri oggetti senza fare presupposizioni su chi siano questi oggetti. In altre parole, non desideri che questi oggetti siano strettamente accoppiati. + +## Usi noti + +* [java.util.Observer](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html) +* [java.util.EventListener](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html) +* [javax.servlet.http.HttpSessionBindingListener](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html) +* [RxJava](https://github.com/ReactiveX/RxJava) + +## Collegamenti esterni + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Java Generics and Collections](https://www.amazon.com/gp/product/0596527756/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596527756&linkCode=as2&tag=javadesignpat-20&linkId=246e5e2c26fe1c3ada6a70b15afcb195) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/ja/README.md b/localization/ja/README.md new file mode 100644 index 000000000000..fb789f991841 --- /dev/null +++ b/localization/ja/README.md @@ -0,0 +1,60 @@ +# Java で実装されたデザインパターン + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + + + +[![All Contributors](https://img.shields.io/badge/all_contributors-185-orange.svg?style=flat-square)](#contributors-) + + + +# はじめに + +デザインパターンとは、アプリケーションやシステムを設計する際によくある問題を解決するために、プログラマーが使用できる形式化された最良の手法です。 + +デザインパターンは、テストされ、証明された開発パラダイムを提供することで、開発プロセスを高速化することができます。 + +デザインパターンを再利用することで、大きな問題を引き起こす微妙な問題を防ぐことができます。 +また、デザインパターンを熟知したコーダーやアーキテクトにとっても、コードの読みやすさが向上します。 + +# はじめる + +このサイトでは、Java のデザインパターンを紹介しています。 +これらのソリューションは、オープンソースコミュニティの経験豊富なプログラマーやアーキテクトによって開発されています。 + +パターンは、ハイレベルの説明またはソースコードを確認することで参照できます。 + +ソースコードの例はよくコメントされていて、特定のパターンをどのように実装するかを説明するプログラミングチュートリアルのようなものです。 + +私たちは、最も一般的で実績のあるオープンソースの Java 技術を使用しています。 + +資料に飛び込む前に、さまざまな[ソフトウェア設計の原則](https://java-design-patterns.com/principles/)に精通している必要があります。 + +すべてのデザインは、可能な限りシンプルであるべきです。 + +KISS(シンプルにしておけ!この間抜け)、YAGNI(機能は実際に必要となるまでは追加しないのがよい)、そして Do The Simplest Thing That Could Possibly Work(機能する可能性のある中で最もシンプルなことをする)の原則に基づいて設計を始めるべきです。 + +複雑さやパターンは、実用的な拡張性が必要な場合にのみ導入すべきです。 + +これらの概念を理解した上で、以下のような方法で[デザインパターン](https://java-design-patterns.com/patterns/) を掘り下げていくことができます。 + +- 特定のパターンを、パターン名で検索することができます。見つかない場合は、新しいパターンを[ここ](https://github.com/iluwatar/java-design-patterns/issues)で報告してください +- `Performance`, `Gang of Four` もしくは`Data access`などのタグを使用。 +- `Creational`, `Behavioral`などのパターンカテゴリーを使用。 + +このサイトで紹介されているオブジェクト指向のソリューションが、あなたのアーキテクチャに役立ち、私たちが開発したように楽しく学ぶことができますように。 + +# コントリビュート方法 + +プロジェクトに貢献したいとお考えの方は、[開発者 wiki](https://github.com/iluwatar/java-design-patterns/wiki)に関連情報が掲載されています。 + +私たちは、[Gitter チャットルーム](https://gitter.im/iluwatar/java-design-patterns)であなたの質問にお答えします。 + +# ライセンス + +このプロジェクトは、MIT ライセンスの条件の下でライセンスされています。 + diff --git a/localization/ja/decorator/README.md b/localization/ja/decorator/README.md new file mode 100644 index 000000000000..d67bfb805459 --- /dev/null +++ b/localization/ja/decorator/README.md @@ -0,0 +1,160 @@ +--- +title: Decorator +category: Structural +language: ja +tag: + - Gang of Four + - Extensibility +--- + +## 別名 + +Wrapper + +## 目的 + +オブジェクトに責任を動的に追加する。 +Decorator パターンは、サブクラス化よりも柔軟な機能拡張方法を提供する。 + +## 説明 + +実世界の例 + +> 近くの丘に住む怒ったトロールがいる。大抵は素手だが、たまに武器を持っている。トロールに武器を持たせるためには、新しいトロールを作る必要はなく、適切な武器を動的に装飾すればいい。 + +分かりやすい説明 + +> Decorator パターンを用いると、decorator クラスのオブジェクトにラップすることで、オブジェクトの振る舞いを実行時間で動的に変更することができる。 + +Wikipedia の説明 + +> オブジェクト指向プログラミングにおいて、Decorator パターンは、同じクラスの別のオブジェクトの振る舞いに影響を与えることなく、静的もしくは動的に、個別のオブジェクトに振る舞いを加えることができるデザインパターンである。Decorator パターンは、単一責任の原則を遵守するためにしばしば便利である。なぜなら、クラスの機能性を変更せずに拡張することで、開放/閉鎖原則などの関心事の特異な分野を元に、クラスの間で機能性を分割することができるためである。 + +**サンプルコード** + +トロールを例として使用する。まず、Troll のインターフェイスを実装する SimpleTroll クラスを作る。 + +```java +public interface Troll { + void attack(); + int getAttackPower(); + void fleeBattle(); +} + +@Slf4j +public class SimpleTroll implements Troll { + + @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!"); + } +} +``` + +次に、トロールに対してこん棒を追加する。decorator を使い、動的に追加することが可能である。 + +```java +@Slf4j +public class ClubbedTroll implements Troll { + + private final 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(); + } +} +``` + +以下がトロールの動き。 + +```java +// simple troll +LOGGER.info("A simple looking troll approaches."); +var troll = new SimpleTroll(); +troll.attack(); +troll.fleeBattle(); +LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower()); + +// change the behavior of the simple troll by adding a decorator +LOGGER.info("A troll with huge club surprises you."); +var clubbedTroll = new ClubbedTroll(troll); +clubbedTroll.attack(); +clubbedTroll.fleeBattle(); +LOGGER.info("Clubbed troll power: {}.\n", clubbedTroll.getAttackPower()); +``` + +アウトプット + +```java +A simple looking troll approaches. +The troll tries to grab you! +The troll shrieks in horror and runs away! +Simple troll power: 10. + +A troll with huge club surprises you. +The troll tries to grab you! +The troll swings at you with a club! +The troll shrieks in horror and runs away! +Clubbed troll power: 20. +``` + +## クラス図 + +![alt text](./etc/decorator.urm.png "Decorator pattern class diagram") + +## 適用可能性 + +次のような場合に Decorator パターンを利用する。 + +* 個々のオブジェクトに責任を動的、かつ透明に(すなわち、他のオブジェクトに影響を与えないように)追加する場合。 +* 責任を取りはずすことができるようにする場合。 +* サブクラス化による拡張が非現実的な場合。非常に多くの独立した拡張が起こり得ることがある。このような場合、サブクラス化により全ての組み合わせの拡張に対応しようとすると、莫大な数のサブクラスが必要になるだろう。また、クラス定義が隠蔽されている場合や入手できない場合にも、このパターンを利用できる。 + +## チュートリアル + +* [Decorator Pattern Tutorial](https://www.journaldev.com/1540/decorator-design-pattern-in-java-example) + +## 使用例 + + * [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), + [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) and [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) + * [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-) + * [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-) + * [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-) + + +## クレジット + +* [オブジェクト指向における再利用のためのデザインパターン](https://www.amazon.co.jp/%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E6%8C%87%E5%90%91%E3%81%AB%E3%81%8A%E3%81%91%E3%82%8B%E5%86%8D%E5%88%A9%E7%94%A8%E3%81%AE%E3%81%9F%E3%82%81%E3%81%AE%E3%83%87%E3%82%B6%E3%82%A4%E3%83%B3%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3-%E3%82%A8%E3%83%AA%E3%83%83%E3%82%AF-%E3%82%AC%E3%83%B3%E3%83%9E/dp/4797311126) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/ja/decorator/etc/decorator.urm.png b/localization/ja/decorator/etc/decorator.urm.png new file mode 100644 index 000000000000..141c0563f0c6 Binary files /dev/null and b/localization/ja/decorator/etc/decorator.urm.png differ diff --git a/localization/ko/README.md b/localization/ko/README.md new file mode 100644 index 000000000000..2a1d34790fc7 --- /dev/null +++ b/localization/ko/README.md @@ -0,0 +1,53 @@ + + +# 자바로 구현된 디자인 패턴 + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-270-orange.svg?style=flat-square)](#contributors-) + + +
    + +다른 언어로 읽기 : [**zh**](localization/zh/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md), [**vi**](localization/vi/README.md), [**bn**](localization/bn/README.md), [**np**](localization/ne/README.md), [**it**](localization/it/README.md), [**da**](localization/da/README.md) + +
    + +# 소개 + +디자인 패턴은 개발자가 응용 프로그램이나 시스템을 디자인할 때 일반적인 문제를 해결하는 데 사용할 수 있는 가장 정석적인 방법입니다. + +디자인 패턴은 테스트되고 입증된 개발 패러다임을 제공하여 개발 프로세스 속도를 높일 수 있습니다. + +디자인 패턴을 사용하면 주요 문제를 유발하는 미묘한 이슈들을 방지하는 데 도움이 되며 또한 패턴에 익숙한 개발자와 아키텍트의 코드 가독성을 향상시킵니다. + +# 시작하기 + +이 사이트는 Java 디자인 패턴을 설명합니다. 이 솔루션은 오픈 소스 커뮤니티의 경험이 많은 개발자와 설계자가 개발했습니다. 패턴이 높은 수준의 설명이나 소스 코드를 통해 찾아볼 수 있습니다. 소스 코드 예제는 잘 설명되어 있으며 특정 패턴을 구현하는 방법을 알려주는 프로그래밍 튜토리얼로 사용할 수 있습니다. 우리는 가장 널리 알려지고 실무에서 입증된 오픈 소스 Java 기술을 사용합니다. + +자료를 살펴보기 전에 다양한 [소프트웨어 설계 원칙](https://java-design-patterns.com/principles/)을 숙지해야 합니다. + +모든 디자인 패턴은 가능한 한 심플해야 합니다. 소프트웨어 개발의 KISS, YAGNI 원칙을 지켜야 하며, 문제를 해결할 수 있는 가장 심플한 일을 해야 합니다. 복잡한 디자인 패턴은 실용적이고 확장성을 위해 필요할 때만 도입되어야 합니다. + +이러한 개념에 익숙해지면 아래와 같은 방법으로 [사용 가능한 디자인 패턴](https://java-design-patterns.com/patterns/) 중 하나를 선택하여 문제를 해결할 수 있습니다. + +- 이름으로 특정 패턴을 검색합니다. 찾는 패턴이 없다면 [여기](https://github.com/iluwatar/java-design-patterns/issues)에서 새 패턴을 요청하세요. +- `Performance`, `Gang of Four` 또는 `Data access` 등의 태그로 검색하세요. +- `Creational`, `Behavioral` 등의 패턴 카테고리로 검색하세요. + +이 사이트에서 제공하는 객체 지향 솔루션이 여러분의 아키텍처에 유용하고 사용되고 우리가 개발 한 것만큼 재미있게 배우기를 바랍니다. + +# 기여하는 방법 + +프로젝트에 기여할 의향이 있다면 [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki)에서 관련 정보를 찾을 수 있습니다. [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns)에서 귀하를 돕고 질문에 답변해 드리겠습니다. + +# 특허 + +이 프로젝트는 MIT 라이센스 조건에 따라 라이센스가 적용됩니다. + diff --git a/localization/ko/adapter/README.md b/localization/ko/adapter/README.md new file mode 100644 index 000000000000..0b8201b56c4a --- /dev/null +++ b/localization/ko/adapter/README.md @@ -0,0 +1,133 @@ +--- +title: Adapter +shortTitle: Adapter +category: Structural +language: ko +tag: +- Gang of Four +--- + +## 또한 ~으로 알려진 + +Wrapper + +## 의도 + +클래스의 인터페이스를 클라이언트가 기대하는 다른 인터페이스로 변환합니다. adapter를 사용하면 호환되지 않는 인터페이스로 인해 같이 쓸 수 없는 클래스를 함께 작동 할 수 있습니다. + +## 설명 + +예시 + +> 메모리 카드에 몇 장의 사진이 있고 컴퓨터로 전송해야한다고 생각하십시오. 이들을 전송하려면 컴퓨터에 메모리 카드를 연결할 수 있도록 컴퓨터 포트와 호환되는 어댑터가 필요합니다. 이 경우 카드 리더는 어댑터입니다. 또 다른 예는 유명한 전원 어댑터입니다. 세 갈래 플러그는 두 갈래 콘센트에 연결할 수 없습니다. 두 갈래 콘센트와 호환되는 전원 어댑터를 사용해야합니다. 또 다른 예는 한 사람이 말한 단어를 다른 사람에게 번역하는 번역가입니다. + +평범하게 말하자면 + +> adapter 패턴을 사용하면 호환되지 않는 개체를 adapter에 연결하여 다른 클래스와 호환되도록 할 수 있습니다. + +Wikipedia 말에 의하면 + +> 소프트웨어 엔지니어링에서 adapter 패턴은 기존 클래스의 인터페이스를 다른 인터페이스로 사용할 수 있도록 하는 소프트웨어 디자인 패턴입니다. 소스 코드를 수정하지 않고 기존 클래스가 다른 클래스와 함께 작동하도록 만드는 데 자주 사용됩니다. + +**프로그램 코드 예제** + +조정 보트만 사용할 수 있고 전혀 항해할 수 없는 선장을 생각해보십시오. + +먼저 `RowingBoat` 및 `FishingBoat` 인터페이스가 있습니다. + +```java +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"); + } +} +``` + +그리고 선장은 `RowingBoat` 인터페이스를 이동할 수 있게 구현했습니다. + +```java +public class Captain { + + private final RowingBoat rowingBoat; + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +이제 해적이오고 있고 우리 선장이 탈출해야하는데 어선만 있습니다. 선장이 조정 보트 기술로 어선을 조작 할 수있는 adapter를 만들어야합니다. + +```java +public class FishingBoatAdapter implements RowingBoat { + + private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoatAdapter.class); + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} +``` + +이제 `Captain` 은 `FishingBoat` 를 사용하여 해적을 탈출 할 수 있습니다. + +```java +var captain = new Captain(new FishingBoatAdapter()); +captain.row(); +``` + +## 클레스 다이어그램 + +![alt text](./etc/adapter.urm.png) + +## 적용 가능성 + +다음과 같은 경우 adapter 패턴을 사용합니다. + +- 기존 클래스를 사용 하려는데 해당 인터페이스가 필요한 클래스와 일치하지 않습니다. +- 관련이 없거나 예상치 못한 클래스, 즉 호환되는 인터페이스가 반드시 필요하지 않은 클래스와 협력하는 재사용 가능한 클래스를 만들고 싶습니다. +- 기존의 여러 하위 클래스를 사용해야하지만 모든 하위 클래스를 하위 클래스로 지정하여 인터페이스를 조정하는 것은 비현실적입니다. 개체 adapter는 부모 클래스의 인터페이스를 조정할 수 있습니다. +- 타사 라이브러리를 사용하는 대부분의 응용 프로그램은 adapter를 응용 프로그램과 타사 라이브러리 사이의 중간 계층으로 사용하여 라이브러리에서 응용 프로그램을 분리합니다. 다른 라이브러리를 사용해야하는 경우 애플리케이션 코드를 변경할 필요없이 새 라이브러리 용 adapter만 필요합니다. + +## 결과 : + +클래스 및 개체 adapter에는 서로 다른 장단점이 있습니다.
    클래스 adapter + +- 구체적인 Adaptee 클래스를 커밋하여 Adaptee를 Target에 적용합니다. 결과적으로 클래스와 모든 하위 클래스를 조정하려는 경우 클래스 adapter가 작동하지 않습니다. +- adapter는 Adaptee의 하위 클래스이기 때문에 Adaptee의 일부 동작을 오버라이드합니다. +- 하나의 객체만 생성하고 adaptee를 얻기위해 위해 추가 포인터 간접 지정이 필요하지 않습니다. + +개체 adapter + +- 하나의 adapter가 많은 Adaptees, 즉 Adaptee 자체와 모든 하위 클래스 (있는 경우)와 함께 작동하도록합시다. adapter는 한 번에 모든 어댑터에 기능을 추가 할 수도 있습니다. +- Adaptee 동작을 오버라이드하기가 더 어렵습니다. Adaptee를 서브 클래싱하고 어댑터가 Adaptee 자체가 아닌 서브 클래스를 참조하도록 해야합니다. + +## 실제 사례 + +- [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +- [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +- [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +- [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + +## 크레딧 + +- [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +- [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +- [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +- [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/ko/adapter/etc/adapter.urm.png b/localization/ko/adapter/etc/adapter.urm.png new file mode 100644 index 000000000000..341ad67699d9 Binary files /dev/null and b/localization/ko/adapter/etc/adapter.urm.png differ diff --git a/localization/ko/builder/README.md b/localization/ko/builder/README.md new file mode 100644 index 000000000000..6189c74fb160 --- /dev/null +++ b/localization/ko/builder/README.md @@ -0,0 +1,145 @@ +--- +title: Builder +shortTitle: Builder +category: Creational +language: ko +tag: +- Gang of Four +--- + +## 의도 + +동일한 구성 프로세스가 다른 표현을 생성할 수 있도록 복잡한 객체의 구성을 해당 표현과 분리합니다. + +## 설명 + +실제 예제 + +> 롤플레잉 게임의 캐릭터 생성기를 상상해 보세요. 가장 쉬운 옵션은 컴퓨터가 사용자를 위해 문자를 만들도록 하는 것입니다. 직업, 성별, 머리색 등 캐릭터 세부 정보를 수동으로 선택하려면 캐릭터 생성은 모든 선택이 준비되었을 때 완료되는 단계별 프로세스가 됩니다. + +쉽게 말하자면 + +> 생성자의 오염을 방지하면서 객체의 다른 맛들을 만들 수 있습니다. 여러 가지 맛의 객체가 있을 때 유용합니다. 또는 개체를 만드는 데 많은 단계가 수반될 때 유용합니다. + +Wikipedia에 의하면 + +> 빌더 패턴은 점층적 생성자 안티-패턴(telescoping constructor anti-pattern)에 대한 해결책을 찾기 위한 목적을 가진 객체 생성 소프트웨어 디자인 패턴이다. + +그렇긴 하지만, 점층적 생성자 안티-패턴(telescoping constructor anti-pattern)이 무엇인지 조금 더 설명하겠습니다. 어느 시점에서, 우리는 모두 다음과 같은 생성자를 보았습니다. + +```java +public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) { +} +``` + +보시다시피 생성자 매개 변수의 수는 빠르게 감당할 수 없게 되고 매개 변수의 배치를 이해하는 것이 어려워질 수 있습니다. 또한 이 매개 변수 목록은 나중에 더 많은 옵션을 추가하려는 경우 계속 증가할 수 있습니다. 이를 점층적 생성자 안티-패턴(telescoping constructor anti-pattern)이라고 합니다. + +**코드 예제** + +올바른 대안은 빌더 패턴을 사용하는 것입니다. 우선, 우리는 우리가 창조하고 싶은 영웅을 가지고 있습니다. : + + +```java +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; + } +} +``` + +그리고 우리는 빌더를 가지고 있습니다. : + +```java + 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); + } + } +``` + +그런 다음, 다음과 같이 사용할 수 있습니다. + + +```java +var mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build(); +``` + +## 클래스 다이어그램 + +![alt text](./etc/builder.urm.png "Builder class diagram") + +## 적용 가능성 + +다음과 같은 경우 빌더 패턴을 사용합니다. + +* 복잡한 객체를 만드는 알고리즘은 객체를 구성하는 부품과 이들이 조립되는 방법에 독립적이어야 한다. +* 구축 프로세스는 구성된 객체에 대해 서로 다른 표현을 허용해야 합니다. + +## 튜토리얼 + +* [Refactoring Guru](https://refactoring.guru/design-patterns/builder) +* [Oracle Blog](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) +* [Journal Dev](https://www.journaldev.com/1425/builder-design-pattern-in-java) + +## 실제 사례 + +* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) +* [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) as well as similar buffers such as FloatBuffer, IntBuffer and so on. +* [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) +* All implementations of [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) +* [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/ko/builder/etc/builder.urm.png b/localization/ko/builder/etc/builder.urm.png new file mode 100644 index 000000000000..d77808d36097 Binary files /dev/null and b/localization/ko/builder/etc/builder.urm.png differ diff --git a/localization/ko/callback/README.md b/localization/ko/callback/README.md new file mode 100644 index 000000000000..caaa4a39874f --- /dev/null +++ b/localization/ko/callback/README.md @@ -0,0 +1,72 @@ +--- +title: Callback +shortTitle: Callback +category: Idiom +language: ko +tag: +- Reactive +--- + +## 의도 + +콜백은 다른 코드에 인자로 넘어가는 실행 가능한 코드의 일부로, 인자는 적절한 시점에 다시 호출 (실행) 된다. + +## 설명 + +실제 예제 + +> 실행 항목이 완료되었다는 사실을 고지받아야 할 때, 콜백 함수를 실행 항목을 담당하는 함수에게 넘겨주고 다시 호출할 때까지 기다린다. + +명확하게는 + +> 콜백은 실행 함수에 넘겨져서 정의된 순간에 호출되는 함수이다. + +위키피디아의 정의는 + +> 컴퓨터 프로그래밍에서, "사후-호출" 함수로도 알려진 콜백은, 다른 코드에 인자로 넘겨지는 실행 가능한 코드를 말한다; +> 다른 코드는 정해진 시간에 인자를 다시 호출 (실행) 할 것으로 기대되어진다. + +**코드 예제** + +콜백은 하나의 메서드를 가지고 있는 단순한 인터페이스이다. + +```java +public interface Callback { + + void call();} +``` + +다음으로 작업의 실행이 끝나고 나서 콜백을 실행시킬 Task 클래스를 정의한다. + +```java +public abstract class Task { + + final void executeWith(Callback callback) { execute(); Optional.ofNullable(callback).ifPresent(Callback::call); } + public abstract void execute();} + +@Slf4j +public final class SimpleTask extends Task { + + @Override public void execute() { LOGGER.info("우선순위의 작업을 마친 이후 콜백 메서드를 호출한다."); + }} +``` + +마지막으로, 다음은 작업을 실행한 후 마쳤을 때 콜백을 받는 방법의 예시이다. + +```java + var task = new SimpleTask(); task.executeWith(() -> LOGGER.info("완료되었음.")); +``` + +## 클래스 다이어그램 + +![alt text](./etc/callback.png "callback") + +## 적용 + +콜백 패턴을 사용할 수 있을 때는 + +* 동기 또는 비동기적인 임의의 행위가 정의된 어떠한 행위의 실행 이후에 수행되어야 할 때이다. + +## 실질적인 예시들 + +* [CyclicBarrier](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) 생성자는 장벽이 넘어질 때마다 발동되는 콜백을 인자로 받을 수 있다. \ No newline at end of file diff --git a/localization/ko/callback/etc/callback.png b/localization/ko/callback/etc/callback.png new file mode 100644 index 000000000000..7b499f79fcaa Binary files /dev/null and b/localization/ko/callback/etc/callback.png differ diff --git a/localization/ko/decorater/README.md b/localization/ko/decorater/README.md new file mode 100644 index 000000000000..5a21841fb4ca --- /dev/null +++ b/localization/ko/decorater/README.md @@ -0,0 +1,168 @@ +--- +title: Decorator +shortTitle: Decorator +category: Structural +language: en +tag: + - Gang of Four + - Extensibility +--- + +## ~로 알려져 있는 + +Wrapper + +## 의도 + +객체에 동적으로 추가적인 책임을 부여합니다. 데코레이터(Decorater)는 기능 확장을 위한 서브 클래스를 만드는 것의 +유연한 대안을 제공합니다. + +## 설명 + +실제 예제 + +> 근처 언덕에 성난 트롤이 살고 있습니다. 보통은 맨손으로 다니지만 가끔씩은 무기를 가지고 있습니다. +> 트롤을 무장시키기 위해 새로운 트롤을 만들 필요 없이 적절한 무기로 트롤을 장식(decorate)하면 됩니다. + +쉽게 설명하면 + +> 데코레이터(Decorator) 패턴은 객체를 데코레이터(Decorater) 클래스의 객체로 감싸 런타임 시, +> 객체의 동작을 동적으로 변경할 수 있도록 합니다. + +Wikipedia에 의하면 + +> 객체 지향 프로그래밍에서, 데코레이터(Decorater)은 다음과 같은 동작을 허용하는 디자인 패턴입니다. +> 정적, 동적 상관없이 개별 객체에 동작을 추가할 수 있는 디자인 패턴입니다. +> 동작에 영향을 주지 않고 개별 객체에 동작을 추가할 수 있는 디자인 패턴입니다. +> 데코레이터(Decorater) 패턴은 종종 단일 책임 원칙(SRP)을 준수하는데 유용합니다. +> 고유한 관심 영역을 가진 클래스 간에 기능을 나눌 수 있기 때문에 개방 폐쇄 원칙(OCP)를 준수하는데 유용합니다. +> 클래스의 기능을 수정하지 않고 확장할 수 있기 때문입니다. + +**프로그램 코드 예제** + +트롤을 예로 들어보겠습니다. 먼저, 'Troll' 인터페이스를 구현하는 'SimpleTroll'이 있습니다. + +```java +public interface Troll { + void attack(); + int getAttackPower(); + void fleeBattle(); +} + +@Slf4j +public class SimpleTroll implements Troll { + + @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!"); + } +} +``` + +다음으로, 트롤을 위한 곤봉을 추가하겠습니다. 데코레이터(Decorater)를 사용해 동적으로 추가할 수 있습니다. + +```java +@Slf4j +public class ClubbedTroll implements Troll { + + private final 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(); + } +} +``` + +트롤이 실제로 동작하는 모습입니다. + +```java +// simple troll +LOGGER.info("A simple looking troll approaches."); +var troll = new SimpleTroll(); +troll.attack(); +troll.fleeBattle(); +LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower()); + +// change the behavior of the simple troll by adding a decorator +LOGGER.info("A troll with huge club surprises you."); +var clubbedTroll = new ClubbedTroll(troll); +clubbedTroll.attack(); +clubbedTroll.fleeBattle(); +LOGGER.info("Clubbed troll power: {}.\n", clubbedTroll.getAttackPower()); +``` + +프로그램 실행 결과: + +```java +A simple looking troll approaches. +The troll tries to grab you! +The troll shrieks in horror and runs away! +Simple troll power: 10. + +A troll with huge club surprises you. +The troll tries to grab you! +The troll swings at you with a club! +The troll shrieks in horror and runs away! +Clubbed troll power: 20. +``` + +## 클래스 다이어그램 + +![alt text](./etc/decorator.urm.png "Decorator pattern class diagram") + +## 적용 가능성 + +다음과 같은 경우 데코레이터(Decorator) 패턴을 사용합니다.: + +* 다른 객체에 영향을 주지 않으면서 개별 객체에 동적으로 투명하게 책임을 추가할 수 있습니다. +* 철회될 수 있는 책임들의 경우에 사용합니다. +* 서브클래스를 통한 확장이 실용적이지 않을 경우에 사용합니다. 때로 많은 수의 독립적인 확장은 모든 조합을 지원하기 위해 서브클래스가 폭발적으로 늘어날 수 있습니다. + 또는 클래스 정의가 숨겨져 있거나 서브클래스 생성이 불가능한 경우에 사용합니다. + +## 튜토리얼 + +* [Decorator Pattern Tutorial](https://www.journaldev.com/1540/decorator-design-pattern-in-java-example) + +## 실제 사례 + + * [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), + [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html), [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) + * [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-) + * [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-) + * [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-) + + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/ko/decorater/etc/decorator.urm.png b/localization/ko/decorater/etc/decorator.urm.png new file mode 100644 index 000000000000..141c0563f0c6 Binary files /dev/null and b/localization/ko/decorater/etc/decorator.urm.png differ diff --git a/localization/ko/event-driven-architecture/README.md b/localization/ko/event-driven-architecture/README.md new file mode 100644 index 000000000000..88f5a395c731 --- /dev/null +++ b/localization/ko/event-driven-architecture/README.md @@ -0,0 +1,34 @@ +--- +title: Event Driven Architecture +shortTitle: Event Driven Architecture +category: Architectural +language: ko +tag: +- Reactive +--- + +## 의도 +이벤트 드리븐 아키텍처를 사용하는 다른 어플리케이션에 특정 객체의 상태 변화를 알리고 관련 이벤트를 발송할 수 있습니다. + +## 클래스 다이어그램 +![alt text](./etc/eda.png "Event Driven Architecture") + +## 적용 가능성 +아래와 같은 상황에서 이벤트 드리븐 아키텍처를 사용할 수 있습니다. + +* 느슨하게 연결된 시스템을 구축하고자 하는 경우 +* 반응형 시스템을 구축하고자 하는 경우 +* 확장성을 갖춘 시스템을 구축하고자 하는 경우 + +## 실제 적용 사례 + +* Chargify라는 결제 API에서는 다양한 이벤트를 통해 결제 활동을 드러냅니다. (https://docs.chargify.com/api-events) +* Amazon의 AWS Lambda에서는 Amazon S3 버킷에서의 변경, Amazon DynamoDB 테이블에서의 수정이나 어플리케이션 및 기기에서 발생한 커스텀 이벤트에 대응하여 코드를 실행할 수 있습니다. (https://aws.amazon.com/lambda) +* MySQL은 데이터베이스 테이블에서 발생하는 삽입이나 수정 이벤트를 기반으로 트리거를 실행합니다. + +## 크레딧 + +* [이벤트 드리븐 아키텍처 - 위키피디아](https://en.wikipedia.org/wiki/Event-driven_architecture) +* [이벤트 드리븐 아키텍처는 무엇인가?](https://aws.amazon.com/event-driven-architecture/) +* [실제 적용 사례/이벤트 드리븐 아키텍처](https://wiki.haskell.org/Real_World_Applications/Event_Driven_Applications) +* [이벤트 드리븐 아키텍처의 정의](http://searchsoa.techtarget.com/definition/event-driven-architecture) diff --git a/localization/ko/event-driven-architecture/etc/eda.png b/localization/ko/event-driven-architecture/etc/eda.png new file mode 100644 index 000000000000..743726451802 Binary files /dev/null and b/localization/ko/event-driven-architecture/etc/eda.png differ diff --git a/localization/ko/event-sourcing/README.md b/localization/ko/event-sourcing/README.md new file mode 100644 index 000000000000..e71882970e59 --- /dev/null +++ b/localization/ko/event-sourcing/README.md @@ -0,0 +1,37 @@ +--- +title: Event Sourcing +shortTitle: Event Sourcing +category: Architectural +language: ko +tag: +- Performance +- Cloud distributed + +--- + +## 의도 + +데이터의 현재 상태만 도메인에 저장하는 대신, 추가 전용 저장소를 사용하여 해당 데이터에 수행된 전체 작업을 기록하십시오. 저장소는 기록 시스템으로서의 역할을 하며 도메인 객체를 구체화하는데 사용할 수 있습니다. 따라서 데이터 모델과 비지니스 도메인을 동기화할 필요가 없고 성능, 확장성 및 응답성이 향상되어 복잡한 도메인에서의 작업을 단순화할 수 있습니다. +또한, 트랜잭션 데이터에 대한 일관성을 제공하고, 보상 작업을 수행할 수 있는 전체 감사용 기록과 히스토리를 유지 관리할 수 있습니다. + +## 클래스 다이어그램 + +![alt text](./etc/event-sourcing.png "Event Sourcing") + +## 적용 가능성 +아래와 같은 상황에서 이벤트 소싱 패턴을 사용할 수 있습니다. + +* 관계형 데이터 구조가 복잡한 어플리케이션 상태를 유지하기 위해 매우 높은 성능이 필요한 경우 +* 어플리케이션 상태의 변경 사항과 특정 시점의 상태를 복원할 수 있는 기능에 대한 로그가 필요한 경우 +* 과거에 발생한 이벤트를 다시 적용하여 프로덕션 문제를 디버깅하는 경우 + +## 실제 적용 사례 + +* [Lmax 아키텍처](https://martinfowler.com/articles/lmax.html) + +## 크레딧 + +* [마틴 파울러 - 이벤트 소싱](https://martinfowler.com/eaaDev/EventSourcing.html) +* [이벤트 소싱에 대한 마이크로소프트의 문서](https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing) +* [레퍼런스 3: 이벤트 소싱에 대한 소개](https://msdn.microsoft.com/en-us/library/jj591559.aspx) +* [이벤트 소싱 패턴](https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing) diff --git a/localization/ko/event-sourcing/etc/event-sourcing.png b/localization/ko/event-sourcing/etc/event-sourcing.png new file mode 100644 index 000000000000..0b0098546300 Binary files /dev/null and b/localization/ko/event-sourcing/etc/event-sourcing.png differ diff --git a/localization/ko/facade/README.md b/localization/ko/facade/README.md new file mode 100644 index 000000000000..5ab53835a7f0 --- /dev/null +++ b/localization/ko/facade/README.md @@ -0,0 +1,225 @@ +--- +title: Facade +shortTitle: Facade +category: Structural +language: ko +tag: + - Gang Of Four + - Decoupling +--- + +## 의도 + +하위 시스템의 인터페이스 집합에 통합 인터페이스를 제공합니다. 퍼싸드(Facade)는 상위 레벨을 정의합니다. +하위시스템을 보다 쉽게 사용할 수 있는 인터페이스. + +## 설명 + +실제 예제 + +> 금광은 어떻게 운영되나요? "광부들이 저 아래로 내려가서 금을 캐죠" 라고 당신은 말합니다. +> 당신은 금광이 외부에 제공하는 간단한 인터페이스를 사용하고 있기 때문에 그렇게 믿습니다. +> 그러나 내부적으로는 많은 작업을 수행해야 합니다. 복잡한 하위 시스템에 대한 이 간단한 인터페이스는 +> 퍼싸드(Facade)입니다. + +쉽게 말하자면 + +> 퍼싸드(Facade) 패턴은 복잡한 하위 시스템에 대한 간소화된 인터페이스를 제공합니다. + +Wikipedia에 의하면 + +> 퍼싸드(Facade)는 클래스 라이브러리와 같은 더 큰 코드 본운에 간단한 인터페이스를 제공하는 객체입니다. + +**코드 예제** + +위의 금광을 예로 들어 보겠습니다. 여기에는 드워프 광산 작업자 계층 구조가 있습니다. +먼저, 베이스 클래스 `DwarvenMineWorker`가 있습니다.: + +```java + +@Slf4j +public abstract class DwarvenMineWorker { + + public void goToSleep() { + LOGGER.info("{} goes to sleep.", name()); + } + + public void wakeUp() { + LOGGER.info("{} wakes up.", name()); + } + + public void goHome() { + LOGGER.info("{} goes home.", name()); + } + + public void goToMine() { + LOGGER.info("{} goes to the mine.", name()); + } + + private void action(Action action) { + switch (action) { + case GO_TO_SLEEP -> goToSleep(); + case WAKE_UP -> wakeUp(); + case GO_HOME -> goHome(); + case GO_TO_MINE -> goToMine(); + case WORK -> work(); + default -> LOGGER.info("Undefined action"); + } + } + + public void action(Action... actions) { + Arrays.stream(actions).forEach(this::action); + } + + public abstract void work(); + + public abstract String name(); + + enum Action { + GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK + } +} +``` + +그 다음 구체적인 드워프 클래스인 `DwarvenTunnelDigger`, `DwarvenGoldDigger` 와 +`DwarvenCartOperator` 입니다: + +```java +@Slf4j +public class DwarvenTunnelDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} creates another promising tunnel.", name()); + } + + @Override + public String name() { + return "Dwarven tunnel digger"; + } +} + +@Slf4j +public class DwarvenGoldDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} digs for gold.", name()); + } + + @Override + public String name() { + return "Dwarf gold digger"; + } +} + +@Slf4j +public class DwarvenCartOperator extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} moves gold chunks out of the mine.", name()); + } + + @Override + public String name() { + return "Dwarf cart operator"; + } +} + +``` + +이 모든 금광의 일꾼들을 운영하기 위해 `DwarvenGoldmineFacade` 가 있습니다.: + +```java +public class DwarvenGoldmineFacade { + + private final List workers; + + public DwarvenGoldmineFacade() { + workers = List.of( + new DwarvenGoldDigger(), + new DwarvenCartOperator(), + new DwarvenTunnelDigger()); + } + + public void startNewDay() { + makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); + } + + public void digOutGold() { + makeActions(workers, DwarvenMineWorker.Action.WORK); + } + + public void endDay() { + makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); + } + + private static void makeActions(Collection workers, + DwarvenMineWorker.Action... actions) { + workers.forEach(worker -> worker.action(actions)); + } +} +``` + +이제 퍼싸드(facade) 패턴을 사용해 봅시다: + +```java +var facade = new DwarvenGoldmineFacade(); +facade.startNewDay(); +facade.digOutGold(); +facade.endDay(); +``` + +프로그램 실행 결과: + +```java +// Dwarf gold digger wakes up. +// Dwarf gold digger goes to the mine. +// Dwarf cart operator wakes up. +// Dwarf cart operator goes to the mine. +// Dwarven tunnel digger wakes up. +// Dwarven tunnel digger goes to the mine. +// Dwarf gold digger digs for gold. +// Dwarf cart operator moves gold chunks out of the mine. +// Dwarven tunnel digger creates another promising tunnel. +// Dwarf gold digger goes home. +// Dwarf gold digger goes to sleep. +// Dwarf cart operator goes home. +// Dwarf cart operator goes to sleep. +// Dwarven tunnel digger goes home. +// Dwarven tunnel digger goes to sleep. +``` + +## 클래스 다이어그램 + +![alt text](./etc/facade.urm.png "Facade pattern class diagram") + +## 적용 가능성 + +다음과 같은 경우 파사드 패턴을 사용합니다. + +* 복잡한 하위시스템에 간단한 인터페이스를 제공하려는 경우, 하위시스템은 점점 더 복잡해지는 경우가 많습니다. 대부분의 패턴들은 적용되었을 때, + 클래스가 점점 더 작아집니다. 이것은 하위 시스템의 재사용성을 늘리고 커스터마이징을 쉽게 해주지만, 커스터마이징이 필요없는 클라이언트는 사용하기 + 어려워집니다. 퍼싸드(Facade)는 하위시스템의 간단한 보기를 제공할 수 있습니다. 오직 커스터마이징이 필요한 클라이언트들만 퍼싸드(Facade) 너머를 + 살펴볼 필요가 있습니다. +* 클라이언트와 추상화의 구현 클래스 사이에는 많은 종속성이 있습니다. 퍼싸드(Facade)를 도입해 하위 시스템을 클라이언트 및 다른 하위 시스템으로부터 + 분리하면 다음과 같은 이점이 있습니다. + 하위 시스템의 독립성과 이식성을 촉진합니다. +* 하위 시스템을 계층화하려고 합니다. 퍼싸드(Facade)를 이용해 각 하위 시스템 계층에 대한 진입점을 정희합니다. + 하위 시스템이 종속적인 경우 하위 시스템 간의 종속성을 단순화할 수 있습니다. + 퍼싸드(Facade)를 통해서만 서로 통신할 수 있습니다. + +## 튜토리얼 + +*[DigitalOcean](https://www.digitalocean.com/community/tutorials/facade-design-pattern-in-java) +* [Refactoring Guru](https://refactoring.guru/design-patterns/facade) +* [GeekforGeeks](https://www.geeksforgeeks.org/facade-design-pattern-introduction/) +* [Tutorialspoint](https://www.tutorialspoint.com/design_pattern/facade_pattern.htm) + + + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/ko/facade/etc/facade.urm.png b/localization/ko/facade/etc/facade.urm.png new file mode 100644 index 000000000000..8e3ec7aca45e Binary files /dev/null and b/localization/ko/facade/etc/facade.urm.png differ diff --git a/localization/ko/factory-method/README.md b/localization/ko/factory-method/README.md new file mode 100644 index 000000000000..9a1cf3e709d5 --- /dev/null +++ b/localization/ko/factory-method/README.md @@ -0,0 +1,131 @@ +--- +title: "Factory Method" +shortTitle: Factory Method +category: Creational +language: ko +tag: + - Gang of Four +--- + +## 또한 ~으로 알려진 + +* Virtual Constructor + +## 의도 + +팩토리 메소드 패턴을 사용하여 객체를 생성하기 위한 인터페이스를 정의하고, 어떤 클래스를 인스턴스화할지는 하위 클래스가 결정하도록 합니다. 이 생성 설계 패턴은 클래스가 인스턴스 생성을 하위 클래스로 위임하여 코드 유연성과 유지보수성을 향상시킬 수 있습니다. + +## 설명 + +예시 + +> 한 물류 회사가 다양한 유형의 패키지를 배송해야 한다고 가정해 봅시다. 일반, 급송, 그리고 대형 배송 패키지가 있습니다. 이 회사는 중앙 시스템을 통해 배송 요청을 처리하지만, 각 패키지 유형이 어떻게 처리되는지에 대한 구체적인 사항은 알지 못합니다. 이를 관리하기 위해 이 회사는 팩토리 메소드 패턴을 사용합니다. +> +> 이 구조에서 중앙 클래스인 `DeliveryRequest`에는 `createPackage()`라는 메서드가 있습니다. 이 메서드는 `StandardDelivery`, `ExpressDelivery`, `OversizedDelivery`와 같은 하위 클래스에서 오버라이딩되며, 각 하위 클래스는 해당 패키지 유형을 생성하고 관리하는 방법을 알고 있습니다. 이렇게 함으로써 중앙 시스템은 각 패키지 유형이 어떻게 생성되고 처리되는지에 대한 세부 사항을 알 필요 없이 배송 요청을 처리할 수 있어, 유연하고 쉽게 유지보수가 가능합니다. + +평범하게 말하자면, + +> 이 패턴은 인스턴스 생성 로직을 자식 클래스에 위임하는 방법을 제공합니다. + +Wikipedia 말에 의하면 + +> 클래스 기반 프로그래밍에서, 팩토리 메소드 패턴은 생성 패턴 중 하나로, 생성할 객체의 구체적인 클래스를 명시하지 않고 객체를 생성하는 문제를 해결합니다. 이를 위해 생성자는 직접 호출하지 않고, 팩토리 메소드를 호출하여 객체를 생성하는 방식을 사용합니다. 팩토리 메소드는 인터페이스에 명시되어 자식 클래스가 구현하거나, 기본 클래스에 구현되어 파생 클래스에서 필요에 따라 오버라이딩할 수 있습니다. + +## 프로그램 코드 예제 + +팩토리 메소드 접근 방식은 다음 예제에서 볼 수 있듯이 유연하고 유지 관리 가능한 코드를 달성하기 위한 자바 디자인 패턴에서 중추적인 역할을 합니다. + +대장장이가 무기를 제작합니다. 엘프는 엘프족 무기를, 오크는 오크족 무기를 필요로 합니다. 고객에 따라 적합한 유형의 대장장이가 소환됩니다. + +우선, `Blacksmith` 인터페이스와 이를 구현한 몇 가지 클래스들이 있습니다. + +```java +public interface Blacksmith { + Weapon manufactureWeapon(WeaponType weaponType); +} + +public class ElfBlacksmith implements Blacksmith { + public Weapon manufactureWeapon(WeaponType weaponType) { + return ELFARSENAL.get(weaponType); + } +} + +public class OrcBlacksmith implements Blacksmith { + public Weapon manufactureWeapon(WeaponType weaponType) { + return ORCARSENAL.get(weaponType); + } +} +``` + +고객이 오면, 올바른 유형의 대장장이가 소환되어 요청된 무기를 제작합니다. + +```java +public static void main(String[] args) { + + Blacksmith blacksmith = new OrcBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + LOGGER.info(MANUFACTURED, blacksmith, weapon); + weapon = blacksmith.manufactureWeapon(WeaponType.AXE); + LOGGER.info(MANUFACTURED, blacksmith, weapon); + + blacksmith = new ElfBlacksmith(); + weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + LOGGER.info(MANUFACTURED, blacksmith, weapon); + weapon = blacksmith.manufactureWeapon(WeaponType.AXE); + LOGGER.info(MANUFACTURED, blacksmith, weapon); +} +``` + +프로그램 실행 결과 +``` +06:40:07.269 [main] INFO com.iluwatar.factory.method.App -- The orc blacksmith manufactured an orcish spear +06:40:07.271 [main] INFO com.iluwatar.factory.method.App -- The orc blacksmith manufactured an orcish axe +06:40:07.272 [main] INFO com.iluwatar.factory.method.App -- The elf blacksmith manufactured an elven spear +06:40:07.272 [main] INFO com.iluwatar.factory.method.App -- The elf blacksmith manufactured an elven axe +``` + +## 클래스 다이어그램 + +![alt text](./etc/factory-method.urm.png "Factory Method Class Diagram") + +## 적용 가능성 + +자바에서 팩토리 메소드 패턴을 사용하는 경우: + +* 클래스가 생성해야 할 객체의 클래스를 예측할 수 없을 때 +* 클래스가 생성할 객체를 자식 클래스가 지정하도록 하고 싶을 때 +* 여러 보조 자식 클래스 중 하나에 책임을 위임하고, 어느 자식 클래스가 해당 작업을 담당하는지에 대한 정보를 국지화하고 싶을 때 + +## 실제 사례 + +* [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +* [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +* [java.text.NumberFormat](http://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +* [java.nio.charset.Charset](http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +* [java.net.URLStreamHandlerFactory](http://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html#createURLStreamHandler-java.lang.String-) +* [java.util.EnumSet](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of-E-) +* [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) +* Frameworks that run application components, configured dynamically at runtime. + +## 장단점 + +장점: + +* 팩토리 메소드 패턴은 하위 클래스에 대한 후크(hooks)를 제공하여 코드의 유연성과 유지보수성을 높입니다. +* 병렬적인 클래스 계층 구조를 연결합니다. +* 애플리케이션 특화 클래스를 코드에 직접 포함할 필요가 없어집니다. 코드가 제품 인터페이스와만 상호작용하므로, 사용자 정의 구체 클래스와 쉽게 연동할 수 있습니다. + +단점: + +* 확장된 팩토리 메소드를 구현하기 위해 새로운 하위 클래스를 추가해야 하므로 코드가 복잡해질 수 있습니다. + +## 관련 패턴 + +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): 팩토리 메소드는 종종 추상 팩토리 패턴 내에서 호출됩니다. +* [Prototype](https://java-design-patterns.com/patterns/prototype/): 프로토타입 클래스를 복제한 새 인스턴스를 반환하는 팩토리 메소드. + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0Rk5y) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG) +* [Patterns of Enterprise Application Architecture](https://amzn.to/4b2ZxoM) diff --git a/localization/ko/factory-method/etc/factory-method.urm.png b/localization/ko/factory-method/etc/factory-method.urm.png new file mode 100644 index 000000000000..7c97aff91ee6 Binary files /dev/null and b/localization/ko/factory-method/etc/factory-method.urm.png differ diff --git a/localization/ko/factory/README.md b/localization/ko/factory/README.md new file mode 100644 index 000000000000..48d126195c86 --- /dev/null +++ b/localization/ko/factory/README.md @@ -0,0 +1,127 @@ +--- +title: Factory +shortTitle: Factory +category: Creational +language: ko +tag: +- Gang of Four +--- + +## 또한 ~으로 알려진 + +- Simple Factory +- Static Factory Method + +## 의도 + +구현 논리를 숨기고 클라이언트 코드가 새 객체를 초기화하는 대신 사용에 집중하도록하기 위해 factory라는 클래스에 캡슐화 된 정적 메서드를 제공합니다. + +## 설명 + +예시 + +> SQLServer에 연결된 웹 응용 프로그램이 있지만 이제 Oracle로 전환하려고 합니다. 기존 소스 코드를 수정하지 않고 이를 수행하려면 주어진 데이터베이스에 대한 연결을 생성하기 위해 정적 메서드를 호출 할 수 있는 Simple Factory 패턴을 구현해야합니다. + +Wikipedia 말에 의하면 + +> factory는 다른 객체를 생성하기위한 객체입니다. 공식적으로 factory는 다양한 프로토 타입 또는 클래스의 객체를 반환하는 함수 또는 메서드입니다. + +**프로그램 코드 예제** + +우리는 인터페이스 `Car` 와 두 가지 구현 `Ford` 와 `Ferrari`을 가지고 있습니다. + +```java +public interface Car { + String getDescription(); +} + +public class Ford implements Car { + + static final String DESCRIPTION = "This is Ford."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class Ferrari implements Car { + + static final String DESCRIPTION = "This is Ferrari."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +열거형은 우리가 지원하는 자동차 유형을 나타냅니다 ( `Ford` 및 `Ferrari` ). + +```java +public enum CarType { + + FORD(Ford::new), + FERRARI(Ferrari::new); + + private final Supplier constructor; + + CarType(Supplier constructor) { + this.constructor = constructor; + } + + public Supplier getConstructor() { + return this.constructor; + } +} +``` + +그런 다음 factory 클래스 `CarsFactory` 캡슐화 된 자동차 객체를 만드는 정적 메서드 `getCar` 가 있습니다. + +```java +public class CarsFactory { + + public static Car getCar(CarType type) { + return type.getConstructor().get(); + } +} +``` + +이제 클라이언트 코드에서 factory 클래스를 사용하여 다양한 유형의 자동차를 만들 수 있습니다. + +```java +var car1 = CarsFactory.getCar(CarType.FORD); +var car2 = CarsFactory.getCar(CarType.FERRARI); +LOGGER.info(car1.getDescription()); +LOGGER.info(car2.getDescription());; +``` + +프로그램 출력 : + +```java +This is Ford. +This Ferrari. +``` + +## 클래스 다이어그램 + +![alt text](./etc/factory.urm.png) + +## 적용 가능성 + +객체 생성 및 관리 방법이 아닌 객체 생성에만 관심이있을 때 Simple Factory 패턴을 사용합니다. + +장점 + +- 모든 객체 생성을 한곳에 유지하고 코드베이스에 '새'키 값이 확산되는 것을 방지합니다. +- 느슨하게 결합 된 코드를 작성할 수 있습니다. 주요 장점 중 일부는 더 나은 테스트 가능성, 이해하기 쉬운 코드, 교체 가능한 구성 요소, 확장성 및 격리된 기능을 포함합니다. + +단점 + +- 코드는 생각보다 복잡해집니다. + +## 관련 패턴 + +- [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +- [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) +- [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/) diff --git a/localization/ko/factory/etc/factory.urm.png b/localization/ko/factory/etc/factory.urm.png new file mode 100644 index 000000000000..4b3420792e06 Binary files /dev/null and b/localization/ko/factory/etc/factory.urm.png differ diff --git a/localization/ko/iterator/README.md b/localization/ko/iterator/README.md new file mode 100644 index 000000000000..fdf662efb1e6 --- /dev/null +++ b/localization/ko/iterator/README.md @@ -0,0 +1,151 @@ +--- +title: Iterator +shortTitle: Iterator +categories: Behavioral +language: ko +tag: +- Gang of Four +--- + +## 또한 ~으로 알려진 + +커서(Cursor) 패턴 + +## 의도 +기반이되는 표현을 노출하지 않고 Aggregate 객체의 요소에 순차적으로 접근할 수 있는 방법을 제공합니다. + +## 설명 + +실제 예제 + +> 보물상자에는 마법의 아이템이 들어 있습니다. 반지, 물약, 무기와 같은 다양한 종류의 물건들이 있습니다. 보물상자가 제공하는 반복기(iterator)를 사용하여 아이템은 유형별로 검색될 수 있을 것입니다. + +쉽게 말하자면 + +> 컨테이너는 요소에 대한 접근을 제공하기 위해 표현에 구애받지 않는 반복기(iterator) 인터페이스를 제공할 수 있습니다. + +Wikipedia에 의하면 + +> 반복자 패턴(iterator pattern)은 객체 지향 프로그래밍에서 반복자를 사용하여 컨테이너를 가로지르며 컨테이너의 요소들에 접근하는 디자인 패턴입니다. + +**코드 예제** + +예제의 메인 클래스는 아이템들을 담고있는 `보물상자(TreasureChest)` 입니다. + +```java +public class TreasureChest { + + private final List items; + + public TreasureChest() { + items = List.of( + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); + } + + public Iterator iterator(ItemType itemType) { + return new TreasureChestItemIterator(this, itemType); + } + + public List getItems() { + return new ArrayList<>(items); + } +} +``` + +다음은 `아이템(item)` 클래스입니다. : + +```java +public class Item { + + private ItemType type; + private final String name; + + public Item(ItemType type, String name) { + this.setType(type); + this.name = name; + } + + @Override + public String toString() { + return name; + } + + public ItemType getType() { + return type; + } + + public final void setType(ItemType type) { + this.type = type; + } +} + +public enum ItemType { + + ANY, WEAPON, RING, POTION + +} +``` + +`반복자(Iterator)` 인터페이스는 아주 단순합니다. + +```java +public interface Iterator { + + boolean hasNext(); + + T next(); +} +``` + +다음 예제에서는 보물상자에서 발견되는 고리형 항목을 반복한다. + +```java +var itemIterator = TREASURE_CHEST.iterator(ItemType.RING); +while (itemIterator.hasNext()) { + LOGGER.info(itemIterator.next().toString()); +} +``` + +프로그램 실행결과: + +```java +Ring of shadows +Ring of armor +``` + +## 클래스 다이어그램 + +![alt text](./etc/iterator_1.png "Iterator") + +## 적용 가능성 + +템플릿 메소드는 사용되어야합니다. + +* 내부 표현을 드러내지않고 aggregate 객체의 컨텐츠에 접근하기 위해서 + +* aggregate 오브젝트들의 여러 번의 횡단을 지원하기 위해서 + +* 서로 다른 aggregate 구조들의 횡단을 위한 획일적인 인터페이스를 제공하기 위해서 + +## 튜토리얼 + +* [How to Use Iterator?](http://www.tutorialspoint.com/java/java_using_iterator.htm) + +## 실제 사례 + +* [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html) +* [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html) + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/ko/iterator/etc/iterator_1.png b/localization/ko/iterator/etc/iterator_1.png new file mode 100644 index 000000000000..d8313bc5881f Binary files /dev/null and b/localization/ko/iterator/etc/iterator_1.png differ diff --git a/localization/ko/observer/README.md b/localization/ko/observer/README.md new file mode 100644 index 000000000000..983d6f6fbc27 --- /dev/null +++ b/localization/ko/observer/README.md @@ -0,0 +1,164 @@ +--- +title: Observer +shortTitle: Observer +category: Behavioral +language: ko +tag: +- Gang Of Four +- Reactive +--- + +## 또한 ~으로 알려진 + +Dependents, Publish-Subscribe + +## 의도 + +하나의 개체가 상태를 변경하면 모든 종속 항목에 알림이 전송되고 자동으로 업데이트 되도록 개체간의 일대 다 종속성을 정의합니다. + +## 설명 + +예시 + +> 멀리 떨어진 땅에는 호빗과 오크 종족이 살고 있습니다. 둘 다 대부분 야외에 있으므로 날씨 변화를 면밀히 따릅니다. 끊임없이 날씨를 관찰하고 있다고 말할 수 있습니다. + +평범하게 말하자면 + +> observer로 등록하여 개체의 상태 변경을 수신합니다. + +Wikipedia 말에 의하면 + +> observer 패턴은 주제라고하는 객체가 observer라고 하는 종속 항목 목록을 유지하고 일반적으로 메서드 중 하나를 호출하여 상태 변경을 자동으로 알리는 소프트웨어 디자인 패턴입니다. + +**프로그램 코드 예제** + +먼저 `WeatherObserver` 인터페이스와 우리의 종족 `Orcs` 와 `Hobbits` 소개하겠습니다. + +```java +public interface WeatherObserver { + + void update(WeatherType currentWeather); +} + +public class Orcs implements WeatherObserver { + + private static final Logger LOGGER = LoggerFactory.getLogger(Orcs.class); + + @Override + public void update(WeatherType currentWeather) { + LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now"); + } +} + +public class Hobbits implements WeatherObserver { + + private static final Logger LOGGER = LoggerFactory.getLogger(Hobbits.class); + + @Override + public void update(WeatherType currentWeather) { + switch (currentWeather) { + LOGGER.info("The hobbits are facing " + currentWeather.getDescription() + " weather now"); + } + } +} +``` + +그리고 끊임없이 변화하는 `Weather` 가 있습니다. + +```java +public class Weather { + + private static final Logger LOGGER = LoggerFactory.getLogger(Weather.class); + + private WeatherType currentWeather; + private final List observers; + + public Weather() { + observers = new ArrayList<>(); + currentWeather = WeatherType.SUNNY; + } + + public void addObserver(WeatherObserver obs) { + observers.add(obs); + } + + public void removeObserver(WeatherObserver obs) { + observers.remove(obs); + } + + /** + * Makes time pass for weather. + */ + public void timePasses() { + var enumValues = WeatherType.values(); + currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; + LOGGER.info("The weather changed to {}.", currentWeather); + notifyObservers(); + } + + private void notifyObservers() { + for (var obs : observers) { + obs.update(currentWeather); + } + } +} +``` + +여기에 전체 예제가 있습니다. + +```java + var weather = new Weather(); + weather.addObserver(new Orcs()); + weather.addObserver(new Hobbits()); + weather.timePasses(); + weather.timePasses(); + weather.timePasses(); + weather.timePasses(); +``` + +프로그램 출력 : + +``` +The weather changed to rainy. +The orcs are facing rainy weather now +The hobbits are facing rainy weather now +The weather changed to windy. +The orcs are facing windy weather now +The hobbits are facing windy weather now +The weather changed to cold. +The orcs are facing cold weather now +The hobbits are facing cold weather now +The weather changed to sunny. +The orcs are facing sunny weather now +The hobbits are facing sunny weather now +``` + +## 클래스 다이어그램 + +![alt text](./etc/observer.png) + +## 적용 가능성 + +다음 상황에서 관찰자 패턴을 사용하십시오. + +- 추상화에 두 가지 측면이 있을 때 하나는 다른 하나에 종속됩니다. 이러한 측면을 별도의 개체에 캡슐화하면 독립적으로 변경하고 재사용 할 수 있습니다. +- 한 개체를 변경하려면 얼마나 다른 개체를 변경해야 하는지 알 수 없는 경우입니다. +- 개체가 다른 개체가 누구인지 가정하지 않고 알릴 수 있어야하는 경우. 즉, 개체가 단단히 결합되는 것을 원하지 않습니다. + +## 일반적인 사용 사례 + +- 한 개체를 변경하면 다른 개체도 변경됩니다. + +## 실제 사례 + +- [java.util.Observer](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html) +- [java.util.EventListener](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html) +- [javax.servlet.http.HttpSessionBindingListener](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html) +- [RxJava](https://github.com/ReactiveX/RxJava) + +## 크레딧 + +- [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +- [Java Generics and Collections](https://www.amazon.com/gp/product/0596527756/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596527756&linkCode=as2&tag=javadesignpat-20&linkId=246e5e2c26fe1c3ada6a70b15afcb195) +- [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +- [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/ko/observer/etc/observer.png b/localization/ko/observer/etc/observer.png new file mode 100644 index 000000000000..f2ab0edfeb21 Binary files /dev/null and b/localization/ko/observer/etc/observer.png differ diff --git a/localization/ko/prototype/README.md b/localization/ko/prototype/README.md new file mode 100644 index 000000000000..498ce4c21251 --- /dev/null +++ b/localization/ko/prototype/README.md @@ -0,0 +1,86 @@ +--- +title: Prototype +shortTitle: Prototype +category: Creational +language: ko +tag: +- Gang Of Four +- Instantiation +--- + +## 의도 + +prototype 인스턴스를 사용하여 만들 개체의 종류를 지정하고 prototype을 복사하여 새 개체를 만듭니다. + +## 설명 + +먼저 성능 이점을 얻기 위해 prototype 패턴이 사용되지 않는다는 점에 유의해야합니다. 오직 prototype 인스턴스에서 새 개체를 만드는 데만 사용됩니다. + +예시 + +> 복제된 양인 돌리에 대해 기억나십니까? 자세한 내용은 다루지 않겠습니다만 여기서 핵심은 복제에 관한 것입니다. + +평범한 말하자면 + +> 복제를 통해 기존 개체를 기반으로 개체를 만듭니다. + +Wikipedia 말에 의하면 + +> prototype 패턴은 소프트웨어 개발에서 생성 디자인 패턴입니다. 생성 할 개체의 유형이 새 개체를 생성하기 위해 복제되는 prototype 인스턴스에 의해 결정될 때 사용됩니다. + +간단히 말해, 객체를 처음부터 만들고 설정하는 문제를 겪는 대신 기존 객체의 복사본을 만들어 필요에 맞게 수정할 수 있습니다. + +**프로그램 코드 예제** + +Java에서는 `Cloneable` 을 구현하고 `Object` 에서 `clone` 을 오버라이딩하여 쉽게 수행 할 수 있습니다. + +```java +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() { + try { + return (Sheep)super.clone(); + } catch(CloneNotSuportedException) { + throw new InternalError(); + } + } +} +``` + +그런 다음 아래와 같이 복제할 수 있습니다. + +```java +var original = new Sheep("Jolly"); +System.out.println(original.getName()); // Jolly + +// Clone and modify what is required +var cloned = original.clone(); +cloned.setName("Dolly"); +System.out.println(cloned.getName()); // Dolly +``` + +## 클래스 다이어그램 + +![alt text](./etc/prototype.urm.png) + +## 적용 가능성 + +시스템이 제품의 생성, 구성, 표현 및 표현 방식에 독립적이어야 할 때 prototype 패턴을 사용 + +- 인스턴스화할 클래스가 런타임에 지정되는 경우 (예 : 동적 로딩) +- 제품의 클래스 계층 구조와 유사한 팩토리의 클래스 계층 구조 구축을 방지해야할 경우 +- 클래스의 인스턴스가 몇 가지 다른 상태 조합 중 하나만 가질 수 있는 경우. 적절한 상태로 매번 클래스를 수동으로 인스턴스화하는 것보다 해당하는 수의 prototype을 설치하고 복제하는 것이 더 편리 할 수 있습니다. +- 복제에 비해 개체 생성 비용이 많이 드는 경우. + +## 실제 사례 + +- [java.lang.Object#clone()](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29) + +## 크레딧 + +- [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +- [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/ko/prototype/etc/prototype.urm.png b/localization/ko/prototype/etc/prototype.urm.png new file mode 100644 index 000000000000..b23c6d1cfb85 Binary files /dev/null and b/localization/ko/prototype/etc/prototype.urm.png differ diff --git a/localization/ko/proxy/README.md b/localization/ko/proxy/README.md new file mode 100644 index 000000000000..0b371ac1de00 --- /dev/null +++ b/localization/ko/proxy/README.md @@ -0,0 +1,161 @@ +--- +title: Proxy +shortTitle: Proxy +category: Structural +language: ko +tag: +- Gang Of Four +- Decoupling +--- + +## 또한 ~으로 알려진 + +Surrogate + +## 의도 + +다른 객체에 대한 접근을 제어할 수 있는 대리인 또는 자리 표시자(placeholder)를 제공합니다. + +## 설명 + +실제 예제 + +> 지역 마법사들이 주문을 공부하러 가는 탑을 상상해 보세요. 상아탑은 프록시를 통해서만 접근할 수 있으며, 프록시는 처음 세 명의 마법사만 들어갈 수 있도록 합니다. 여기서 프록시는 타워의 기능을 나타내며 액세스 제어를 추가합니다. + +쉽게 말하자면 + +> 프록시 패턴을 사용하여, 클래스는 다른 클래스의 기능을 나타냅니다. + +Wikipedia에 의하면 + +> 프록시는 가장 일반적인 형태로 다른 것에 대한 인터페이스로서 기능하는 클래스이다. 프록시는 클라이언트가 백그라운드에서 실제 서비스 객체에 액세스하기 위해 호출하는 래퍼 또는 에이전트 객체입니다. 프록시의 사용은 단순히 실제 객체로 포워딩하거나 추가적인 논리를 제공할 수 있습니다. 프록시에서 실제 객체에 대한 작업이 리소스 집약적일 때, 캐싱하거나 실제 객체에 대한 작업이 호출되기 전에 사전 조건을 확인하는 등의 추가 기능이 제공될 수 있습니다. + +**코드 예제** + +위로부터 마법사 타워를 예로 들어보겠습니다. 먼저 `WiszrdTower` 인터페이스와 이를 구현한 +`IvoryTower` 클래스가 있습니다. + +```java +public interface WizardTower { + + void enter(Wizard wizard); +} + +@Slf4j +public class IvoryTower implements WizardTower { + + public void enter(Wizard wizard) { + LOGGER.info("{} enters the tower.", wizard); + } + +} +``` + +그리고 간단한 `Wizard` 클래스입니다. + + +```java +public class Wizard { + + private final String name; + + public Wizard(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} +``` + +그리고 `WizardTower`에 대한 엑세스 통제를 추가하기 위해 `WizardTowerProxy`를 가집니다. + +```java +@Slf4j +public class WizardTowerProxy implements WizardTower { + + private static final int NUM_WIZARDS_ALLOWED = 3; + + private int numWizards; + + private final WizardTower tower; + + public WizardTowerProxy(WizardTower tower) { + this.tower = tower; + } + + @Override + public void enter(Wizard wizard) { + if (numWizards < NUM_WIZARDS_ALLOWED) { + tower.enter(wizard); + numWizards++; + } else { + LOGGER.info("{} is not allowed to enter!", wizard); + } + } +} +``` + +그리고 다음은 타워에 입장하는 시나리오입니다. + +```java +var proxy = new WizardTowerProxy(new IvoryTower()); +proxy.enter(new Wizard("Red wizard")); +proxy.enter(new Wizard("White wizard")); +proxy.enter(new Wizard("Black wizard")); +proxy.enter(new Wizard("Green wizard")); +proxy.enter(new Wizard("Brown wizard")); +``` + +프로그램 실행 결과: + +``` +Red wizard enters the tower. +White wizard enters the tower. +Black wizard enters the tower. +Green wizard is not allowed to enter! +Brown wizard is not allowed to enter! +``` + +## 클래스 다이어그램 + +![alt text](./etc/proxy.urm.png "Proxy pattern class diagram") + +## 적용 가능성 + +프록시는 단순한 포인터보다 더 다재다능하거나 정교한 오브젝트 참조가 필요할 때마다 적용할 수 있습니다. 다음은 프록시 패턴을 적용할 수 있는 몇 가지 일반적인 상황입니다. + + +* 원격 프록시는 다른 주소 공간에 있는 체의 로컬 대리자를 제공합니다. +* 가상 프록시는 요청 시 값비싼 개체를 생성합니다. +* 보호 프록시는 원래 객체에 대한 액세스를 제어합니다. 보호 프록시는 객체가 서로 다른 액세스 권한을 가져야 할 때 유용합니다. + +일반적으로 프록시 패턴은 다음과 같이 사용됩니다. + +* 다른 객체에 대한 액세스 제어 +* 지연 초기화 +* 로깅(logging) 구현 +* 네트워크 연결 촉진 +* 객체에 대한 참조 카운팅 + +## 튜토리얼 + +* [Controlling Access With Proxy Pattern](http://java-design-patterns.com/blog/controlling-access-with-proxy-pattern/) + +## 실제 사례 + +* [java.lang.reflect.Proxy](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html) +* [Apache Commons Proxy](https://commons.apache.org/proper/commons-proxy/) +* Mocking frameworks [Mockito](https://site.mockito.org/), + [Powermock](https://powermock.github.io/), [EasyMock](https://easymock.org/) + +## 관련 패턴 + +* [Ambassador](https://java-design-patterns.com/patterns/ambassador/) + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/ko/proxy/etc/proxy.urm.png b/localization/ko/proxy/etc/proxy.urm.png new file mode 100644 index 000000000000..a0c94fc7c717 Binary files /dev/null and b/localization/ko/proxy/etc/proxy.urm.png differ diff --git a/localization/ko/singleton/README.md b/localization/ko/singleton/README.md new file mode 100644 index 000000000000..2b5c8502a909 --- /dev/null +++ b/localization/ko/singleton/README.md @@ -0,0 +1,83 @@ +--- +title: Singleton +shortTitle: Singleton +category: Creational +language: ko +tag: +- Gang of Four +--- + +## 의도 + +클래스에 인스턴스가 하나만 있는지 확인하고 이에 대한 전역 access point을 제공합니다. + +## 설명 + +예시 + +> 마법사들이 마법을 연구하는 상아탑은 단 하나뿐입니다. 마법사는 항상 동일한 마법의 상아탑을 사용합니다. 여기서 상아탑은 singleton입니다. + +평범하게 말하자면 + +> 특정 클래스의 개체가 하나만 생성되도록합니다. + +Wikipedia 말에 의하면 + +> 소프트웨어 엔지니어링에서 singleton 패턴은 클래스의 인스턴스화를 하나의 객체로 제한하는 소프트웨어 디자인 패턴입니다. 이는 시스템 전체에서 작업을 조정하는 데 정확히 하나의 개체가 필요할 때 유용합니다. + +**프로그램 코드 예제** + +Joshua Bloch, Effective Java 2nd Edition p.18 + +> 단일 요소 열거형은 singleton을 구현하는 가장 좋은 방법입니다. + +```java +public enum EnumIvoryTower { + INSTANCE +} +``` + +그런 다음 사용하려면 : + +```java +var enumIvoryTower1 = EnumIvoryTower.INSTANCE; +var enumIvoryTower2 = EnumIvoryTower.INSTANCE; +assertEquals(enumIvoryTower1, enumIvoryTower2); // true +``` + +## 클래스 다이어그램 + +![alt text](./etc/singleton.urm.png) + +## 적용 가능성 + +다음과 같은 경우 Singleton 패턴을 사용합니다. + +- 정확히 하나의 클래스 인스턴스가 있어야하며 잘 알려진 access point에서 클라이언트에 접근할 수 있어야합니다. +- 단일 인스턴스가 서브 클래싱으로 확장 가능해야하고 클라이언트가 코드를 수정하지 않고 확장 인스턴스를 사용할 수 있어야 하는 경우 + +## 일반적인 사용 사례 + +- 로깅 클래스 +- 데이터베이스에 대한 연결 관리 +- 파일 관리자 + +## 실제 사례 + +- [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29) +- [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--) +- [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--) + +## 결과 + +- 자체 생성 및 수명주기를 제어하여 SRP (Single Responsibility Principle)를 위반합니다. +- 이 개체가 사용하는 개체와 리소스가 할당 해제되는 것을 방지하는 전역 공유 인스턴스를 사용하도록 권장합니다. +- 밀접하게 연결된 코드를 만듭니다. Singleton의 클라이언트는 테스트하기가 어려워집니다. +- Singleton의 하위 클래스를 만드는 것이 거의 불가능합니다. + +## 크레딧 + +- [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +- [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +- [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +- [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/ko/singleton/etc/singleton.urm.png b/localization/ko/singleton/etc/singleton.urm.png new file mode 100644 index 000000000000..46584af40039 Binary files /dev/null and b/localization/ko/singleton/etc/singleton.urm.png differ diff --git a/localization/ko/strategy/README.md b/localization/ko/strategy/README.md new file mode 100644 index 000000000000..f604962d1f6b --- /dev/null +++ b/localization/ko/strategy/README.md @@ -0,0 +1,184 @@ +--- +title: Strategy +shortTitle: Strategy +category: Behavioral +language: ko +tag: + - Gang of Four +--- + +## 동의어 + +정책(Policy) 패턴 + +## 의도 + +알고리즘군을 정의하고 각 알고리즘을 캡슐화하고 상호 변경 가능하게 만듭니다. 전략(Strategy) 패턴을 사용하면 알고리즘이 이를 사용하는 클라이언트와 독립적일 수 있습니다. + +## 설명 + +실제 예제 + +> 드래곤을 사냥하는 것은 위험한 일입니다. 경험이 쌓이면 쉬워집니다. 베테랑 사냥꾼들은 서로 다른 유형의 드래곤에 대해 서로 다른 전투 전략을 개발했습니다. + +평범한 말로는 + +> 전략(Strategy) 패턴을 사용하면 런타임에 가장 적합한 알고리즘을 선택할 수 있습니다. + +Wikipedia는 + +> 컴퓨터 프로그래밍에서 전략 패턴(정책 패턴이라고도 함)은 런타임에 알고리즘을 선택할 수 있는 행동 소프트웨어 디자인 패턴입니다. + +**프로그래밍 예** + +먼저 드래곤 사냥 전략 인터페이스와 그 구현을 살펴봅니다. + +```java +@FunctionalInterface +public interface DragonSlayingStrategy { + + void execute(); +} + +@Slf4j +public class MeleeStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("With your Excalibur you sever the dragon's head!"); + } +} + +@Slf4j +public class ProjectileStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!"); + } +} + +@Slf4j +public class SpellStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"); + } +} +``` + +그리고 여기 상대하는 드래곤에 따라 자신의 전투 전략을 선택할 수 있는 강력한 드래곤 슬레이어가 있습니다. + +```java +public class DragonSlayer { + + private DragonSlayingStrategy strategy; + + public DragonSlayer(DragonSlayingStrategy strategy) { + this.strategy = strategy; + } + + public void changeStrategy(DragonSlayingStrategy strategy) { + this.strategy = strategy; + } + + public void goToBattle() { + strategy.execute(); + } +} +``` + +마지막으로 여기 드래곤 슬레이어가 행동합니다. + +```java + LOGGER.info("Green dragon spotted ahead!"); + var dragonSlayer = new DragonSlayer(new MeleeStrategy()); + dragonSlayer.goToBattle(); + LOGGER.info("Red dragon emerges."); + dragonSlayer.changeStrategy(new ProjectileStrategy()); + dragonSlayer.goToBattle(); + LOGGER.info("Black dragon lands before you."); + dragonSlayer.changeStrategy(new SpellStrategy()); + dragonSlayer.goToBattle(); +``` + +프로그램 출력: + +``` + Green dragon spotted ahead! + With your Excalibur you sever the dragon's head! + Red dragon emerges. + You shoot the dragon with the magical crossbow and it falls dead on the ground! + Black dragon lands before you. + You cast the spell of disintegration and the dragon vaporizes in a pile of dust! +``` + +또한 Java 8의 새로운 기능인 Lambda Expressions은 구현을 위한 또 다른 접근 방식을 제공합니다: + +```java +public class LambdaStrategy { + + private static final Logger LOGGER = LoggerFactory.getLogger(LambdaStrategy.class); + + public enum Strategy implements DragonSlayingStrategy { + MeleeStrategy(() -> LOGGER.info( + "With your Excalibur you sever the dragon's head!")), + ProjectileStrategy(() -> LOGGER.info( + "You shoot the dragon with the magical crossbow and it falls dead on the ground!")), + SpellStrategy(() -> LOGGER.info( + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); + + private final DragonSlayingStrategy dragonSlayingStrategy; + + Strategy(DragonSlayingStrategy dragonSlayingStrategy) { + this.dragonSlayingStrategy = dragonSlayingStrategy; + } + + @Override + public void execute() { + dragonSlayingStrategy.execute(); + } + } +} +``` + +그리고 여기 드래곤 슬레이어가 행동합니다. + +```java + LOGGER.info("Green dragon spotted ahead!"); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy); + dragonSlayer.goToBattle(); + LOGGER.info("Red dragon emerges."); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy); + dragonSlayer.goToBattle(); + LOGGER.info("Black dragon lands before you."); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy); + dragonSlayer.goToBattle(); +``` + +프로그램 출력은 위와 동일합니다. + +## 클래스 다이어그램 + +![alt text](./etc/strategy_urm.png "Strategy") + +## 적용 가능성 + +다음과 같은 경우 전략(Strategy) 패턴을 사용합니다. + +* 비슷한 클래스들이 동작 만 다른 경우가 많이 있습니다. 전략 패턴은 여러 동작 중 하나를 클래스로 구성하는 방법을 제공합니다. +* 알고리즘의 다양한 변형이 필요합니다. 예를 들어 다양한 공간 / 시간 절충을 반영하는 알고리즘을 정의할 수 있습니다. 이러한 변형이 알고리즘의 클래스 계층 구조로 구현될 때 전략 패턴을 사용할 수 있습니다. +* 알고리즘은 클라이언트가 알 필요 없는 데이터를 사용합니다. 전략 패턴을 사용하여 복잡한 알고리즘 별 데이터 구조가 노출되지 않도록 합니다. +* 클래스는 많은 동작을 정의하며 이러한 동작은 작업에서 여러 조건문으로 나타납니다. 많은 조건부 대신 관련 조건부 분기를 자체 전략 클래스로 이동하세요. + +## 튜토리얼 + +* [전략 패턴 튜토리얼](https://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorial) + +## 크레딧 + +* [디자인 패턴: 재사용 가능한 객체 지향 소프트웨어의 요소](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [자바의 함수형 프로그래밍: Java 8 Lambda 표현식의 강력한 기능 활용](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) +* [헤드 퍼스트 디자인 패턴: 두뇌 친화적인 가이드](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [패턴으로 리팩토링](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/ko/strategy/etc/strategy_urm.png b/localization/ko/strategy/etc/strategy_urm.png new file mode 100644 index 000000000000..67d19acae62d Binary files /dev/null and b/localization/ko/strategy/etc/strategy_urm.png differ diff --git a/localization/ko/template-method/README.md b/localization/ko/template-method/README.md new file mode 100644 index 000000000000..d2dbde0a0656 --- /dev/null +++ b/localization/ko/template-method/README.md @@ -0,0 +1,146 @@ +--- +title: Template Method +shortTitle: Template Method +category: Behavioral +language: ko +tag: +- Gang of Four +--- + +## 의도 + +동작 상의 알고리즘의 뼈대를 정의하고 일부 단계들을 하위 클래스에게 미룹니다. 템플릿 메소드는 알고리즘 구조의 변경없이 하위 클래스들이 알고리즘의 특정 단계들을 재정의할 수 있게 합니다. + +## 설명 + +실제 예제 + +> 일반적으로 물건을 훔치는 절차는 동일합니다. 첫번째 단계로 대상을 고릅니다. 다음 단계로 대상을 어느정도 혼란스럽게 만듭니다. 마지막 단계로 물건을 훔칩니다. 하지만, 이 단계를 실행하는 구체적인 방법에는 여러가지가 있습니다. + +쉽게 말하자면 + +> 템플릿 메소드 패턴은 일반적인 단계의 아웃라인을 부모 클래스에 제시합니다. 그리고 구체적인 자식 클래스의 구현으로 디테일한 사항들을 정의합니다. + +Wikipedia에 의하면 + +> 객체지향 프로그래밍에서, 템플릿 메소드는 디자인 패턴 책에서 감마를 포함한 책의 저자들이 확인한 행동 디자인 패턴 중 하나입니다. 템플릿 메소드는 보통 추상 수퍼클래스인 수퍼클래스에서의 메소드이며 수많은 high-level 단계들의 관점에서 동작의 뼈대를 정의합니다. 이러한 절차들은 템플릿 메소드와 동일한 클래스의 추가적인 헬퍼 메소드들에 의해 구현됩니다. + +**코드 예제** + +먼저 구체적인 구현과 함께 템플릿 방법 클래스를 소개합니다. 하위클래스들이 템플릿 메소드를 재정의하지 않는 것을 확실히 하기위해 템플릿 메소드(예제에서는 메소드명`steal`)는 `final`로 선언해야 합니다. 그렇지 않으면 기본 클래스에 정의된 뼈대는 하위 클래스에서 재정의될 수 있습니다. + + +```java +@Slf4j +public abstract class StealingMethod { + + protected abstract String pickTarget(); + + protected abstract void confuseTarget(String target); + + protected abstract void stealTheItem(String target); + + public final void steal() { + var target = pickTarget(); + LOGGER.info("The target has been chosen as {}.", target); + confuseTarget(target); + stealTheItem(target); + } +} + +@Slf4j +public class SubtleMethod extends StealingMethod { + + @Override + protected String pickTarget() { + return "shop keeper"; + } + + @Override + protected void confuseTarget(String target) { + LOGGER.info("Approach the {} with tears running and hug him!", target); + } + + @Override + protected void stealTheItem(String target) { + LOGGER.info("While in close contact grab the {}'s wallet.", target); + } +} + +@Slf4j +public class HitAndRunMethod extends StealingMethod { + + @Override + protected String pickTarget() { + return "old goblin woman"; + } + + @Override + protected void confuseTarget(String target) { + LOGGER.info("Approach the {} from behind.", target); + } + + @Override + protected void stealTheItem(String target) { + LOGGER.info("Grab the handbag and run away fast!"); + } +} +``` + +템플릿 메소드를 담고 있는 반쪽짜리 도적 클래스입니다. + +```java +public class HalflingThief { + + private StealingMethod method; + + public HalflingThief(StealingMethod method) { + this.method = method; + } + + public void steal() { + method.steal(); + } + + public void changeMethod(StealingMethod method) { + this.method = method; + } +} +``` + +그리고 마지막으로, 반쪽짜리 도둑이 다른 도둑질 방법을 어떻게 활용하는지 보여줍니다. + +```java + var thief = new HalflingThief(new HitAndRunMethod()); + thief.steal(); + thief.changeMethod(new SubtleMethod()); + thief.steal(); +``` + +## 클래스 다이어그램 + +![alt text](./etc/template_method_urm.png "Template Method") + +## 적용 가능성 + +템플릿 메소드는 사용되어야합니다. + +* 알고리즘의 변하지않는 부분을 한번만 구현하고, 다양할 수 있는 행위의 구현을 서브클래스에게 맡기기 위해 +* 중복되는 코드를 피하기위해 서브클래스들 사이의 공통적인 행위를 공통 클래스에서 고려하고 현지화해야 하는 경우. 이것은 Opdyke 와 Johonson이 묘사한 "일반화하기 위한 수정"의 좋은 예입니다. 먼저 기존 코드들 간의 차이를 확인한 다음 새로운 동작으로 구분합니다. 마지막으로, 다른 코드들을 새로운 동작중 하나를 호출하는 템플릿 메소드로 대체합니다. +* 서브클래스들의 확장을 컨트롤하기 위해. 특정 지점에서 "훅" 작업을 호출하여 해당 지점에서만 확장을 허용하는 템플릿 메서드를 정의할 수 있습니다. + +## 튜토리얼 + +* [Template-method Pattern Tutorial](https://www.journaldev.com/1763/template-method-design-pattern-in-java) + +## 실제 사례 + +* [javax.servlet.GenericServlet.init](https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/GenericServlet.html#init--): + Method `GenericServlet.init(ServletConfig config)` calls the parameterless method `GenericServlet.init()` which is intended to be overridden in subclasses. + Method `GenericServlet.init(ServletConfig config)` is the template method in this example. + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/ko/template-method/etc/template_method_urm.png b/localization/ko/template-method/etc/template_method_urm.png new file mode 100644 index 000000000000..b7babccff96d Binary files /dev/null and b/localization/ko/template-method/etc/template_method_urm.png differ diff --git a/localization/ko/visitor/README.md b/localization/ko/visitor/README.md new file mode 100644 index 000000000000..6b8408c3ff41 --- /dev/null +++ b/localization/ko/visitor/README.md @@ -0,0 +1,231 @@ +--- +title: Visitor +shortTitle: Visitor +category: Behavioral +language: ko +tag: + - Gang of Four +--- + +## 의도 + + +객체 구조의 요소들에 대해 수행할 작업을 나타냅니다. 방문자(Visitor)는 +연산하는 요소의 클래스를 변경하지 않고 새 연산을 정의할 수 있게 해줍니다. +## 설명 + +살제 예제 + +> 육군 부대의 편성을 생각해보세요. 지휘관은 아래에 2명의 중사를 휘하에 두고 있고 각 중사들은 +> 3명의 병사를 휘하에 두고 있습니다. 위계에 따라 방문자(Visitor) 패턴이 구현되는 것을 함께 생각하면, +> 우리는 지휘관, 중사 병사 또는 그들 모두와 상호작용하는 새로운 게체를 쉽게 만들 수 있습니다. + +쉽게 말하자면 + +> 방문자(Visitor) 패턴은 데이터 구조의 노드에서 수행할 수 있는 작업들을 정의합니다. + +Wikipedia에 의하면 + +> 객체 지향 프로그래밍 및 소프트웨어 엔지니어링에에서, 방문자(Visitor) 패턴은 +> 알고리즘이 동작하는 객체 구조로부터 알고리즘을 분리하는 것, +> 이 분리를 통해, 구조의 변경 없이 기본 객체 구조에 새로운 연산을 추가할 수 있도록 하는 방법입니다. + +**코드 예제** + +위의 육군 부대를 예로 들겠습니다. 먼저 `Unit` 추상화 클래스와 `UnitVisitor` 인터페이스가 있습니다. + +```java +public abstract class Unit { + + private final Unit[] children; + + public Unit(Unit... children) { + this.children = children; + } + + public void accept(UnitVisitor visitor) { + Arrays.stream(children).forEach(child -> child.accept(visitor)); + } +} + +public interface UnitVisitor { + + void visit(Soldier soldier); + + void visit(Sergeant sergeant); + + void visit(Commander commander); +} +``` + +그리고 이를 구현한 `Commander`,`Sergant`,`Soilder` 구현 클래스입니다. + +```java +public class Commander extends Unit { + + public Commander(Unit... children) { + super(children); + } + + @Override + public void accept(UnitVisitor visitor) { + visitor.visit(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "commander"; + } +} + +public class Sergeant extends Unit { + + public Sergeant(Unit... children) { + super(children); + } + + @Override + public void accept(UnitVisitor visitor) { + visitor.visit(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "sergeant"; + } +} + +public class Soldier extends Unit { + + public Soldier(Unit... children) { + super(children); + } + + @Override + public void accept(UnitVisitor visitor) { + visitor.visit(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "soldier"; + } +} +``` + +그리고 `UnitVisiotr`를 구현한 `CommanderVisitor`,`SergantVisitor`,`Soilder` 구현 클래스입니다. + +```java +@Slf4j +public class CommanderVisitor implements UnitVisitor { + + @Override + public void visit(Soldier soldier) { + // Do nothing + } + + @Override + public void visit(Sergeant sergeant) { + // Do nothing + } + + @Override + public void visit(Commander commander) { + LOGGER.info("Good to see you {}", commander); + } +} + +@Slf4j +public class SergeantVisitor implements UnitVisitor { + + @Override + public void visit(Soldier soldier) { + // Do nothing + } + + @Override + public void visit(Sergeant sergeant) { + LOGGER.info("Hello {}", sergeant); + } + + @Override + public void visit(Commander commander) { + // Do nothing + } +} + +@Slf4j +public class SoldierVisitor implements UnitVisitor { + + @Override + public void visit(Soldier soldier) { + LOGGER.info("Greetings {}", soldier); + } + + @Override + public void visit(Sergeant sergeant) { + // Do nothing + } + + @Override + public void visit(Commander commander) { + // Do nothing + } +} +``` + +마지막으로, 우린 방문자(Visitor)의 위력을 볼 수 있습니다. + +```java +commander.accept(new SoldierVisitor()); +commander.accept(new SergeantVisitor()); +commander.accept(new CommanderVisitor()); +``` + +프로그램 실행 결과: + +``` +Greetings soldier +Greetings soldier +Greetings soldier +Greetings soldier +Greetings soldier +Greetings soldier +Hello sergeant +Hello sergeant +Good to see you commander +``` + +## 클래스 다이어그램 + +![alt text](./etc/visitor_1.png "Visitor") + +## 적용 가능성 + +일반적으로 방문자(Visitor) 패턴은 다음과 같은 상황에 사용할 수 있습니다. + +* 객체 구조에 다양한 인터페이스를 가진 객체의 클래스가 많이 포함되어 있고, 객체들의 구현 클래스에 따라 연산되게 하고 싶을 때 사용할 수 있습니다. +* 객체 구조에 있는 객체들에 대해 개별적이고 서로 연관이 없는 연산들을 수행하고 싶을 때, 이러한 연산들로 인해 클래스가 "오염(Polluting)"되는 것을 방지하고자 합니다. 이럴 때, 방문자(Visitor)를 사용해 관련 연산을 하나의 클래스에 정의하여 유지할 수 있습니다. 객체 구조가 여러 응용 프로그램에서 공유되는 경우에는 방문자(Visitor)를 사용해 필요한 응용 프로그램에만 연산을 추가할 수 있습니다. +* 객체 구조를 정의하는 클래스들은 거의 변경되지 않지만, 종종 새로운 연산을 정의해야 할 때가 있습니다. 객체 구조 클래스들을 변경하려면 모둔 방문자(Visitor)에 데한 인터페이스를 재정의해야 하므로 비용이 많이 들수 있습니다. 객체 구조 클래스가 자주 변경되는 경우 해당 클래스의 연산을 정의하는 것이 더 나을 수 있습니다. + +## 튜토리얼 + +* [Refactoring Guru](https://refactoring.guru/design-patterns/visitor) +* [Dzone](https://dzone.com/articles/design-patterns-visitor) +* [Sourcemaking](https://sourcemaking.com/design_patterns/visitor) + +## 실제 사례 + +* [Apache Wicket](https://github.com/apache/wicket) 구성 요소, [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java)를 참조하세요. +* [javax.lang.model.element.AnnotationValue](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/AnnotationValue.html) 그리고 [AnnotationValueVisitor](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/AnnotationValueVisitor.html) +* [javax.lang.model.element.Element](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/Element.html) 그리고 [Element Visitor](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/ElementVisitor.html) +* [java.nio.file.FileVisitor](http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileVisitor.html) + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/ko/visitor/etc/visitor_1.png b/localization/ko/visitor/etc/visitor_1.png new file mode 100644 index 000000000000..de5285d7fdc3 Binary files /dev/null and b/localization/ko/visitor/etc/visitor_1.png differ diff --git a/localization/mr/README.md b/localization/mr/README.md new file mode 100644 index 000000000000..d705d42dc8f7 --- /dev/null +++ b/localization/mr/README.md @@ -0,0 +1,69 @@ + + + # जावा मध्ये डिझाइन नमुने लागू केले + + ![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-214-orange.svg?style=flat-square)](#contributors-) + + +
    + +Read in different language : [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md), [**vi**](localization/vi/README.md), [**ma**](localization/ma/README.md) + +
    + +#परिचय + +डिझाईन पॅटर्न हे प्रोग्रामर वापरू शकणार्‍या सर्वोत्तम, औपचारिक पद्धती आहेत +अनुप्रयोग किंवा सिस्टम डिझाइन करताना सामान्य समस्या सोडवा. + +डिझाइन नमुने चाचणी केलेले, सिद्ध करून विकास प्रक्रियेस गती देऊ शकतात +विकास नमुना. + +डिझाईन नमुन्यांचा पुनर्वापर केल्याने प्रमुख कारणीभूत असलेल्या सूक्ष्म समस्या टाळण्यास मदत होते +समस्या, आणि ते कोडर आणि आर्किटेक्टसाठी कोड वाचनीयता देखील सुधारते +नमुन्यांशी परिचित आहेत. + +#सुरुवात + +ही साइट Java डिझाइन पॅटर्न दाखवते. द्वारे उपाय विकसित केले गेले आहेत +ओपन-सोर्स समुदायातील अनुभवी प्रोग्रामर आणि आर्किटेक्ट. द +नमुने त्यांच्या उच्च-स्तरीय वर्णनांद्वारे किंवा त्यांच्याकडे पाहून ब्राउझ केले जाऊ शकतात +मूळ सांकेतिक शब्दकोश. स्त्रोत कोड उदाहरणे चांगल्या प्रकारे टिप्पणी केली आहेत आणि म्हणून विचार केला जाऊ शकतो +विशिष्ट पॅटर्न कसे अंमलात आणायचे यावरील प्रोग्रामिंग ट्यूटोरियल. आम्ही सर्वात जास्त वापरतो +लोकप्रिय युद्ध-सिद्ध ओपन-सोर्स जावा तंत्रज्ञान. + +आपण सामग्रीमध्ये जाण्यापूर्वी, आपल्याला विविध गोष्टींशी परिचित असले पाहिजे [सॉफ्टवेअर डिझाइन तत्त्वे](https://java-design-patterns.com/principles/). + +सर्व रचना शक्य तितक्या सोप्या असाव्यात. तुम्ही KISS, YAGNI ने सुरुवात करावी, +आणि शक्यतो तत्त्वे कार्य करू शकणारी सर्वात सोपी गोष्ट करा. जटिलता आणि +नमुने केवळ तेव्हाच सादर केले जावे जेव्हा ते प्रॅक्टिकलसाठी आवश्यक असतील +विस्तारक्षमता + +एकदा आपण या संकल्पनांशी परिचित झाल्यानंतर आपण मध्ये ड्रिल करणे सुरू करू शकता +[उपलब्ध डिझाइन नमुने](https://java-design-patterns.com/patterns/) कोणत्याही +खालील दृष्टिकोनांपैकी + + - नावाने विशिष्ट नमुना शोधा. एक शोधू शकत नाही? कृपया नवीन नमुना [येथे] (https://github.com/iluwatar/java-design-patterns/issues) नोंदवा. + - `परफॉर्मन्स`, `गँग ऑफ फोर` किंवा `डेटा ऍक्सेस` यासारखे टॅग वापरणे. + - पॅटर्न श्रेण्या, `सृजनात्मक`, `वर्तणूक` आणि इतर वापरणे. + +आशा आहे की, तुम्हाला या साइटवर सादर केलेले ऑब्जेक्ट-ओरिएंटेड उपाय उपयुक्त वाटतील +तुमच्या आर्किटेक्चर्समध्ये आणि त्यांना विकसित करताना आम्हाला जेवढी मजा आली तेवढीच ती शिकण्यात मजा करा. +# योगदान कसे द्यावे + +तुम्ही प्रकल्पात योगदान देण्यास इच्छुक असाल तर तुम्हाला संबंधित माहिती मिळेल +आमचे [डेव्हलपर विकी](https://github.com/iluwatar/java-design-patterns/wiki). आम्ही मदत करू +तुम्ही आणि तुमच्या प्रश्नांची उत्तरे [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns) मध्ये द्या. + +# परवाना + +हा प्रकल्प एमआयटी परवान्याच्या अटींनुसार परवानाकृत आहे. + diff --git a/localization/ne/README.md b/localization/ne/README.md new file mode 100644 index 000000000000..7bf47074b14a --- /dev/null +++ b/localization/ne/README.md @@ -0,0 +1,64 @@ + + +# जाभामा लागू गरिएको डिजाइन ढाँचाहरू + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-218-orange.svg?style=flat-square)](#contributors-) + + +
    + +फरक भाषामा पढ्नुहोस् : [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md), [**de**](localization/de/README.md), [**ja**](localization/ja/README.md), [**vi**](localization/vi/README.md), [**bn**](localization/bn/README.md), [**np**](localization/np/README.md) +
    + +# परिचय + +डिजाइन ढाँचाहरू सबै भन्दा राम्रो, औपचारिक अभ्यासहरू हुन् जुन प्रोग्रामरले अनुप्रयोग वा प्रणाली डिजाइन गर्दा सामान्य समस्याहरू समाधान गर्न प्रयोग गर्न सक्छ। + +डिजाइन ढाँचाहरूले परीक्षण, प्रमाणित विकास प्रतिमानहरू प्रदान गरेर विकास प्रक्रियालाई गति दिन सक्छ। + +डिजाइन ढाँचाहरू पुन: प्रयोग गर्नाले प्रमुख समस्याहरू निम्त्याउने सूक्ष्म समस्याहरूलाई रोक्न मद्दत गर्दछ, र यसले ढाँचाहरूसँग परिचित भएका कोडरहरू र आर्किटेक्टहरूको लागि कोड पढ्न योग्यतामा पनि सुधार गर्दछ। + +# सुरु गर्दै + +यो साइटले जाभा डिजाइन ढाँचाहरू प्रदर्शन गर्दछ। समाधानहरू द्वारा विकसित गरिएको छ +खुला स्रोत समुदायबाट अनुभवी प्रोग्रामरहरू र आर्किटेक्टहरू। द +ढाँचाहरू तिनीहरूको उच्च-स्तरको विवरणहरू वा हेरेर ब्राउज गर्न सकिन्छ +स्रोत कोड। स्रोत कोड उदाहरणहरू राम्ररी टिप्पणी गरिएका छन् र सोच्न सकिन्छ +एक विशिष्ट ढाँचा कसरी कार्यान्वयन गर्ने बारे प्रोग्रामिङ ट्यूटोरियल। हामी सबैभन्दा बढी प्रयोग गर्छौं +लोकप्रिय युद्ध सिद्ध खुला स्रोत जाभा प्रविधिहरू। + +तपाईंले सामग्रीमा डुब्नु अघि, तपाईं विभिन्नसँग परिचित हुनुपर्छ +[सफ्टवेयर डिजाइन सिद्धान्तहरू](https://java-design-patterns.com/principles/). + +सबै डिजाइनहरू सकेसम्म सरल हुनुपर्छ। चुम्बन, यज्ञीबाट सुरु गर्नुपर्छ, +र सम्भवतः सिद्धान्तहरू काम गर्न सक्ने साधारण कुरा गर्नुहोस्। जटिलता र +ढाँचाहरू मात्र पेश गर्नुपर्छ जब तिनीहरू व्यावहारिक रूपमा आवश्यक हुन्छन् +विस्तारशीलता। + +एकचोटि तपाइँ यी अवधारणाहरूसँग परिचित भएपछि तपाइँ मा ड्रिल गर्न सुरु गर्न सक्नुहुन्छ +[उपलब्ध डिजाइन ढाँचा](https://java-design-patterns.com/patterns/) कुनै पनि द्वारा +निम्न दृष्टिकोणहरु को + +- नाम द्वारा एक विशिष्ट ढाँचा खोज्नुहोस्। एउटा भेट्टाउन सक्नुहुन्न? कृपया एउटा नयाँ ढाँचा रिपोर्ट गर्नुहोस् [यहाँ](https://github.com/iluwatar/java-design-patterns/issues). +- `प्रदर्शन`, `Gang of Four`, वा `डेटा पहुँच` जस्ता ट्यागहरू प्रयोग गर्दै। +- ढाँचा कोटिहरू प्रयोग गर्दै, `सृजनात्मक`, `व्यवहार`, र अन्य। + +आशा छ, तपाईंले यस साइटमा प्रस्तुत वस्तु-उन्मुख समाधानहरू उपयोगी पाउनुहुनेछ +तपाईंको आर्किटेक्चरमा र तिनीहरूलाई सिक्न धेरै रमाईलो गर्नुहोस् हामीले तिनीहरूलाई विकास गर्दा। + +# कसरी योगदान गर्ने +यदि तपाईं परियोजनामा ​​योगदान गर्न इच्छुक हुनुहुन्छ भने तपाईंले सान्दर्भिक जानकारी पाउनुहुनेछ +हाम्रो [विकासकर्ता विकि](https://github.com/iluwatar/java-design-patterns/wiki). हामी मद्दत गर्नेछौं +तपाईं र [गिटर च्याटरूम](https://gitter.im/iluwatar/java-design-patterns) मा तपाईंका प्रश्नहरूको जवाफ दिनुहोस्। + +# इजाजतपत्र +यो परियोजना MIT लाइसेन्स को सर्तहरु अन्तर्गत इजाजतपत्र दिइएको छ। + diff --git a/localization/pt/README.md b/localization/pt/README.md new file mode 100644 index 000000000000..93c5f9750b3b --- /dev/null +++ b/localization/pt/README.md @@ -0,0 +1,66 @@ + + +# Padrões de projeto implementados em Java + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-170-orange.svg?style=flat-square)](#contributors-) + +
    + +Leia em outro idioma: [**zh**](/localization/zh/README.md), [**ko**](/localization/ko/README.md), [**fr**](/localization/fr/README.md), [**tr**](/localization/tr/README.md), [**ar**](/localization/ar/README.md), [**es**](/localization/es/README.md) + +
    + +# Introdução + +Os padrões de projeto são um conjunto das melhores práticas e soluções formalizadas que um programador pode usar para resolver problemas comuns ao projetar um aplicativo ou sistema. + +Os padrões de projeto podem acelerar o processo de desenvolvimento, fornecendo testes e comprovados paradigmas de desenvolvimento. + +Reutilizar padrões de projeto ajuda a evitar problemas sutis que causam +problemas, e também melhora a legibilidade do código para desenvolvedores e arquitetos que +estão familiarizados com os padrões. + +# Começando + +Este site apresenta padrões de projeto Java. As soluções foram desenvolvidas por +programadores e arquitetos experientes da comunidade de código aberto. Os +padrões podem ser acessados por meio de suas descrições de alto nível ou por meio de seu +Código fonte. Os exemplos de código-fonte são bem comentados e podem ser considerados como +tutoriais de programação sobre como implementar um padrão específico. Nós usamos as mais +populares tecnologias Java de código aberto comprovadas em batalhas. + +Antes de mergulhar no material, você deve estar familiarizado com vários +[Princípios de design de software](https://java-design-patterns.com/principles/). + +Todos os projetos devem ser o mais simples possível. Você deve começar com KISS, YAGNI, +e fazer a coisa mais simples que poderia funcionar com os princípios. Complexidade e +os padrões só devem ser introduzidos quando são necessários para fins práticos e +extensibilidade. + +Assim que estiver familiarizado com esses conceitos, você pode começar a se aprofundar nos +[padrões de projeto disponíveis](https://java-design-patterns.com/patterns/) por qualquer +das seguintes abordagens + + - Pesquise um padrão específico por nome. Não consegue encontrar um? Informe um novo padrão [aqui](https://github.com/iluwatar/java-design-patterns/issues). + - Usando tags como `Performance`,` Gang of Four` ou `Acesso de dados`. + - Usando categorias de padrões, `Criacional`,` Comportamental` e outros. + + Esperamos que você encontre as soluções orientadas a objetos apresentadas neste site úteis +em suas arquiteturas e divirta-se as aprendendo tanto quanto nos divertimos ao desenvolvê-las. + +# Como contribuir + +Se você estiver disposto a contribuir para o projeto, você encontrará as informações mais relevantes em nossa [wiki do desenvolvedor](https://github.com/iluwatar/java-design-patterns/wiki). Ajudaremos você e responderemos as suas perguntas na [sala de bate-papo do Gitter](https://gitter.im/iluwatar/java-design-patterns). + +# Licença + +Este projeto está licenciado sob os termos da licença MIT. + diff --git a/localization/pt/abstract-factory/README.md b/localization/pt/abstract-factory/README.md new file mode 100644 index 000000000000..f2da58ba4b29 --- /dev/null +++ b/localization/pt/abstract-factory/README.md @@ -0,0 +1,229 @@ +--- +title: Abstract Factory +categories: Creational +language: pt +tag: +- Gang of Four +--- + +## Também conhecido como + +Kit + +## Propósito + +Fornece uma interface para criar famílias de objetos relacionados dependentes sem especificar sua classe concreta. + +## Explicação + +Exemplo do Mundo Real + +> Para criar um reino precisamos de objetos com um tema comum. O reino élfico precisa de um rei élfico, um castelo élfico e um exército élfico, enquanto o reino orc precisa de um rei orc, um castelo orc e um exército orc. Existe uma dependência entre os objetos do reino. + +Em outras palavras + +> Uma fábrica de fábricas; uma fábrica que agrupa outras fábricas individuais, mas relacionadas/dependentes, sem especificar sua classe concreta. + +De acordo com a Wikipédia + +> A essência do padrão Abstract Factory é fornecer uma interface para criar famílias de objetos relacionados ou dependentes sem especificar suas classes concretas. + +**Exemplo Programático** + +Traduzindo o exemplo do reino acima. Em primeiro lugar, temos algumas interfaces e implementação para os objetos no reino. + +```java +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 -> ... + +``` + +Em seguida, temos a abstração e as implementações para a fábrica do reino. + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +Agora temos a fábrica abstrata que nos permite fazer uma família de objetos relacionados, ou seja, a fábrica do reino élfico cria castelo élfico, rei e exército, etc. + + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +Output do programa: + +```java +This is the elven castle! +This is the elven king! +This is the elven Army! +``` + + +Agora, podemos projetar uma fábrica para nossas diferentes fábricas do reino. Neste exemplo, criamos o `FactoryMaker`, responsável por devolver uma instância de `ElfKingdomFactory` ou `OrcKingdomFactory`. +O cliente pode usar o `FactoryMaker` para criar uma fatoração concreta, que uma vez, produzirá diferentes objetos concretos (derivados de `Army`, `King`, `Castle`). +Neste exemplo, também usamos um enum para parametrizar qual tipo de fábrica do reino o cliente solicitará. + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + default -> throw new IllegalArgumentException("KingdomType not supported."); + }; + } +} + + public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + --similar use of the orc factory + } +``` + +## Diagrama de classes + +![alt text](../../../abstract-factory/etc/abstract-factory.urm.png "Diagrama de Classes de Abstract Factory") + + +## Aplicabilidade + +Use o padrão Abstract Factory quando + +* O sistema deve ser independente de como seus produtos são criados, compostos e representados +* O sistema deve ser configurado com uma das várias famílias de produtos +* A família de objetos de produtos relacionados foi projetada para ser usada em conjunto e você precisa aplicar essa restrição +* Você deseja fornecer uma biblioteca de classes de produtos e deseja revelar apenas suas interfaces, não suas implementações +* O tempo de vida da dependência é conceitualmente menor que o tempo de vida do consumidor. +* Você precisa de um valor em tempo de execução para construir uma dependência específica +* Você deseja decidir qual produto chamar de uma família em tempo de execução. +* Você precisa fornecer um ou mais parâmetros conhecidos apenas em tempo de execução antes de resolver uma dependência. +* Quando você precisa de consistência entre os produtos +* Você não deseja alterar o código existente ao adicionar novos produtos ou famílias de produtos ao programa. + +Exemplos de casos de uso + +* Selecionando para chamar a implementação apropriada de FileSystemAcmeService ou DatabaseAcmeService ou NetworkAcmeService em tempo de execução. +* A escrita de casos de teste de unidade torna-se muito mais fácil +* Ferramentas de interface do usuário para diferentes sistemas operacionais + +## Consequencias + +* A injeção de dependência em java oculta as dependências da classe de serviço que podem levar a erros de tempo de execução que seriam detectados em tempo de compilação. +* Embora o padrão seja ótimo ao criar objetos predefinidos, adicionar novos pode ser um desafio. +* O código se torna mais complicado do que deveria, pois muitas novas interfaces e classes são introduzidas junto com o padrão. + +## Tutoriais + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## Usos conhecidos + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## Padrões relacionados + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/pt/adapter/README.md b/localization/pt/adapter/README.md new file mode 100644 index 000000000000..ccc251525c88 --- /dev/null +++ b/localization/pt/adapter/README.md @@ -0,0 +1,136 @@ +--- +title: Adapter +category: Structural +language: pt +tag: + - Gang of Four +--- + +## Também conhecido como +Wrapper + +## Propósito +Converter a interface de uma classe em outra que o cliente espera. +O padrão Adapter permite que uma classe funcione em conjunto com outras classes que não poderiam por problemas de imcompatibilidade de interfaces. + +## Explicação + +Exemplo do mundo real + +> Considere que você possui algumas imagens no seu cartão de memória e precisa transferí-las para seu computador. Para isso, você irá precisar de algum tipo de adaptador que seja compatível com alguma entrada de seu computador, então você poderá conectar o cartão de memória no seu computador. Nesse caso, o leitor de cartões de memória é um adaptador (Adapter). +> Outro exemplo poderia ser o famoso adaptador elétrico; um plug de três pinos não pode ser conectado a uma tomada de dois oríficios, é necessário usar um adaptador que fará com que haja compatibilidade entre a tomada e o plugue. +> Outro exemplo ainda poderia ser um tradutor traduzindo palavras ditas por uma pessoa para outra. + +Em outras palavras + +> O padrão Adapter permite que você envolva um objeto incompatível em um adaptador que o transforma em um objeto compatível com outra classe. + +Wikipedia diz + +> Em engenharia de software, o padrão Adapter é um padrão de projeto de software que permite a interface de uma classe existente ser usada como outra interface. É frequentemente usada para fazer classes já existentes funcionarem com outras, sem modificar seu código fonte. + +**Exemplo de programação** + +Considere um capitão que pode apenas usar botes a remo e não pode navegar de outro modo. + +Primeiramente, temos as interfaces `RowingBoat` e `FishingBoat` + +```java +public interface RowingBoat { + void row(); +} + +@Slf4j +public class FishingBoat { + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } +} +``` + +E o capitão espera uma implementação da interface `RowingBoat` para ser capaz de se mover + +```java +public class Captain { + + private final RowingBoat rowingBoat; + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +Agora, digamos que os piratas estão chegando e nosso capitão precisa escapar, mas há apenas um bote de pesca disponível. Nós precisamos criar um adaptador que permita o capitão operar o bote de pesca com suas habilidades de condução do bote a remo. + +```java +@Slf4j +public class FishingBoatAdapter implements RowingBoat { + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} +``` + +E agora o `Captain` pode usar o `FishingBoat` para escapar dos piratas. + +```java +var captain = new Captain(new FishingBoatAdapter()); +captain.row(); +``` + +## Diagrama de classes +![alt text](./etc/adapter.urm.png "Diagrama de classes do Adapter") + +## Aplicabilidade +Use o padrão Adapter quando + +* Você quer usar uma classe existente, e sua interface não combina exatamente com o que você precisa +* Você quer criar uma classe reusável que contribui com classes não relacionadas ou não previstas, isto é, classes que não necessariamente tem interfaces compatíveis +* Você precisa utilizar várias subclasses existentes, mas é impraticável adaptar suas interfaces criando novas subclasses para cada uma. Um adapter pode adaptar a interface da sua classe pai. +* A maioria das aplicações que usa bibliotecas de terceiros usa apdaters como uma camada intermediária entre a aplicação e a biblioteca de terceiro para desacoplar a aplicação da biblioteca externa. Se outra biblioteca precisar ser usada, será necessário apenas adequar o adapter para essa nova biblioteca, sem necessidade de alterar muito código. + +## Tutoriais (em inglês) + +* [Dzone](https://dzone.com/articles/adapter-design-pattern-in-java) +* [Refactoring Guru](https://refactoring.guru/design-patterns/adapter/java/example) +* [Baeldung](https://www.baeldung.com/java-adapter-pattern) + +## Consequências +Classes e objetos adapter tem diferentes prós e contras. Uma classe adapter + +* Converte o objeto adaptado para o alvo por meio de uma classe concreta. Como consequência, uma classe adapter não irá funcionar se desejamos adaptar uma classe e todas as suas subclasses. +* Deixa o Adapter sobrescrever algum comportamento da classe adaptada já que o Adapter é uma subclasse da classe adaptada. +* Introduz apenas um objeto, e nenhum ponteiro indireto é necessário para obter a classe adaptada. + +Um objeto adapter + +* Permite um único adaptador funcionar com vários objetos adaptados, isto é, o objeto adaptado em si e todas as suas subclasses (se houver). O adapter também pode adicionar funcionalidade a todas os objetos adaptados de uma vez só. +* Torna mais difícil sobrescrever o comportamento do objeto adaptado. Isso irá requerer geração de subclasses para o objeto adaptado e fazer o adapter se referir a essa subclasse em vez do objeto adaptado em si. + +## Exemplos do mundo real + +* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +* [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +* [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/pt/builder/README.md b/localization/pt/builder/README.md new file mode 100644 index 000000000000..2c202db7b669 --- /dev/null +++ b/localization/pt/builder/README.md @@ -0,0 +1,152 @@ +--- +title: Builder +categories: Creational +language: pt +tag: +- Gang of Four +--- + +## Propósito + +Separe a construção de um objeto complexo de sua representação para que a mesma construção do +processo possa criar diferentes representações. + +## Explicação + +Exemplo do Mundo Real + +> Imagine um gerador de personagens para um jogo de RPG. A opção mais fácil é deixar que o computador +> crie o personagem para você. Se você quiser selecionar manualmente os detalhes do personagem como +> profissão, gênero, cor de cabelo, etc. a geração do personagem se torna um processo passo a passo que +> termina quando todas as seleções estiverem prontas. + +Em outras palavras + +> Permite criar diferentes formas de um objeto, evitando a poluição do construtor. Útil +> quando pode haver várias formas de um objeto. Ou quando há muitos passos envolvidos na +> criação de um objeto. + +De acordo com a Wikipédia + +> o Builder constrói objetos complexos passo a passo e procura evitar ser um anti-padrão. + +Dito isso, deixe-me acrescentar um pouco sobre o que é o antipadrão do construtor. Em um ponto +ou o outro, todos nós vimos um construtor como abaixo: + +```java +public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) { +} +``` + +Como você pode ver, o número de parâmetros do construtor pode ficar rapidamente fora de controle e pode se tornar +difícil entender a disposição dos parâmetros. Além disso, esta lista de parâmetros pode continuar +crescendo se você quiser adicionar mais opções no futuro. Isso é chamado de construtor telescópico +anti-padrão. + +**Exemplo Programático** + +A alternativa sensata é usar o padrão Builder. Em primeiro lugar, temos o nosso herói que queremos criar: + +```java +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; + } +} +``` + +Então temos o builder: + +```java + 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); + } + } +``` + +Então pode ser usado como: + +```java +var mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build(); +``` + +## Diagrama de classes + +![alt text](../../../builder/etc/builder.urm.png "Diagrama de classes Builder") + +## Aplicabilidade + +Use o padrão Builder quando + +* O algoritmo para criar um objeto complexo deve ser independente das partes que compõem o objeto e de como elas são montadas +* O processo de construção deve permitir diferentes representações para o objeto construído + +## Tutoriais + +* [Refactoring Guru](https://refactoring.guru/design-patterns/builder) +* [Oracle Blog](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) +* [Journal Dev](https://www.journaldev.com/1425/builder-design-pattern-in-java) + +## Usos conhecidos + +* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) +* [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) bem como buffers semelhantes, como FloatBuffer, IntBuffer e assim por diante. +* [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) +* Todas as implementações de [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) +* [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/pt/caching/README.md b/localization/pt/caching/README.md new file mode 100644 index 000000000000..fd4dd75223b1 --- /dev/null +++ b/localization/pt/caching/README.md @@ -0,0 +1,326 @@ +--- +title: Cache +category: Behavioral +language: pt +tag: + - Performance + - Cloud distributed +--- + + +## Propósito + +O padrão de armazenamento em cache evita a custosa reaquisição de recursos por não liberá-los ou limpá-los imediatamente após o uso. Os recursos mantêm sua identidade, são mantidos em algum tipo de armazenamento de acesso rápido e são reutilizados para evitar a necessidade de buscá-los novamente. +## Explicação + +Exemplo de uso em mundo real: + +> Uma equipe está trabalhando em um site que oferece novos lares para gatos abandonados. As pessoas podem postar seus gatos no site depois de se registrarem, mas todos os novos posts precisam da aprovação de um dos moderadores do site. As contas dos moderadores do site tem um campo específico sinalizando isso e os dados são salvos em um banco de dados MongoDB. +> Checar esse campo específico todas vez que um post é visualizado custa caro e é uma boa ideia usar armazenamento em cache nesse caso. + +De modo simples: + +> O padrão de armazenamento em cache guarda dados que são requisitados frequentemente em um armazenamento de rápido acesso para melhorar a performance. + +De acordo com a Wikipedia: + +>Em computação, cache é um componente de hardware ou software que guarda dados que quando futuramente solicitados, podem ser servidos de maneira mais rapida. +>Os dados armazenados em cache podem ser o resultado de algum cálculo anterior ou a cópia de outros dados que anteriormente estava armazenados em outro lugar. +>Um "cache hit" (acerto de cache) acontece quando o dado requisitado é encontrado no cache, enquanto um "cache miss" (falta de cache) acontece quando os dado não é encontrado no cache. +>Os "cache hits" são lidos diretamente do cache, o que é mais rápido do que recalcular ou buscar os dados em outro lugar. Portante quando mais requisições forem atendidas pelo cache, mais rápido o sistema performa. + +**Exemplo programático** + +Vamos primeiro analisar a camada de dados da nossa aplicação. As classes que nos interessa são `UserAccount` que é um objeto Java simples que contém detalhes da conta do usuário e a interface `DbManager` que lida com a leitura e escrita desses objetos no banco de dados. +```java +@Data +@AllArgsConstructor +@ToString +@EqualsAndHashCode +public class UserAccount { + private String userId; + private String userName; + private String additionalInfo; +} + +public interface DbManager { + + void connect(); + void disconnect(); + + UserAccount readFromDb(String userId); + UserAccount writeToDb(UserAccount userAccount); + UserAccount updateDb(UserAccount userAccount); + UserAccount upsertDb(UserAccount userAccount); +} +``` +No exemplos, vamos demonstrar várias políticas de armazenamento de cache diferentes: + +* Write-through: Escreve os dados no cache e no DB em uma única transação. +* Write-around: Escreve os dados diretamente no DB em vez de escrever no cache. + Write-behind: Escreve os dados no cache inicialmente enquanto os dados são escritos no banco de dados apenas quando o cache está cheio. + Cache-aside: Delega a responsabilidade de manter os dados sincronizados em ambas as fontes de dados (cache e DB) para a própria aplicação. +* Read-through: Essa estratégia também está incluída nas estratégias mencionadas acima e retorna dados do cache (cache hit) para o chamador, se existir, caso contrário (cache miss), consulta o banco de dados e armazena os dados no cache para uso futuro. + +The cache implementation in `LruCache` is a hash table accompanied by a doubly +linked-list. The linked-list helps in capturing and maintaining the LRU data in the cache. When +data is queried (from the cache), added (to the cache), or updated, the data is moved to the front +of the list to depict itself as the most-recently-used data. The LRU data is always at the end of +the list. + +A implementação de cache em `LruCache` é uma tabela hash acompanhada por uma lista duplamente encadeada - ou lista duplamente ligada (Doubly linked list). +Essa lista ligada ajuda a capturar e manter os dados LRU (Least Recently Used - Menos Recentemente Usados) no cache. +Quando os dados são consultados (do cache), adicionados (ao cache) ou atualizados, os dados são movidos para o início da lista como os dados mais recentemente usados. Os dados LRU estão sempre no final da lista. + +```java +@Slf4j +public class LruCache { + + static class Node { + String userId; + UserAccount userAccount; + Node previous; + Node next; + + public Node(String userId, UserAccount userAccount) { + this.userId = userId; + this.userAccount = userAccount; + } + } + + /* ... omitted details ... */ + + public LruCache(int capacity) { + this.capacity = capacity; + } + + public UserAccount get(String userId) { + if (cache.containsKey(userId)) { + var node = cache.get(userId); + remove(node); + setHead(node); + return node.userAccount; + } + return null; + } + + public void set(String userId, UserAccount userAccount) { + if (cache.containsKey(userId)) { + var old = cache.get(userId); + old.userAccount = userAccount; + remove(old); + setHead(old); + } else { + var newNode = new Node(userId, userAccount); + if (cache.size() >= capacity) { + LOGGER.info("# Cache is FULL! Removing {} from cache...", end.userId); + cache.remove(end.userId); // remove LRU data from cache. + remove(end); + setHead(newNode); + } else { + setHead(newNode); + } + cache.put(userId, newNode); + } + } + + public boolean contains(String userId) { + return cache.containsKey(userId); + } + + public void remove(Node node) { /* ... */ } + public void setHead(Node node) { /* ... */ } + public void invalidate(String userId) { /* ... */ } + public boolean isFull() { /* ... */ } + public UserAccount getLruData() { /* ... */ } + public void clear() { /* ... */ } + public List getCacheDataInListForm() { /* ... */ } + public void setCapacity(int newCapacity) { /* ... */ } +} +``` + +A próxima camada que vamos analisar é `CacheStore`, que implementa as diferentes estratégias de armazenamento em cache. + +```java +@Slf4j +public class CacheStore { + + private static final int CAPACITY = 3; + private static LruCache cache; + private final DbManager dbManager; + + /* ... details omitted ... */ + + public UserAccount readThrough(final String userId) { + if (cache.contains(userId)) { + LOGGER.info("# Found in Cache!"); + return cache.get(userId); + } + LOGGER.info("# Not found in cache! Go to DB!!"); + UserAccount userAccount = dbManager.readFromDb(userId); + cache.set(userId, userAccount); + return userAccount; + } + + public void writeThrough(final UserAccount userAccount) { + if (cache.contains(userAccount.getUserId())) { + dbManager.updateDb(userAccount); + } else { + dbManager.writeToDb(userAccount); + } + cache.set(userAccount.getUserId(), userAccount); + } + + public void writeAround(final UserAccount userAccount) { + if (cache.contains(userAccount.getUserId())) { + dbManager.updateDb(userAccount); + // Cache data has been updated -- remove older + cache.invalidate(userAccount.getUserId()); + // version from cache. + } else { + dbManager.writeToDb(userAccount); + } + } + + public static void clearCache() { + if (cache != null) { + cache.clear(); + } + } + + public static void flushCache() { + LOGGER.info("# flushCache..."); + Optional.ofNullable(cache) + .map(LruCache::getCacheDataInListForm) + .orElse(List.of()) + .forEach(DbManager::updateDb); + } + + /* ... omitted the implementation of other caching strategies ... */ + +} +``` + +A classe `AppManager` ajuda em fazer a ponte de comunicação entre a classe principal e o backend da aplicação. A conexão com o DB é inicializada por meio dessa classe. A estratégia ou política de cache escolhida também é inicializada aqui. +Antes do cache poder ser usado, é preciso definir o tamanho do cache. +Dependendo da estratégio de armazenamento de cache escolhida, a classe `AppManager` chamará a função (método) apropriada na classe `CacheStore`. + +```java +@Slf4j +public final class AppManager { + + private static CachingPolicy cachingPolicy; + private final DbManager dbManager; + private final CacheStore cacheStore; + + private AppManager() { + } + + public void initDb() { /* ... */ } + + public static void initCachingPolicy(CachingPolicy policy) { /* ... */ } + + public static void initCacheCapacity(int capacity) { /* ... */ } + + public UserAccount find(final String userId) { + LOGGER.info("Trying to find {} in cache", userId); + if (cachingPolicy == CachingPolicy.THROUGH + || cachingPolicy == CachingPolicy.AROUND) { + return cacheStore.readThrough(userId); + } else if (cachingPolicy == CachingPolicy.BEHIND) { + return cacheStore.readThroughWithWriteBackPolicy(userId); + } else if (cachingPolicy == CachingPolicy.ASIDE) { + return findAside(userId); + } + return null; + } + + public void save(final UserAccount userAccount) { + LOGGER.info("Save record!"); + if (cachingPolicy == CachingPolicy.THROUGH) { + cacheStore.writeThrough(userAccount); + } else if (cachingPolicy == CachingPolicy.AROUND) { + cacheStore.writeAround(userAccount); + } else if (cachingPolicy == CachingPolicy.BEHIND) { + cacheStore.writeBehind(userAccount); + } else if (cachingPolicy == CachingPolicy.ASIDE) { + saveAside(userAccount); + } + } + + public static String printCacheContent() { + return CacheStore.print(); + } + + /* ... details omitted ... */ +} +``` + +Essa é nossa classe princial e como usamos a implmentação: + +```java +@Slf4j +public class App { + + public static void main(final String[] args) { + boolean isDbMongo = isDbMongo(args); + if(isDbMongo){ + LOGGER.info("Using the Mongo database engine to run the application."); + } else { + LOGGER.info("Using the 'in Memory' database to run the application."); + } + App app = new App(isDbMongo); + app.useReadAndWriteThroughStrategy(); + String splitLine = "=============================================="; + LOGGER.info(splitLine); + app.useReadThroughAndWriteAroundStrategy(); + LOGGER.info(splitLine); + app.useReadThroughAndWriteBehindStrategy(); + LOGGER.info(splitLine); + app.useCacheAsideStategy(); + LOGGER.info(splitLine); + } + + public void useReadAndWriteThroughStrategy() { + LOGGER.info("# CachingPolicy.THROUGH"); + appManager.initCachingPolicy(CachingPolicy.THROUGH); + + var userAccount1 = new UserAccount("001", "John", "He is a boy."); + + appManager.save(userAccount1); + LOGGER.info(appManager.printCacheContent()); + appManager.find("001"); + appManager.find("001"); + } + + public void useReadThroughAndWriteAroundStrategy() { /* ... */ } + + public void useReadThroughAndWriteBehindStrategy() { /* ... */ } + + public void useCacheAsideStategy() { /* ... */ } +} +``` + +## Diagrama de classes + +![alt text](./etc/caching.png "Caching") + +## Aplicabilidade + +Utilize os padrões de armazenamento em cache quando: + +* Repetidas aquisições, inicialização e liberação do mesmo recurso causam sobrecarga de desempenho desnecessária. + +## Padrões relacionados + +* [Proxy](https://java-design-patterns.com/patterns/proxy/) + +## Créditos + +* [Write-through, write-around, write-back: Cache explained](http://www.computerweekly.com/feature/Write-through-write-around-write-back-Cache-explained) +* [Read-Through, Write-Through, Write-Behind, and Refresh-Ahead Caching](https://docs.oracle.com/cd/E15357_01/coh.360/e15723/cache_rtwtwbra.htm#COHDG5177) +* [Cache-Aside pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/cache-aside) +* [Java EE 8 High Performance: Master techniques such as memory optimization, caching, concurrency, and multithreading to achieve maximum performance from your enterprise applications](https://www.amazon.com/gp/product/178847306X/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=178847306X&linkId=e948720055599f248cdac47da9125ff4) +* [Java Performance: In-Depth Advice for Tuning and Programming Java 8, 11, and Beyond](https://www.amazon.com/gp/product/1492056111/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1492056111&linkId=7e553581559b9ec04221259e52004b08) +* [Effective Java](https://www.amazon.com/gp/product/B078H61SCH/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B078H61SCH&linkId=f06607a0b48c76541ef19c5b8b9e7882) +* [Java Performance: The Definitive Guide: Getting the Most Out of Your Code](https://www.amazon.com/gp/product/1449358454/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1449358454&linkId=475c18363e350630cc0b39ab681b2687) diff --git a/localization/pt/chain-of-responsability/README.md b/localization/pt/chain-of-responsability/README.md new file mode 100644 index 000000000000..85f962b19bfb --- /dev/null +++ b/localization/pt/chain-of-responsability/README.md @@ -0,0 +1,174 @@ +--- +title: Chain of responsibility +category: Behavioral +language: pt +tag: + - Gang of Four +--- + +## Propósito + +Evitar acoplar o remetente de uma *request* ao seu destinatário, dando a mais de um objeto a chance de +lidar com a solicitação. Encadeie os objeto recebidos e passe a solicitação ao longo da cadeia até um objeto +lidar com isso. + +## Explicação + +Exemplo do mundo real + +> O Rei Orc dá ordens ao seu exército. O primeiro a receber a ordem é o comandante, então +> um oficial e depois um soldado. O comandante, o oficial e o soldado formam uma cadeia de responsabilidades. + + +Em outras palavras + +> Ajuda a construir uma cadeia de objetos. Uma solicitação entra de uma extremidade e continua indo de um objeto +> para outro até encontrar um manipulador adequado. + +Wikipedia diz + +> Em orientação a objetos, Chain of Responsibility é um padrão cuja principal função é evitar a dependência +> entre um objeto receptor e um objeto solicitante. Consiste em uma série de objetos receptores e de objetos +> de solicitação, onde cada objeto de solicitação possui uma lógica interna que separa quais são tipos de +> objetos receptores que podem ser manipulados. O restante é passado para os próximos objetos de solicitação da cadeia. + +**Exemplo de programação** + +Traduzindo nosso exemplo com os orcs acima. Primeiro, nós temos a classe `Request`: + +```java +public class Request { + + private final RequestType requestType; + private final String requestDescription; + private boolean handled; + + public Request(final RequestType requestType, final String requestDescription) { + this.requestType = Objects.requireNonNull(requestType); + this.requestDescription = Objects.requireNonNull(requestDescription); + } + + public String getRequestDescription() { return requestDescription; } + + public RequestType getRequestType() { return requestType; } + + public void markHandled() { this.handled = true; } + + public boolean isHandled() { return this.handled; } + + @Override + public String toString() { return getRequestDescription(); } +} + +public enum RequestType { + DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX +} +``` + +Em seguida, mostramos a hierarquia no request handler + +```java +public interface RequestHandler { + + boolean canHandleRequest(Request req); + + int getPriority(); + + void handle(Request req); + + String name(); +} + +@Slf4j +public class OrcCommander implements RequestHandler { + @Override + public boolean canHandleRequest(Request req) { + return req.getRequestType() == RequestType.DEFEND_CASTLE; + } + + @Override + public int getPriority() { + return 2; + } + + @Override + public void handle(Request req) { + req.markHandled(); + LOGGER.info("{} handling request \"{}\"", name(), req); + } + + @Override + public String name() { + return "Orc commander"; + } +} + +// OrcOfficer and OrcSoldier are defined similarly as OrcCommander + +``` + +O Rei Orc dá as ordens e forma a cadeia + +```java +public class OrcKing { + + private List handlers; + + public OrcKing() { + buildChain(); + } + + private void buildChain() { + handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier()); + } + + public void makeRequest(Request req) { + handlers + .stream() + .sorted(Comparator.comparing(RequestHandler::getPriority)) + .filter(handler -> handler.canHandleRequest(req)) + .findFirst() + .ifPresent(handler -> handler.handle(req)); + } +} +``` + +O chain of responsibility em ação. + +```java +var king = new OrcKing(); +king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); +king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); +king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); +``` + +A saída do console. + +``` +Orc commander handling request "defend castle" +Orc officer handling request "torture prisoner" +Orc soldier handling request "collect tax" +``` + +## Diagrama de classe + +![alt text](././etc/chain-of-responsibility.urm.png "Diagrama de classe Chain of Responsibility") + +## Aplicabilidade + +Usar Chain of Responsibility quando + +* Mais de um objeto pode lidar com uma solicitação, e o manipulador não é conhecido a priori. O manipulador deve ser verificado automaticamente. +* Você deseja emitir uma solicitação para um dos vários objetos sem especificar o destinatário explicitamente. +* O conjunto de objetos que podem lidar com uma solicitação deve ser especificado dinamicamente. + +## Exemplos do mundo real + +* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) +* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) +* [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/pt/facade/README.md b/localization/pt/facade/README.md new file mode 100644 index 000000000000..6584d7fd17a2 --- /dev/null +++ b/localization/pt/facade/README.md @@ -0,0 +1,218 @@ +--- +title: Facade +category: Structural +language: pt +tag: + - Gang Of Four + - Decoupling +--- + +## Propósito + +Prover uma interface unificada para um conjunto de interfaces em um subsistema. +Facade (ou fachada) define uma interface num nível mais elevado que torna o subsistema mais fácil de ser utilizado. + +## Explicação + +Real-world example +Exemplo do mundo real + +> Como uma mina de ouro funciona? "Bem, os mineradores vão pro subsolo, cavam e encontram ouro!" você pode dizer. +> Isso é o que você acredita porque você está usando uma simples interface que a mina de ouro provê para o exterior, +> internamente há muitas coisas a fazer para que isso aconteça. Essa interface simples para um subsistema complexo é +> um facade. + +Em termos pŕaticos + +> O padrão Facade provê uma interface simplificada para um subsistema complexo. + +Wikipedia diz + +> Um facade é um objeto que provê uma interface simplificada para um corpo maior de código fonte, +> como uma biblioteca de uma classe. + +**Exemplo programático** + +Vamos pegar nosso exemplo da mina de ouro acima. Aqui temos uma hierarquia de anão minerador. +Primeiro há uma classe base `DwarvenMineWorker`: + +```java + +@Slf4j +public abstract class DwarvenMineWorker { + + public void goToSleep() { + LOGGER.info("{} goes to sleep.", name()); + } + + public void wakeUp() { + LOGGER.info("{} wakes up.", name()); + } + + public void goHome() { + LOGGER.info("{} goes home.", name()); + } + + public void goToMine() { + LOGGER.info("{} goes to the mine.", name()); + } + + private void action(Action action) { + switch (action) { + case GO_TO_SLEEP -> goToSleep(); + case WAKE_UP -> wakeUp(); + case GO_HOME -> goHome(); + case GO_TO_MINE -> goToMine(); + case WORK -> work(); + default -> LOGGER.info("Undefined action"); + } + } + + public void action(Action... actions) { + Arrays.stream(actions).forEach(this::action); + } + + public abstract void work(); + + public abstract String name(); + + enum Action { + GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK + } +} +``` + +Então nós temos as classes concretas anão `DwarvenTunnelDigger`, `DwarvenGoldDigger` and +`DwarvenCartOperator`: + +```java +@Slf4j +public class DwarvenTunnelDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} creates another promising tunnel.", name()); + } + + @Override + public String name() { + return "Dwarven tunnel digger"; + } +} + +@Slf4j +public class DwarvenGoldDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} digs for gold.", name()); + } + + @Override + public String name() { + return "Dwarf gold digger"; + } +} + +@Slf4j +public class DwarvenCartOperator extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} moves gold chunks out of the mine.", name()); + } + + @Override + public String name() { + return "Dwarf cart operator"; + } +} + +``` + +Para operar todos esses mineradores de ouro temos o `DwarvenGoldmineFacade`: + +```java +public class DwarvenGoldmineFacade { + + private final List workers; + + public DwarvenGoldmineFacade() { + workers = List.of( + new DwarvenGoldDigger(), + new DwarvenCartOperator(), + new DwarvenTunnelDigger()); + } + + public void startNewDay() { + makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); + } + + public void digOutGold() { + makeActions(workers, DwarvenMineWorker.Action.WORK); + } + + public void endDay() { + makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); + } + + private static void makeActions(Collection workers, + DwarvenMineWorker.Action... actions) { + workers.forEach(worker -> worker.action(actions)); + } +} +``` + +Agora vamos usar o facade: + +```java +var facade = new DwarvenGoldmineFacade(); +facade.startNewDay(); +facade.digOutGold(); +facade.endDay(); +``` + +Saída do programa: + +```java +// Dwarf gold digger wakes up. +// Dwarf gold digger goes to the mine. +// Dwarf cart operator wakes up. +// Dwarf cart operator goes to the mine. +// Dwarven tunnel digger wakes up. +// Dwarven tunnel digger goes to the mine. +// Dwarf gold digger digs for gold. +// Dwarf cart operator moves gold chunks out of the mine. +// Dwarven tunnel digger creates another promising tunnel. +// Dwarf gold digger goes home. +// Dwarf gold digger goes to sleep. +// Dwarf cart operator goes home. +// Dwarf cart operator goes to sleep. +// Dwarven tunnel digger goes home. +// Dwarven tunnel digger goes to sleep. +``` + +## Diagrama de classe + +![alt text](./etc/facade.urm.png "Diagrama de classe padrão Facade") + +## Aplicabilidade + +Use o padrão facade quando + +* Você quer prover uma simples interface para um subsistema complexo. Subsistemas frequentemente +vão ficando mais complexos conforme eles evoluem. A maioria dos padrões, quando aplicada, resulta +em classes menores e mais numerosas. Isso faz com que o subsistema se torne mais reusável e mais +fácil de customizar, mas também torna mais difícil de usar para clientes que não precisam de +customização. +* Há muitas dependências entre clientes e as classes de implementação de uma abstração. Introduza +um facade para desacoplar o subsistema de clientes e outros subsistemas, portanto promovendo independência +e portabilidade para o subsistema. +* Você quer subdividir em camadas o seu subsistema. Use um facade para definir um ponto de entrada +para cada nível de subsistema. Se o subsistema é dependente, então você pode simplificar as dependências +entre eles, fazendo-os se comunicarem entre si apenas pelos facades. + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/pt/factory/README.md b/localization/pt/factory/README.md new file mode 100644 index 000000000000..296c1b758b0c --- /dev/null +++ b/localization/pt/factory/README.md @@ -0,0 +1,141 @@ +--- +title: Factory +category: Creational +language: pt +tag: + - Gang of Four +--- + +## Também conhecido como + +* Simple Factory +* Static Factory Method + +## Propósito + +Fornecer um método estático encapsulado em uma classe conhecida como factory, para ocultar a lógica +de implementação e fazer com que o código do cliente se preocupe apenas com sua utilização em vez de +inicializar novos objetos. + +## Explicação + +Exemplo de mundo real + +> Imagine um alquimista que está prestes a fabricar moedas. O alquimista deve ser capaz de produzir +> moedas de ouro e cobre, e a alternância entre a fabricação destas deve ser possível sem a necessidade +> de modificar o código fonte. O padrão factory torna isso possível fornecendo um método construtor estático +> que pode ser chamado com parâmetros relevantes. + +Wikipedia diz + +> Factory é um objeto para a criação de outros objetos - formalmente uma factory é uma função ou método +> que retorna objetos de protótipos ou classes variadas. + +**Exemplo de programação** + +Temos uma interface `Coin` e duas implementações `GoldCoin` e `CopperCoin`. + +```java +public interface Coin { + String getDescription(); +} + +public class GoldCoin implements Coin { + + static final String DESCRIPTION = "This is a gold coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class CopperCoin implements Coin { + + static final String DESCRIPTION = "This is a copper coin."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +O enum abaixo representa os tipos de moedas que suportamos (`GoldCoin` e `CopperCoin`). + +```java +@RequiredArgsConstructor +@Getter +public enum CoinType { + + COPPER(CopperCoin::new), + GOLD(GoldCoin::new); + + private final Supplier constructor; +} +``` + +Então temos o método estático `getCoin` para criar objetos de moeda encapsulados na classe factory +`CoinFactory`. + +```java +public class CoinFactory { + + public static Coin getCoin(CoinType type) { + return type.getConstructor().get(); + } +} +``` + +Agora no código cliente podemos criar diferentes tipos de moedas usando a classe factory. + +```java +LOGGER.info("The alchemist begins his work."); +var coin1 = CoinFactory.getCoin(CoinType.COPPER); +var coin2 = CoinFactory.getCoin(CoinType.GOLD); +LOGGER.info(coin1.getDescription()); +LOGGER.info(coin2.getDescription()); +``` + +Saída do programa: + +```java +The alchemist begins his work. +This is a copper coin. +This is a gold coin. +``` + +## Diagrama de classes + +![alt text](./etc/factory.urm.png "Diagrama de classes do padrão Factory") + +## Aplicabilidade + +Utilize o padrão factory quando a preocupação é apenas em criar o objeto, e não como criar +e gerenciá-lo. + +Prós + +* Permite manter a criação de todos os objetos em um só lugar e evita espalhar a palavra-chave 'new' pela base de código. +* Permite escrever código desacoplado. Algumas de suas principais vantagens incluem uma melhor testabilidade, código fácil de entender, componentes substituíveis, escalabilidade e funcionalidades isoladas. + +Contras + +* O código se torna mais complicado do que deveria. + +## Usos conhecidos + +* [java.util.Calendar#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +* [java.util.ResourceBundle#getBundle()](https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +* [java.text.NumberFormat#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +* [java.nio.charset.Charset#forName()](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +* [java.net.URLStreamHandlerFactory#createURLStreamHandler(String)](https://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html) (retorna objetos singleton diferentes, dependendo do protocolo) +* [java.util.EnumSet#of()](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of(E)) +* [javax.xml.bind.JAXBContext#createMarshaller()](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) e outros métodos parecidos. + +## Padrões relacionados + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/) + diff --git a/localization/pt/proxy/README.md b/localization/pt/proxy/README.md new file mode 100644 index 000000000000..79f467baf3d2 --- /dev/null +++ b/localization/pt/proxy/README.md @@ -0,0 +1,166 @@ +--- +title: Proxy +category: Structural +language: pt +tag: + - Gang Of Four + - Decoupling +--- + +## Também conhecido como + +Surrogate + +## Propósito + +Fornecer um substituto para controlar o acesso ao objeto original + +## Explicação + +Exemplo de mundo real + +> Imagine uma torre onde magos locais vão estudar os seus feitiços. A torre de marfim consegue ser +> acedida através de uma proxy que garante que apenas os três primeiros magos podem entrar. Aqui a proxy +> representa a funcionalidade da torre e adiciona controlo de acesso a ela. + +Em palavras simples + +> Usando um padrão proxy, a classe representa a funcionalidade de uma outra classe. + +Wikipedia diz + +> Uma proxy, na sua forma mais genérica, é uma classe a funcionar como interface para algo. +> Uma proxy é um wrapper ou objeto agente que está a ser chamado pelo cliente para aceder ao verdadeiro +> objeto por detrás das cortinas. O uso de uma proxy pode ser apenas redirecionar para o objeto real, ou +> pode fornecer lógica adicional. Numa proxy, funcionalidade extra também pode ser fornecida, por exemplo apanhar +> operações no objeto real que gastam muitos recursos, ou verificar precondições antes +> das operações no objeto real serem invocadas. + +**Exemplos de programação** + +Usando a nossa torre de magos do exemplo acima. Primeiro temos a interface `WizardTower` e a classe +`IvoryTower`. + +```java +public interface WizardTower { + + void enter(Wizard wizard); +} + +@Slf4j +public class IvoryTower implements WizardTower { + + public void enter(Wizard wizard) { + LOGGER.info("{} enters the tower.", wizard); + } + +} +``` + +Depois uma simples classe `Wizard`. + +```java +public class Wizard { + + private final String name; + + public Wizard(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} +``` + +Depois temos a `WizardTowerProxy` para adicionar controlo à `WizardTower`. + +```java +@Slf4j +public class WizardTowerProxy implements WizardTower { + + private static final int NUM_WIZARDS_ALLOWED = 3; + + private int numWizards; + + private final WizardTower tower; + + public WizardTowerProxy(WizardTower tower) { + this.tower = tower; + } + + @Override + public void enter(Wizard wizard) { + if (numWizards < NUM_WIZARDS_ALLOWED) { + tower.enter(wizard); + numWizards++; + } else { + LOGGER.info("{} is not allowed to enter!", wizard); + } + } +} +``` + +E aqui está a torre a entrar em cenário. + +```java +var proxy = new WizardTowerProxy(new IvoryTower()); +proxy.enter(new Wizard("Red wizard")); +proxy.enter(new Wizard("White wizard")); +proxy.enter(new Wizard("Black wizard")); +proxy.enter(new Wizard("Green wizard")); +proxy.enter(new Wizard("Brown wizard")); +``` + +Saída do programa: + +``` +Red wizard enters the tower. +White wizard enters the tower. +Black wizard enters the tower. +Green wizard is not allowed to enter! +Brown wizard is not allowed to enter! +``` + +## Diagrama de classes + +![alt text](./etc/proxy.urm.png "Diagrama de classes do padrão proxy") + +## Aplicabilidade + +O proxy é aplicável quando existe a necessidade de uma referência a um objeto mais versátil ou sofisticada em vez de um simples ponteiro. Aqui estão várias situações comuns em que o padrão Proxy é aplicável. + +* Proxy remoto dá uma representação local de um objeto num espaço de endereçamento diferente. +* Proxy virtual cria objetos dispendiosos quando requisitado. +* Proxy de proteção controla o acesso ao objeto original. Proxies de proteção são úteis quando objetos deviam ter direitos de acesso diferentes. + +Tipicamente, o padrão proxy é usado para + +* Controlar acesso a um outro objeto +* Inicialização preguiçosa +* Implementar um registro de eventos (logging) +* Facilitar a conexão com a rede +* Contar o número de referências para um objeto + +## Tutoriais + +* [Controlar acesso com um padrão Proxy](http://java-design-patterns.com/blog/controlling-access-with-proxy-pattern/) + +## Usos conhecidos + +* [java.lang.reflect.Proxy](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html) +* [Apache Commons Proxy](https://commons.apache.org/proper/commons-proxy/) +* Frameworks para Mocking [Mockito](https://site.mockito.org/), +[Powermock](https://powermock.github.io/), [EasyMock](https://easymock.org/) +* UIKit's da Apple [UIAppearance](https://developer.apple.com/documentation/uikit/uiappearance) + +## Padrões relacionados + +* [Ambassador](https://java-design-patterns.com/patterns/ambassador/) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/pt/singleton/README.md b/localization/pt/singleton/README.md new file mode 100644 index 000000000000..83604d959368 --- /dev/null +++ b/localization/pt/singleton/README.md @@ -0,0 +1,109 @@ +--- +title: "Singleton Pattern in Java: Implementing Global Access Points in Java Applications" +shortTitle: Singleton +description: "Explore the Singleton Pattern in Java with our comprehensive guide. Learn how to implement efficient object management for your Java applications, ensuring optimal use of resources and easy access with examples and detailed explanations." +category: Creational +language: pt +tag: + - Gang of Four + - Instantiation + - Lazy initialization + - Resource management +--- + +## Também conhecido como + +* Single Instance + +## Propósito + +Assegurar que a classe Java possua somente uma instância e forneça um ponto global de acesso a essa instância Singleton. + +## Explicação + +Exemplo do Mundo Real + +> Uma analogia do mundo real para o padrão Singleton é um governo emitindo um passaporte. Em um país, cada cidadão pode receber apenas um passaporte válido por vez. O escritório de passaportes garante que nenhum passaporte duplicado seja emitido para a mesma pessoa. Sempre que um cidadão precisa viajar, ele deve usar este passaporte único, que serve como o identificador único e globalmente reconhecido para suas credenciais de viagem. Este acesso controlado e gerenciamento de instância exclusivo espelham como o padrão Singleton garante o gerenciamento eficiente de objetos em aplicativos Java. + +Em outras palavras + +> Assegura que somente um objeto de classe em particular seja criado. + +De acordo com a Wikipédia + +> Na engenharia de software, o padrão Singleton é um padrão de design de software que restringe a instanciação de uma classe a um objeto. Isso é útil quando exatamente um objeto é necessário para coordenar ações no sistema. + +## Exemplo Programático + +Joshua Bloch, Effective Java 2nd Edition pg.18 + +> Um tipo Enum de elemento único é a melhor maneira de implementar um Singleton + +```java +public enum EnumIvoryTower { + INSTANCE +} +``` + +Então para usar: + +```java + var enumIvoryTower1 = EnumIvoryTower.INSTANCE; + var enumIvoryTower2 = EnumIvoryTower.INSTANCE; + LOGGER.info("enumIvoryTower1={}", enumIvoryTower1); + LOGGER.info("enumIvoryTower2={}", enumIvoryTower2); +``` + +A saída do console + +``` +enumIvoryTower1=com.iluwatar.singleton.EnumIvoryTower@1221555852 +enumIvoryTower2=com.iluwatar.singleton.EnumIvoryTower@1221555852 +``` + +## Quando usar + +Use o padrão Singleton quando + +* Deve haver exatamente uma instância de uma classe, e ela deve ser acessível aos clientes a partir de um ponto de acesso bem conhecido +* Quando a única instância deve ser extensível por herança, e os clientes devem ser capazes de usar uma instância estendida sem modificar seu código + +## Aplicações do mundo real + +* A classe de Log +* Classes de configuração em muitos aplicativos +* Pools de conexão +* Gerenciador de arquivos +* [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29) +* [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--) +* [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--) + +## Benefícios e desafios do padrão Singleton + +Benefícios: + +* Acesso controlado à instância única. +* Poluição reduzida do namespace. +* Permite refinamento de operações e representação. +* Permite um número variável de instâncias (se desejado mais de uma). +* Mais flexível do que operações de classe. + +Desafios: + +* Difícil de testar devido ao estado global. +* Gerenciamento de ciclo de vida potencialmente mais complexo. +* Pode introduzir gargalos se usado em um contexto concorrente sem sincronização cuidadosa. + +## Outros Padrōes de Projeto Relacionados + +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Geralmente usado para garantir que uma classe tenha apenas uma instância. +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/): O padrão Singleton pode ser implementado usando o padrāo Factory para encapsular a lógica de criação. +* [Prototype](https://java-design-patterns.com/patterns/prototype/): Evita a necessidade de criar instâncias, pode ser usado em conjunto com o Singleton para gerenciar instâncias únicas. + +## Referências e Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/localization/ru/README.md b/localization/ru/README.md new file mode 100644 index 000000000000..89e4ddffc317 --- /dev/null +++ b/localization/ru/README.md @@ -0,0 +1,65 @@ + + +# Шаблоны проектирования на Java + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-178-orange.svg?style=flat-square)](#contributors-) + + +# Введение +Шаблоны проектирования - лучший метод для решения проблем, возникающих +во время разработки приложения или системы. + +Шаблоны проектирования могут ускорить процесс разработки путем предоставления +проверенных моделей/парадигм. + +Использование шаблонов повторно поможет избежать частых проблем, из-за которых +происходят проблемы. А еще это повысит читаемость кода для программистов и +архитекторов, знакомых с шаблонами. + +# Начало работы + +В этом репозитории размещены шаблоны проектирования на Java. Они были разработаны +программистами из open source сообщества. Шаблон может быть выбран +из его описания или просмотром его исходного кода. Код хорошо задокументирован, +его можно рассматривать, как учебник по программированию о конкретном шаблоне. +Мы используем самые популярные (прошедшие огонь, воду и медные трубы) технологии, +основанные только на ПО с открытым исходным кодом. + +Преждем чем нырнуть в материал, тебе следует ознакомиться с различными +[принципами разработки ПО(англ)](https://java-design-patterns.com/principles/). + +Все конструкции должны быть максимально простыми. Не делай лишнюю функциональность, +которая скорей всего не пригодиться, а просто создай простую штуку, что сможет +работать. Усложнять и вводить паттерны необходимо, лишь когда масштабируемость +действительно нужна. + +Как только ознакомитесь с этими концепциями, приступайте к изучению +[доступных шаблонов проектирования(англ)](https://java-design-patterns.com/patterns/) любым +из следующих методов: + +- Ищите шаблон по имени. Не смогли найти такой? Сообщите об этом [здесь](https://github.com/iluwatar/java-design-patterns/issues). +- Используя тэги, например `Performance`, `Gang of Four` или `Data access`. +- Используя категории шаблонов `Creational`, `Behavioral` и другие. + +Надеемся объективно-ориентированные решения, представленные здесь будут вам +полезны и найдут место в ваших проектах, а также вы получите такое же удовольствие +от их изучения, какое получили мы во время их разработки. + +# Как принять участие в разработке + +Если вы захотите принять участие в жизни проекта, вся полезная информация находится на +нашей [вики(англ)](https://github.com/iluwatar/java-design-patterns/wiki). Мы можем помочь +и ответить на твои вопросы в чате [Gitter](https://gitter.im/iluwatar/java-design-patterns). + +# Лицензия + +Проект основывается на тезисах лицензии MIT. + diff --git a/localization/ru/abstract-factory/README.md b/localization/ru/abstract-factory/README.md new file mode 100644 index 000000000000..044e03c53c5c --- /dev/null +++ b/localization/ru/abstract-factory/README.md @@ -0,0 +1,237 @@ +--- +title: Abstract Factory +category: Creational +language: ru +tag: + - Gang of Four +--- + +## Альтернативные названия +Kit + +## Цель +Предоставление интерфейса для создания семейств взаимосвязанных или взаимозависимых объектов без указания их конкретных классов. + +## Объяснение +Пример из реального мира: +> Представьте, что вы хотите создать королевство с замком, королём и армией. Эльфийскому королевству понадобится эльфийский замок, эльфийский король и эльфийская армия, в то время как оркскому королевству понадобится оркский замок, оркский король и оркская армия. Между объектами королевства существует взаимозависимость. + +Простыми словами: +> Фабрика фабрик; фабрика, которая объединяет отдельные, но взаимозависимые/взаимозаменяемые фабрики без указания их конкретных классов. + +Википедия пишет: +> Порождающий шаблон проектирования, предоставляет интерфейс для создания семейств взаимосвязанных или взаимозависимых объектов, не специфицируя их конкретных классов. + +**Программный пример**\ +Основываясь на примере королевства выше, во-первых, нам понадобятся интерфейсы и реализации для объектов в королевстве. + +```java +public interface Castle { + String getDescription(); +} + +public interface King { + String getDescription(); +} + +public interface Army { + String getDescription(); +} + +// Эльфийская реализация +public class ElfCastle implements Castle { + static final String DESCRIPTION = "Это эльфийский замок!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} +public class ElfKing implements King { + static final String DESCRIPTION = "Это эльфийский король!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} +public class ElfArmy implements Army { + static final String DESCRIPTION = "Это эльфийская армия!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +// Оркская реализация +public class OrcCastle implements Castle { + static final String DESCRIPTION = "Это оркский замок!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} +public class OrcKing implements King { + static final String DESCRIPTION = "Это оркский король!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} +public class OrcArmy implements Army { + static final String DESCRIPTION = "Это оркская армия!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +Во-вторых, нам понадобятся абстракция фабрики королевства, а также реализации этой абстракции: + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +На данный момент, у нас есть абстрактная фабрика, которая позволяет создавать семейство взаимосвязанных объектов, то есть фабрика эльфийского королевства создаёт эльфийский замок, эльфийского короля, эльфийскую армию и так далее: + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +Вывод программы: + +``` +Это эльфийский замок! +Это эльфийский король! +Это эльфийская армия! +``` + +Можно спроектировать фабрику для наших различных фабрик королевств. В следующем примере, мы создали `FactoryMaker`, который ответственен за создание экземпляра `ElfKingdomFactory`, либо `OrcKingdomFactory`. + +Клиент может использовать класс `FactoryMaker`, чтобы создать желаемую конкретную фабрику, которая в свою очередь будет производить разные конкретные объекты, унаследованные от `Castle`, `King`, `Army`. + +В этом примере использовано перечисление, чтобы параметризовать то, какую фабрику королевства запрашивает клиент: + +```java +public static class FactoryMaker { + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + default -> throe new IllegalArgumentException("Данный тип королества не поддерживается.") + } + } +} + + public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Эльфийское королевство"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.indo(app.getCastle().getDescription()); + LOGGER.indo(app.getKinv().getDescription()); + LOGGER.indo(app.getArmy().getDescription()); + + LOGGER.info("Оркское королевство"); + + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + LOGGER.indo(app.getCastle().getDescription()); + LOGGER.indo(app.getKinv().getDescription()); + LOGGER.indo(app.getArmy().getDescription()); + } + +``` + +## Диаграмма классов +![Диаграмма классов паттерна проектирования абстрактная фабрика](../../../abstract-factory/etc/abstract-factory.urm.png) + +## Применимость +Используйте шаблон проектирования абстрактная фабрика, когда: + +- Система должна быть независимой от того, как создаются, составляются и представляются её продукты; +- Система должна быть сконфигурирована одним из нескольких семейств продуктов; +- Семейство связанных продуктов спроектировано для совместного использования и вам необходимо обеспечить соблюдение данного ограничения; +- Вы хотите предоставить библиотеку классов, но готовы раскрыть только их интерфейсы, но не реализацию; +- Время жизни зависимости концептуально короче, чем время жизни потребителя; +- Вам требуется значение времени исполнения, чтобы создать требуемую зависимость; +- Вы хотите решить какие продукты из семейства вам нужны во время исполнения; +- Вам нужно предоставить один или несколько параметров, которые известны только во время исполнения прежде, чем вы сможете решить зависимость; +- В случае, когда требуется последовательность среди продуктов; +- Вы не хотите менять существующий код, когда добавляются новые продукты или семейство продуктов в программе. + +Примеры сценариев использования: + +- Выбор необходимой реализации FileSystemAcmeService или DataBaseAcmeSerivce или NetworkAcmeService во времени выполнения; +- Написание модульных тестов становится намного легче; +- Элементы графического пользовательского интерфейса для различных операционных систем. + +## Следствия +- Внедрение зависимости в Java скрывает зависимости класса, приводящие к ошибкам времени выполнения, которые могли-бы быть обнаружены во времени компиляции; +- Данный паттерн проектирования отлично справляется с задачей создания уже определённых объектов, но добавление новых может быть трудоёмким; +- Код становится сложнее, чем ему следует из-за появления большого количества новых интерфейсов и классов, которые появляются вместе с этим паттерном проектирования. + +## Руководства +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## Известные применения +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## Родственные паттерны проектирования +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## Благодарности +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/si/README.md b/localization/si/README.md new file mode 100644 index 000000000000..e3d789216398 --- /dev/null +++ b/localization/si/README.md @@ -0,0 +1,69 @@ + + +# ජාවා නිර්මාණ රටා + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-176-orange.svg?style=flat-square)](#contributors-) + + + + +# හැදින්වීම + +පැන නගින ගැටළු විසඳීම සඳහා හොඳම ක්රමය නිර්මාණ රටා වේ. + +සැලසුම් රටා ලබා දීමෙන් සංවර්ධන ක්රියාවලිය වේගවත් කළ හැකිය. + +සැකිලි නැවත භාවිතා කිරීම හේතු වන පොදු ගැටළු මඟහරවා ගැනීමට උපකාරී වේ. +ගැටළු ඇතිවේ. මෙය ක්‍රමලේඛකයින් සඳහා කේතයේ කියවීමේ හැකියාවද වැඩි කරයි. + + +# ආරම්භය + +මෙම ගබඩාව Java හි නිර්මාණ රටා සත්කාරකත්වය සපයයි. ඒවා දියුණු කළා +විවෘත මූලාශ්‍ර ප්‍රජාවේ ක්‍රමලේඛකයින්. රටාව තෝරා ගත හැකිය. +එහි විස්තරයෙන් හෝ එහි මූල කේතය බැලීමෙන්. කේතය හොඳින් ලේඛනගත කර ඇත, +එය නිශ්චිත රටාවක් පිළිබඳ ක්‍රමලේඛන නිබන්ධනයක් ලෙස සැලකිය හැකිය. +අපි වඩාත් ජනප්රිය (ගිනි, ජලය සහ තඹ පයිප්ප පරීක්ෂා කරන ලද) තාක්ෂණයන් භාවිතා කරමු, +විවෘත කේත මෘදුකාංග මත පමණක් පදනම් වේ. + +මෙයට කිමිදීමට පෙර, ඔබ විවිධත්වය ගැන හුරුපුරුදු විය යුතුය. +[මෘදුකාංග සංවර්ධනයේ මූලධර්ම](https://java-design-patterns.com/principles/). + +සියලුම මෝස්තර හැකි තරම් සරල විය යුතුය. අනවශ්‍ය ක්‍රියාකාරීත්වයක් ඇති නොකරන්න +බොහෝ දුරට ප්‍රයෝජනවත් නොවනු ඇත, නමුත් කළ හැකි සරල දෙයක් සාදන්න +කාර්යය. පරිමාණය කිරීමේදී පමණක් රටා සංකීර්ණ කිරීම හා හඳුන්වා දීම අවශ්ය වේ +ඇත්තටම අවශ්යයි. + +ඔබ මෙම සංකල්ප ගැන හුරුපුරුදු වූ පසු, අධ්යයනය ආරම්භ කරන්න +[ලබා ගත හැකි නිර්මාණ රටා](https://java-design-patterns.com/patterns/) +පහත ක්‍රම වලින්: + +- නමින් සැකිල්ලක් සොයන්න. එකක් හොයාගන්න බැරි වුනාද? එය වාර්තා කරන්න [මෙහි](https://github.com/iluwatar/java-design-patterns/issues). +- `Performance`, `Gang of Four` හෝ `Data access` වැනි ටැග් භාවිතා කිරීම. +- සැකිලි කාණ්ඩ භාවිතා කිරීම `Creational`, `Behavioral` සහ වෙනත්. + + +මෙහි ඉදිරිපත් කර ඇති වෛෂයික-නැඹුරු විසඳුම් ඔබට ප්‍රයෝජනවත් වනු ඇතැයි අපි බලාපොරොත්තු වෙමු +ප්රයෝජනවත් වන අතර ඔබේ ව්යාපෘතිවල ස්ථානයක් සොයා ගනු ඇත, ඔබට එම සතුට ලැබෙනු ඇත +ඔවුන්ගේ සංවර්ධනයේදී අපට ලැබුණු අධ්‍යයනයෙන්. + +# සංවර්ධනයට සහභාගී වන්නේ කෙසේද +ඔබට ව්‍යාපෘතියේ ජීවිතයට සහභාගී වීමට අවශ්‍ය නම්, සියලු ප්‍රයෝජනවත් තොරතුරු ක්‍රියාත්මක වේ +අපගේ [wiki](https://github.com/iluwatar/java-design-patterns/wiki). අපිට උදව් කරන්න පුළුවන් +සහ [Gitter] කතාබස් (https://gitter.im/iluwatar/java-design-patterns) තුළ ඔබේ ප්‍රශ්නවලට පිළිතුරු දෙන්න. + +# බලපත්‍රය +ව්‍යාපෘතිය MIT බලපත්‍රයේ සාරාංශ මත පදනම් වේ. + diff --git a/localization/tr/README.md b/localization/tr/README.md new file mode 100644 index 000000000000..2effd99927c6 --- /dev/null +++ b/localization/tr/README.md @@ -0,0 +1,43 @@ + + +![Java CI with Maven](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI%20with%20Maven/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![All Contributors](https://img.shields.io/badge/all_contributors-148-orange.svg?style=flat-square)](#contributors-) + + +# Giriş + +Tasarım desenleri, bir yazılım mühendisi bir uygulamayı veya sistemi tasarlarken yaygın sorunları çözmek için kullanabileceği en iyi çözüm prensipleridir. + +Tasarım desenleri, test edilip kanıtlanmış prensipler olduğu için yazılım geliştirme sürecini hızlandırabilir. + +Tasarım desenlerini yeniden kullanmak, büyük sorunlara neden olan ince sorunları önlemeye yardımcı olur ve aynı zamanda tasarım desenlerine alışkın olan yazılım mühendisileri ve yazılım mimarları için kod okunabilirliğini artırır. + +# Başlangıç + +Bu site Java Tasarım Desenlerini sergiliyor. Çözümler, açık kaynak topluluğundan deneyimli yazılım mühendisileri ve yazılım mimarları tarafından geliştirilmiştir. Bu yazılım desenleri, detaylı açıklamalarıyla veya kaynak kodlarına bakılarak göz atılabilir. Kaynak kod örneklerinde iyi derecede açıklayıcı yorum satırlarına sahip olup ve belirli bir tasarım deseninin nasıl uygulanacağına dair programlama dersi olarak düşünülebilir. Savaşta en çok kanıtlanmış açık kaynak Java teknolojilerini kullanıyoruz. + +Bu projeye başlamadan önce çeşitli [Yazılım Tasarım İlkelerine](https://java-design-patterns.com/principles/) aşina olmalısınız. + +Tüm tasarımlar olabildiğince basit olmalıdır. [KISS](https://en.wikipedia.org/wiki/KISS_principle), [YAGNI](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it) ve [Do The Simplest Thing That Could Possibly Work](https://learning.oreilly.com/library/view/extreme-programming-pocket/9781449399849/ch17.html) ilkeleri ile başlamalısınız. + +Bu kavramlara aşina olduktan sonra, aşağıdaki yaklaşımlardan herhangi birini kullanarak [mevcut tasarım desenlerini](https://java-design-patterns.com/patterns/) derinlemesine incelemeye başlayabilirsiniz. + +- İsme göre belirli bir tasarım deseni arayın. Bulamadınız mı? Lütfen yeni bir tasarım deseni için [bizim ile](https://github.com/iluwatar/java-design-patterns/issues) iletişime geçin. +- Performance, Gang of Four ya da Data access gibi etiketleri kullanın. +- Creational(Yaratıcı Tasarım Desenleri), Behavioral(Davranışsal Tasarım Desenleri), ve Structural(Yapısal Tasarım Desenleri) gibi tasarım kategorilerini kullanın. + +Umarım bu sitede sunulan nesne yönelimli çözümleri yazılım mimarileriniz için yararlı bulursunuz ve onları geliştirirken bizim kadar eğlenirsiniz. + +# Nasıl Katkı Sağlayabilirim + +Projeye katkıda bulunmaya istekliysen, ilgili bilgileri [geliştirici wiki'mizde](https://github.com/iluwatar/java-design-patterns/wiki) bulabilirsin. [Gitter](https://gitter.im/iluwatar/java-design-patterns) ile size yardımcı olacağız ve sorularınızı cevaplayacağız. + +# Lisans + +Bu proje, MIT lisansı koşulları altında lisanslanmıştır. + diff --git a/localization/tr/singleton/README.md b/localization/tr/singleton/README.md new file mode 100644 index 000000000000..0c92b3692f68 --- /dev/null +++ b/localization/tr/singleton/README.md @@ -0,0 +1,85 @@ +--- +title: Singleton +category: Creational +language: tr +tag: +- Gang of Four +--- + +## Amaç + +Bir sınıfın yalnızca bir örneğine sahip olduğundan emin olun ve ona global bir erişim noktası sağlayın. + + +## Açıklama + +Örnek + +> Büyücülerin büyülerini çalıstıkları tek bir fildişi kule olabilir. Aynı büyülü fildişi kule, +> büyücüler tarafından her zaman kullanılır. Buradaki fildişi kulesi singleton tasarım desenine örnektir. +Özetle + +> Belirli bir sınıftan yalnızca bir nesnenin oluşturulmasını sağlar. +Wikipedia açıklaması + + + +> Yazılım mühendisliğinde, tekil desen, bir sınıfın somutlaştırılmasını tek bir nesneyle sınırlayan +> bir yazılım tasarım modelidir.Bu,sistemdeki eylemleri koordine etmek için +> tam olarak bir nesne gerektiğinde kullanışlıdır. +**Örnek** + +Joshua Bloch, Effective Java 2nd Edition p.18 + +> Enum singleton tasarım desenini uygulamak için en iyi yoldur. +```java +public enum EnumIvoryTower { + INSTANCE +} +``` + +Tanımladıktan sonra kullanmak için: + +```java +var enumIvoryTower1 = EnumIvoryTower.INSTANCE; +var enumIvoryTower2 = EnumIvoryTower.INSTANCE; +assertEquals(enumIvoryTower1, enumIvoryTower2); // true +``` + +## Sınıf diagramı + +![alt text](etc/singleton.urm.png) + +## Uygulanabilirlik + +Singleton tasarım deseni şu durumlarda kullanılmalıdır + +* Bir sınıfın tam olarak bir örneği olmalı ve iyi bilinen bir erişim noktasından istemciler tarafından erişilebilir olmalıdır. +* Tek örnek alt sınıflandırma yoluyla genişletilebilir olduğunda ve istemciler, kodlarını değiştirmeden genişletilmiş bir örnek kullanabilmelidir + +## Use Case + +* Logging sınıflarında +* Database bağlantılarını yönetmek için +* File manager + +## Gerçek dünya örnekleri + +* [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29) +* [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--) +* [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--) + + +## Sonuçlar + +* Kendi yaratımını ve yaşam döngüsünü kontrol ederek Tek Sorumluluk İlkesini (SRP) ihlal ediyor. +* Bu nesne tarafından kullanılan bir nesnenin ve kaynakların serbest bırakılmasını önleyen global bir paylaşılan örnek kullanmayı teşvik eder. +* Birbirine sıkı bağlı kod oluşturur. Singleton tasarım deseni kullanan istemci sınıflarını test etmek zorlaşır. +* Bir Singleton tasarım deseninden alt sınıflar oluşturmak neredeyse imkansız hale gelir. + +## Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) \ No newline at end of file diff --git a/localization/tr/singleton/etc/singleton.urm.png b/localization/tr/singleton/etc/singleton.urm.png new file mode 100644 index 000000000000..46584af40039 Binary files /dev/null and b/localization/tr/singleton/etc/singleton.urm.png differ diff --git a/localization/ur/README.md b/localization/ur/README.md new file mode 100644 index 000000000000..6241f76c1a77 --- /dev/null +++ b/localization/ur/README.md @@ -0,0 +1,63 @@ + + +# جاوا میں لاگو ڈیزائن پیٹرن + +![Java CI](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) +[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) +[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + + + +[![All Contributors](https://img.shields.io/badge/all_contributors-213-orange.svg?style=flat-square)](#contributors-) + + + +# تعارف + +ڈیزائن پیٹرن بہترین، باضابطہ طریقے ہیں جو ایک پروگرامر ایپلی کیشن یا سسٹم کو ڈیزائن کرتے وقت عام مسائل کو حل کرنے کے لیے استعمال کر سکتا ہے۔ + +ڈیزائن کے نمونے آزمائشی، ثابت شدہ ترقیاتی نمونے فراہم کرکے ترقی کے عمل کو تیز کر سکتے ہیں۔ + +ڈیزائن کے نمونوں کو دوبارہ استعمال کرنے سے ان لطیف مسائل کو روکنے میں مدد ملتی ہے جو بڑے مسائل کا باعث بنتے ہیں، اور یہ کوڈرز اور معماروں کے لیے کوڈ پڑھنے کی اہلیت کو بھی بہتر بناتا ہے جو پیٹرن سے واقف ہیں۔ + +# شروع کرتے ہیں + +یہ سائٹ جاوا ڈیزائن پیٹرنز کی نمائش کرتی ہے۔ حل اوپن سورس کمیونٹی کے تجربہ کار پروگرامرز اور آرکیٹیکٹس کے ذریعہ تیار کیے گئے ہیں۔ پیٹرن کو ان کی اعلیٰ سطحی وضاحت یا ان کے سورس کوڈ کو دیکھ کر براؤز کیا جا سکتا ہے۔ سورس کوڈ کی مثالوں پر اچھی طرح تبصرہ کیا گیا ہے اور ان کو پروگرامنگ ٹیوٹوریل کے طور پر سوچا جا سکتا ہے کہ کسی مخصوص پیٹرن کو کیسے نافذ کیا جائے۔ ہم سب سے مشہور جنگ سے ثابت شدہ اوپن سورس جاوا ٹیکنالوجیز استعمال کرتے ہیں۔ + +مواد میں غوطہ لگانے سے پہلے، آپ کو مختلف اصولوں سے واقف ہونا چاہیے۔ + +[سافٹ ویئر ڈیزائن کے اصول](https://java-design-patterns.com/patterns/) + +تمام ڈیزائن ممکنہ حد تک آسان ہونے چاہئیں۔ + +آپ کو KISS، YAGNI، اور سب سے آسان کام کرنا چاہیے جو ممکنہ طور پر اصولوں پر کام کر سکے۔ + +پیچیدگی اور نمونوں کو صرف اس وقت متعارف کرایا جانا چاہئے جب ان کی عملی توسیع کے لئے ضرورت ہو۔ + +ایک بار جب آپ ان تصورات سے واقف ہو جائیں تو آپ مندرجہ ذیل طریقوں میں سے کسی کے [دستیاب ڈیزائن پیٹرن](https://java-design-patterns.com/patterns/) کے نمونوں میں ڈرلنگ شروع کر سکتے ہیں۔ + +⚪ نام سے مخصوص پیٹرن تلاش کریں۔ ایک نہیں مل سکتا؟ براہ کرم ایک نئے پیٹرن کی اطلاع دیں۔ [یہاں](https://github.com/iluwatar/java-design-patterns/issues). + + ⚪ کارکردگی'، 'گینگ آف فور' یا 'ڈیٹا تک رسائی' جیسے ٹیگز کا استعمال۔ + + ⚪ پیٹرن کے زمرے استعمال کرنا، 'تخلیقی'، 'رویے'، اور دیگر۔ + +امید ہے کہ، آپ کو اس سائٹ پر پیش کردہ آبجیکٹ پر مبنی حل کارآمد معلوم ہوں گے۔ +اپنے فن تعمیرات میں اور ان کو سیکھنے میں اتنا ہی مزہ کریں جتنا ہم نے انہیں تیار کرتے وقت کیا تھا۔ + +# شراکت کیسے کریں + +اگر آپ پروجیکٹ میں حصہ ڈالنے کے لیے تیار ہیں تو آپ کو متعلقہ معلومات مل جائیں گی۔ +ہمارے [ڈویلپر ویکی](https://github.com/iluwatar/java-design-patterns/wiki). ہم مدد کریں گے۔ آپ اور میں آپ کے سوالات کے جوابات [گیٹر چیٹ روم](https://gitter.im/iluwatar/java-design-patterns). + + +# لائسنس + +یہ پروجیکٹ MIT لائسنس کی شرائط کے تحت لائسنس یافتہ ہے۔ + + + diff --git a/localization/ur/abstract-document/README.md b/localization/ur/abstract-document/README.md new file mode 100644 index 000000000000..e8711f6ea687 --- /dev/null +++ b/localization/ur/abstract-document/README.md @@ -0,0 +1,176 @@ +--- +title: Abstract Document +category: Structural +language: ur +tag: + - Extensibility +--- + +## ارادہ + +متحرک خصوصیات کا استعمال کریں اور ٹائپ سیفٹی کو برقرار رکھتے ہوئے غیر ٹائپ شدہ زبانوں کی لچک حاصل کریں۔ + +## وضاحت + +خلاصہ دستاویز کا پیٹرن اضافی، غیر جامد خصوصیات کو سنبھالنے کے قابل بناتا ہے۔ یہ پیٹرن قسم کی حفاظت اور مختلف کلاسوں کی الگ الگ خصوصیات کو انٹرفیس کے سیٹ میں فعال کرنے کے لیے خصلتوں کے تصور کا استعمال کرتا ہے۔ + +حقیقی مثال + +> ایک ایسی کار پر غور کریں جو متعدد حصوں پر مشتمل ہو۔ تاہم ہم نہیں جانتے کہ آیا مخصوص کار میں واقعی تمام پرزے ہیں یا ان میں سے کچھ ۔ ہماری کاریں متحرک اور انتہائی لچکدار ہیں۔ + +صاف لفظوں میں + +> خلاصہ دستاویز کا پیٹرن اشیاء کے بارے میں جانے بغیر خصوصیات کو منسلک کرنے کی اجازت دیتا ہے۔ + +ویکیپیڈیا کہتا ہے۔ + +> ڈھیلے ٹائپ شدہ کلیدی قدر والے اسٹورز میں اشیاء کو منظم کرنے اور ٹائپ شدہ نظاروں کا استعمال کرتے ہوئے ڈیٹا کو ظاہر کرنے کے لیے آبجیکٹ پر مبنی ساختی ڈیزائن کا نمونہ۔ پیٹرن کا مقصد اجزاء کے درمیان اعلی درجے کی لچک حاصل کرنا ہے۔ +سختی سے ٹائپ کی گئی زبان میں جہاں قسم کی حفاظت کی حمایت کو کھونے کے بغیر، فلائی پر آبجیکٹ ٹری میں نئی خصوصیات شامل کی جا سکتی ہیں۔پیٹرن کلاس کی مختلف خصوصیات کو مختلف انٹرفیس میں الگ کرنے کے لیے خصلتوں کا استعمال کرتا ہے۔ + +**پروگرامی مثال** + +آئیے پہلے بیس کلاسز `Document` اور `AbstractDocument` کی وضاحت کرتے ہیں۔ +وہ بنیادی طور پر آبجیکٹ کو پراپرٹی کا نقشہ اور کسی بھی مقدار میں چائلڈ آبجیکٹ رکھتے ہیں۔ + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + ... +} +``` +اس کے بعد ہم ایک enum `Property` اور type, price, model اور parts کے لئے انٹرفیس کا ایک سیٹ بیان کرتے ہیں۔ یہ ہمیں تخلیق کرنے کی اجازت دیتا ہے۔ +ہماری `Car` کلاس میں جامد نظر آنے والا انٹرفیس۔ + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} +``` +اب ہم 'کار' متعارف کرانے کے لیے تیار ہیں۔ + +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` + +اور آخر کار یہ ہے کہ ہم ایک مکمل مثال میں 'کار' کو کیسے بناتے اور استعمال کرتے ہیں۔ + +```java + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); + + +``` + +## کلاس ڈایاگرام + +![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain") + +## استعمال + +خلاصہ دستاویز کا پیٹرن استعمال کریں جب - + +* نئ پراپرٹیز آن دی فلائی شامل کرنے کی ضرورت ہے۔ +* آپ ڈھانچے جیسے درخت میں ڈومین کو منظم کرنے کا ایک لچکدار طریقہ چاہتے ہیں۔ +* آپ کو زیادہ ڈھیلا ڈھالا نظام چاہتے ہیں۔ + +## کریڈٹ + +* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492) \ No newline at end of file diff --git a/localization/ur/abstract-factory/README.md b/localization/ur/abstract-factory/README.md new file mode 100644 index 000000000000..0da565ca3b0e --- /dev/null +++ b/localization/ur/abstract-factory/README.md @@ -0,0 +1,224 @@ +--- +title: Abstract Factory +category: Creational +language: ur +tag: + - Gang of Four +--- + +## اس نام سے بہی جانا جاتاہے + +کٹ + +## ارادہ +متعلقہ یا منحصر خاندانوں کو بنانے کے لیے ایک انٹرفیس فراہم کریں۔ +اشیاء کو ان کی ٹھوس کلاسوں کی وضاحت کیے بغیر۔ + +## وضاحت + +حقیقی مثال + +> ایک سلطنت بنانے کے لیے ہمیں ایک مشترکہ تھیم والی اشیاء کی ضرورت ہے۔ ایلوین بادشاہی کو ایلون بادشاہ، ایلون قلعہ، اور ایلوین فوج کی ضرورت ہوتی ہے جبکہ آرکیش بادشاہی کو ایک اورش بادشاہ، اورکش قلعہ، اور آرکیش فوج کی ضرورت ہوتی ہے۔ بادشاہی میں اشیاء کے درمیان انحصار ہے۔ + +صاف لفظوں میں + +> کارخانوں کا ایک کارخانہ؛ ایک فیکٹری جو انفرادی لیکن متعلقہ/انحصار کارخانوں کو ان کی کنکریٹ کلاسز کی وضاحت کیے بغیر ایک ساتھ گروپ کرتی ہے۔ + +ویکیپیڈیا کہتا ہے۔ + +> تجریدی فیکٹری پیٹرن انفرادی فیکٹریوں کے ایک گروپ کو سمیٹنے کا ایک طریقہ فراہم کرتا ہے جن کی کنکریٹ کلاسز کی وضاحت کیے بغیر ایک مشترکہ تھیم ہے۔ + +**پروگرامی مثال** + +اوپر کی بادشاہی کی مثال کا ترجمہ کرنا۔ سب سے پہلے، ہمارے پاس بادشاہی میں موجود اشیاء کے لیے کچھ انٹرفیس اور نفاذ ہیں۔ + +```java +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 -> ... + +``` + +پھر ہمارے پاس کنگڈم فیکٹری کے لیے تجرید اور نفاذات ہیں۔ + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +اب ہمارے پاس ایک تجریدی کارخانہ ہے جو ہمیں متعلقہ اشیاء کا ایک خاندان بنانے دیتا ہے یعنی ایلون کنگڈم فیکٹری ایلوین قلعہ، بادشاہ اور فوج وغیرہ بناتی ہے۔ + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +پروگرام آؤٹ پٹ: + +```java +This is the elven castle! +This is the elven king! +This is the elven Army! +``` +اب، ہم اپنی مختلف بادشاہی فیکٹریوں کے لیے ایک فیکٹری ڈیزائن کر سکتے ہیں۔ اس مثال میں، ہم نے `FactoryMaker` بنایا، جو کہ `ElfKingdomFactory` یا `OrcKingdomFactory` کی مثال واپس کرنے کے لئے ذمہ دار ہے۔ +کلائنٹ مطلوبہ کنکریٹ فیکٹری بنانے کے لیے 'فیکٹری میکر' کا استعمال کر سکتا ہے جو بدلے میں مختلف کنکریٹ اشیاء ('آرمی'، 'کنگ'، 'کیسل' سے ماخوذ) تیار کرے گا۔ +اس مثال میں، ہم نے پیرامیٹرائز کرنے کے لیے ایک اینوم بھی استعمال کیا کہ کلائنٹ کس قسم کی بادشاہی فیکٹری طلب کرے گا۔ + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + default -> throw new IllegalArgumentException("KingdomType not supported."); + }; + } +} + + public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + --similar use of the orc factory + } +``` + +## کلاس ڈایاگرام + +![alt text](./etc/abstract-factory.urm.png "Abstract Factory class diagram") + +## استعمال + +خلاصہ فیکٹری پیٹرن کا استعمال کریں جب. + +* نظام کو اس بات سے آزاد ہونا چاہئے کہ اس کی مصنوعات کی تخلیق، تشکیل اور نمائندگی کیسے کی جاتی ہے۔ +* سسٹم کو مصنوعات کے متعدد خاندانوں میں سے ایک کے ساتھ ترتیب دیا جانا چاہئے۔ +* متعلقہ مصنوعات کی اشیاء کے خاندان کو ایک ساتھ استعمال کرنے کے لیے ڈیزائن کیا گیا ہے، اور آپ کو اس پابندی کو نافذ کرنے کی ضرورت ہے۔ +* آپ مصنوعات کی کلاس لائبریری فراہم کرنا چاہتے ہیں، اور آپ صرف ان کے انٹرفیس کو ظاہر کرنا چاہتے ہیں، ان کے نفاذ کو نہیں۔ +* انحصار کی زندگی تصوراتی طور پر صارف کی زندگی سے کم ہوتی ہے۔ +* کسی خاص انحصار کی تعمیر کے لیے آپ کو رن ٹائم ویلیو کی ضرورت ہے۔ +* آپ فیصلہ کرنا چاہتے ہیں کہ رن ٹائم کے وقت فیملی سے کس پروڈکٹ کو کال کرنا ہے۔ +* انحصار کو حل کرنے سے پہلے آپ کو ایک یا زیادہ پیرامیٹرز فراہم کرنے کی ضرورت ہے جو صرف رن ٹائم پر معلوم ہوتے ہیں۔ +* جب آپ کو مصنوعات کے درمیان مستقل مزاجی کی ضرورت ہو۔ +* پروگرام میں نئی مصنوعات یا مصنوعات کے خاندانوں کو شامل کرتے وقت آپ موجودہ کوڈ کو تبدیل نہیں کرنا چاہتے۔ + + مثال کے طور پر استعمال کے معاملات + + * رن ٹائم پر FileSystemAcmeService یا DatabaseAcmeService یا NetworkAcmeService کے مناسب نفاذ کے لیے کال کرنے کا انتخاب کرنا۔ + * یونٹ ٹیسٹ کیس لکھنا بہت آسان ہو جاتا ہے۔ + * مختلف OS کے لیے UI ٹولز + ## نتائج + + * جاوا میں انحصار کا انجیکشن سروس کلاس کے انحصار کو چھپاتا ہے جو رن ٹائم کی غلطیوں کا باعث بن سکتا ہے جو مرتب وقت پر پکڑا جاتا۔ +* اگرچہ پہلے سے طے شدہ اشیاء بناتے وقت پیٹرن بہت اچھا ہوتا ہے، نئی چیزوں کو شامل کرنا مشکل ہوسکتا ہے۔ +* کوڈ اس سے کہیں زیادہ پیچیدہ ہو جاتا ہے کیونکہ پیٹرن کے ساتھ بہت سارے نئے انٹرفیس اور کلاسز متعارف کرائے جاتے ہیں۔ + +## سبق + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## معروف استعمال + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## متعلقہ پیٹرن + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## کریڈٹس + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) \ No newline at end of file diff --git a/localization/ur/active-object/README.md b/localization/ur/active-object/README.md new file mode 100644 index 000000000000..0535fc42ceba --- /dev/null +++ b/localization/ur/active-object/README.md @@ -0,0 +1,127 @@ +--- +title: Active Object +category: Concurrency +language: en +tag: + - Performance +--- + +## ارادہ + +فعال آبجیکٹ ڈیزائن پیٹرن ان اشیاء کے لیے طریقہ کار کی درخواست سے طریقہ کار پر عمل درآمد کو الگ کرتا ہے جو ہر ایک اپنے کنٹرول کے دھاگے میں رہتی ہے۔ +مقصد یہ ہے کہ ہم آہنگی کو متعارف کرایا جائے، غیر مطابقت پذیر طریقہ کی درخواست کا استعمال کرتے ہوئے، اور درخواستوں کو ہینڈل کرنے کے لیے شیڈولر۔ + +## وضاحت + +کلاس جو فعال آبجیکٹ پیٹرن کو نافذ کرتی ہے اس میں 'مطابقت پذیر' طریقوں کا استعمال کیے بغیر خود ہم آہنگی کا طریقہ کار ہوگا۔ + +حقیقی مثال + +> آرکس اپنی جنگلی پن اور ناقابل تسخیر روح کے لیے مشہور ہیں۔ ایسا لگتا ہے کہ پچھلے رویے کی بنیاد پر ان کے پاس کنٹرول کا اپنا دھاگہ ہے۔ + +ایک ایسی مخلوق کو نافذ کرنے کے لیے جس کا کنٹرول میکانزم کا اپنا دھاگہ ہے اور اس کے API کو صرف اور صرف عمل درآمد کو ظاہر نہیں کرتا ہے، ہم Active Object پیٹرن استعمال کر سکتے ہیں۔ + +**پروگرامی مثال** + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +ہم دیکھ سکتے ہیں کہ کوئی بھی کلاس جو ActiveCreature کلاس میں توسیع کرے گی اس کے پاس طریقوں کو استعمال کرنے اور اس پر عمل کرنے کے لیے اپنا کنٹرول کا دھاگہ ہوگا۔ + +مثال کے طور پر، Orc کلاس: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` + +اب، ہم Orcs جیسی متعدد مخلوقات بنا سکتے ہیں، انہیں کھانے اور گھومنے کو کہہ سکتے ہیں، اور وہ اسے اپنے کنٹرول کے اپنے دھاگے پر عمل میں لائیں گے: + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## کلاس ڈایاگرام + +![alt text](./etc/active-object.urm.png "Active Object class diagram") + +## سبق + +* [Android and Java Concurrency: The Active Object Pattern](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) \ No newline at end of file diff --git a/localization/ur/acyclic-visitor/README.md b/localization/ur/acyclic-visitor/README.md new file mode 100644 index 000000000000..6c9d651fc720 --- /dev/null +++ b/localization/ur/acyclic-visitor/README.md @@ -0,0 +1,166 @@ +--- +title: Acyclic Visitor +category: Behavioral +language: ur +tag: + - Extensibility +--- + +## ارادہ + +ان درجہ بندیوں کو متاثر کیے بغیر، اور تخلیق کیے بغیر، موجودہ طبقاتی درجہ بندی میں نئے فنکشنز کو شامل کرنے کی اجازت دیں +پریشان کن انحصار سائیکل جو GoF وزیٹر پیٹرن میں شامل ہیں۔ + +## وضاحت + +حقیقی مثال + +> ہمارے پاس موڈیم کلاسز کا درجہ بندی ہے۔ اس درجہ بندی میں موڈیمز کو ایک بیرونی الگورتھم کی بنیاد پر دیکھنے کی ضرورت ہے۔ +فلٹرنگ کے معیار پر (کیا یہ یونکس ہے یا DOS کے موافق موڈیم)۔ + +صاف لفظوں میں + +> Acyclic Visitor درجہ بندی میں ترمیم کیے بغیر فنکشنز کو موجودہ طبقاتی درجہ بندی میں شامل کرنے کی اجازت دیتا ہے۔ + +[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) کہتے ہیں + +> Acyclic پیٹرن ان کو درجہ بندی میں فرق صرف موجودہ طبقاتی میں فنکشنز کو شامل کرنے کی اجازت دیتا ہے۔ + +> درجہ بندی، اور انحصار سائیکل بنائے بغیر جو کہ GangOfFour VisitorPattern میں موروثی ہیں۔ + +**پروگرامی مثال** + +یہ ہے `موڈیم` درجہ بندی۔ + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + +اس کے بعد ہم 'ModemVisitor' کا درجہ بندی متعارف کراتے ہیں۔ + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + ... + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + ... + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +آخر میں، یہاں ایکشن میں زائرین ہیں. + + +```java + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + var zoom = new Zoom(); + var hayes = new Hayes(); + hayes.accept(conDos); + zoom.accept(conDos); + hayes.accept(conUnix); + zoom.accept(conUnix); +``` + +پروگرام آؤٹ پٹ: + +``` + // Hayes modem used with Dos configurator. + // Zoom modem used with Dos configurator. + // Only HayesVisitor is allowed to visit Hayes modem + // Zoom modem used with Unix configurator. +``` + +## کلاس ڈایاگرام + +![alt text](./etc/acyclic-visitor.png "Acyclic Visitor") + +## استعمال + +یہ پیٹرن استعمال کیا جا سکتا ہے: + +* جب آپ کو کسی موجودہ درجہ بندی میں ایک نیا فنکشن شامل کرنے کی ضرورت ہو بغیر اس درجہ بندی کو تبدیل کرنے یا متاثر کرنے کی ضرورت۔ +* جب ایسے افعال ہوتے ہیں جو درجہ بندی پر کام کرتے ہیں، لیکن ان کا تعلق خود درجہ بندی میں نہیں ہوتا ہے۔ جیسے ConfigureForDOS / ConfigureForUnix / ConfigureForX مسئلہ۔ +* جب آپ کو کسی چیز پر اس کی قسم کے لحاظ سے بہت مختلف آپریشن کرنے کی ضرورت ہوتی ہے۔ +* جب ملاحظہ کردہ کلاس کے درجہ بندی کو عنصر کلاس کے نئے مشتقات کے ساتھ کثرت سے بڑھایا جائے گا۔ +* جب عنصر کے مشتقات کو دوبارہ مرتب کرنا، دوبارہ لنک کرنا، دوبارہ جانچنا یا دوبارہ تقسیم کرنا بہت مہنگا ہوتا ہے۔ + +## ٹیوٹوریل + +* [Acyclic Visitor Pattern Example](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) + +## نتائج + +اچھائی: + +* طبقاتی درجہ بندی کے درمیان کوئی انحصار سائیکل نہیں ہے۔ +* اگر کوئی نیا شامل کیا جائے تو تمام زائرین کو دوبارہ مرتب کرنے کی ضرورت نہیں ہے۔ +* اگر کلاس کے درجہ بندی میں کوئی نیا ممبر ہے تو موجودہ زائرین میں تالیف کی ناکامی کا سبب نہیں بنتا ہے۔ + +برائی: + + * خلاف ورزی کرتا ہے۔ [Liskov's Substitution Principle](https://java-design-patterns.com/principles/#liskov-substitution-principle) + یہ ظاہر کر کے کہ یہ تمام زائرین کو قبول کر سکتا ہے لیکن اصل میں صرف خاص مہمانوں میں دلچسپی رکھتا ہے۔ +* ملاحظہ کرنے کے قابل طبقاتی درجہ بندی میں تمام اراکین کے لیے زائرین کا متوازی درجہ بندی بنانا ضروری ہے۔ + + ## متعلقہ پیٹرن + + [Visitor Pattern](https://java-design-patterns.com/patterns/visitor/) + + + کریڈٹس + + * [Acyclic Visitor by Robert C. Martin](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor in WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) \ No newline at end of file diff --git a/localization/vi/README.md b/localization/vi/README.md new file mode 100644 index 000000000000..ba12faaa2c91 --- /dev/null +++ b/localization/vi/README.md @@ -0,0 +1,43 @@ +# Mẫu thiết kế được hiện thực bằng Java + +# Giới thiệu + +Mẫu thiết kế là phương pháp tốt nhất, được chuẩn hóa mà một lập trình viên có thể sử dụng để giải quyết các vấn đề chung khi thiết kế một ứng dụng hoặc hệ thống. + +Mẫu thiết kế có thể đẩy nhanh quá trình phát triển bằng cách cung cấp các mô hình đã được kiểm nghiệm, chứng minh. + +Việc sử dụng lại các mẫu thiết kế giúp phòng ngừa các vấn đề tiềm ẩn có thể xảy ra và nó cũng cải thiện khả năng đọc hiểu mã nguồn cho các lập trình viên và người thiết kế hệ thống đã quen thuộc với các mẫu đó. + +# Mở đầu + +Trang web này giới thiệu các mẫu thiết kế được hiện thực bằng Java. Các giải pháp này đã được phát triển +bởi các lập trình viên và người thiết kế có kinh nghiệm từ cộng đồng mã nguồn mở. +Bạn có thể tham khảo các mẫu thông qua mô tả cấp cao hoặc mã nguồn của chúng. +Các mã nguồn mẫu được giải thích đầy đủ và được coi là hướng dẫn trực quan về cách triển khai một mẫu thiết kế cụ thể. +Chúng tôi cũng sử dụng các công nghệ Java nguồn mở đã được chứng minh thực chiến phổ biến nhất. + +Trước khi đào sâu vào tài liệu, bạn nên làm quen với những +[quy tắc thiết kế](https://java-design-patterns.com/principles/). + +Tất cả các thiết kế nên đơn giản nhất có thể. +Bạn nên bắt đầu với KISS, YAGNI, và Làm-Thứ-Đơn-Giản-Nhất-Mà-Giải-Quyết-Vấn-Đề (Do-The-Simplest-Thing-That-Could-Possibly-Work). +Sự phức tạp và các mẫu chỉ được thêm vào khi chúng thực sự cần cho sự mở rộng về sau. + +Một khi đã quen với các khái niệm, bạn có thể bắt đầu đào sâu +[các mẫu thiết kế hiện có](https://java-design-patterns.com/patterns/) +bằng các cách tiếp cận sau + + - Tìm kiếm một mẫu thiết kế cụ thể bằng tên. Nếu không tìm thấy, vui lòng yêu cầu một mẫu mới [ở đây](https://github.com/iluwatar/java-design-patterns/issues). + - Sử dụng đánh dấu (tag) như `Performance`, `Gang of Four` hoặc `Data access`. + - Sử dụng danh mục như `Creational`, `Behavioral`, vân vân. + +Mong rằng những giải pháp hướng đối tượng ở đây sẽ mang lại lợi ích công việc cũng như niềm vui học tập cho bạn, giống như chúng tôi đã và đang được trải nghiệm trong quá trình phát triển chúng. + +# Đóng góp + +Nếu bạn mong muốn đóng góp cho dự án, bạn có thể tìm kiếm thông tin liên quan ở [wiki cho nhà phát triển](https://github.com/iluwatar/java-design-patterns/wiki). +Chúng tôi sẽ giúp trả lời câu hỏi của bạn ở [Gitter](https://gitter.im/iluwatar/java-design-patterns). + +# Giấy phép + +Dự án này được cấp phép theo các điều khoản của giấy phép MIT. diff --git a/localization/vi/abstract-document/README.md b/localization/vi/abstract-document/README.md new file mode 100644 index 000000000000..4648822b8db0 --- /dev/null +++ b/localization/vi/abstract-document/README.md @@ -0,0 +1,185 @@ +--- +title: Abstract Document +category: Structural +language: vi +tag: + - Extensibility +--- + +## Mục tiêu + +Tận dụng thuộc tính và khả năng linh động của các ngôn ngữ không định kiểu trong khi vẫn giữ được đặc tính an toàn kiểu. + +## Giải thích + +Tài Liệu Trừu Tượng (thuật ngữ tiếng Anh: Abstract Document) là mẫu cho phép sử dụng các thuộc tính bổ sung, không tĩnh. +Mẫu này sử dụng khái niệm "đặc tính" (thuật ngữ gốc: "trait") để cho phép an toàn kiểu và phân tách thuộc tính của các lớp (class) khác nhau thành các tập giao diện (interface). + +Ví dụ thực tế + +> Chiếc ô tô có thể bao gồm nhiều thành phần. Tuy nhiên, chúng ta không biết liệu một chiếc ô tô cụ thể có thể chứa những thành phần nào, tất cả hay chỉ một vài thành phần nhất định. Có thể nói rằng, những chiếc ô tô này là động và rất linh hoạt. + +Một cách đơn giản + +> Mẫu tài liệu trừu tượng cho phép cấy thêm thuộc tính vào đối tượng mà không để cho nó biết về điều đó. + +Wikipedia viết (tạm dịch) + +> Là mẫu hướng đối tượng loại cấu trúc dùng để tổ chức các đối tượng theo dạng lưu trữ khóa-giá trị và phơi bày dữ liệu dưới dạng định kiểu. Mục đích của mẫu này là để đạt được khả năng linh hoạt cao giữa các thành phần trong ngôn ngữ định kiểu mạnh, nơi mà những thuộc tính mới có thể được thêm vào cây đối tượng một cách linh hoạt (trong khi chạy chương trình), nhưng vẫn giữ được sự hỗ trợ của an toàn kiểu. Mẫu này sử dụng khái niệm "đặc tính" (thuật ngữ gốc: "trait") để phân tách thuộc tính của các lớp (class) thành các tập giao diện (interface). + + +**Chương trình ví dụ** + +Đầu tiên, định nghĩa lớp cơ sở `Document` và `AbstractDocument`. +2 lớp này định nghĩa đối tượng sẽ giữ bảng thuộc tính và các đối tượng con có kiểu bất kì. + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + ... +} +``` + +Tiếp theo, chúng ta định nghĩa một enum `Property` và một tập các interface cho thuộc tính: `type`, `price`, `model`, `parts`. +Điều này cho phép ta tạo ra một giao diện tĩnh cho lớp `Car`. + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} +``` + +Bây giờ, chúng ta đã sẵn sàng cho lớp `Car`. + +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` + +Và cuối cùng là cách khởi tạo và sử dụng `Car` trong một ví dụ hoàn chỉnh. + +```java + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); + + // Constructing parts and car + // Here is our car: + // model: 300SL + // price: 10000 + // parts: + // wheel/15C/100 + // door/Lambo/300 +``` + +## Sơ đồ lớp + +![alt text](../../../abstract-document/etc/abstract-document.png "Abstract Document Traits and Domain") + +## Ứng dụng + +Sử dụng mẫu Tài Liệu Trừu Tượng khi + +* Có nhu cầu thêm các thuộc tính mới trong lúc chạy (khái niệm gốc: "on the fly") +* Muốn có khả năng linh hoạt trong tổ chức nghiệp vụ dưới dạng sơ đồ cây +* Muốn hệ thống lỏng lẻo hơn + +## Tham khảo + +* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492) diff --git a/localization/vi/abstract-factory/README.md b/localization/vi/abstract-factory/README.md new file mode 100644 index 000000000000..4e5ec0b9acf3 --- /dev/null +++ b/localization/vi/abstract-factory/README.md @@ -0,0 +1,227 @@ +--- +title: Abstract Factory +category: Creational +language: vi +tag: + - Gang of Four +--- + +## Còn được biết đến như + +Kit + +## Mục tiêu + +Cung cấp giao diện (interface) để khởi tạo các đối tượng liên quan +hoặc có phụ thuộc mà không cần chỉ định các lớp cụ thể của chúng. + +## Giải thích + +Nhà Máy Trừu Tượng (thuật ngữ tiếng Anh: Abstract Factory). + +Ví dụ thực tế + +> Để tạo ra một vương quốc, chúng ta cần các đối tượng có chủ đề chung. Vương quốc Elf cần một vị vua Elf, lâu đài Elf và quân đội Elf trong khi vương quốc Orc cần một vị vua Orc, lâu đài Orc và quân đội Orc. Các đối tượng trong vương quốc phụ thuộc lẫn nhau. + +Một cách đơn giản + +> Một nhà máy của nhiều nhà máy; một nhà máy nhóm các nhà máy riêng lẻ nhưng có liên quan hoặc phụ thuộc lại với nhau mà không chỉ định các lớp cụ thể của chúng. + +Wikipedia viết (tạm dịch) + +> Mẫu Nhà Máy Trừu Tượng cung cấp cách làm để đóng gói một nhóm các nhà máy riêng lẻ có chủ đề chung mà không cần chỉ định các lớp cụ thể của chúng + +**Chương trình ví dụ** + +Sử dụng ví dụ về vương quốc đã nêu ở trên. +Trước hết, chúng ta có một số giao diện (interface) và lớp (class) được hiện thực hóa cho các đối tượng trong vương quốc. + +```java +public interface Castle { + String getDescription(); +} + +public interface King { + String getDescription(); +} + +public interface Army { + String getDescription(); +} + +// Hiện thực hóa tộc Elf -> +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; + } +} + +// Tương tự, hiện thực hóa tộc Orc -> ... + +``` + +Sau đó, chúng ta có trừu tượng hóa và hiện thực hóa cho nhà máy vương quốc. + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +Bây giờ, chúng ta có Nhà Máy Trừu Tượng cho phép chúng ta tạo một nhóm các đối tượng liên quan, tức là nhà máy vương quốc Elf tạo ra lâu đài, vua và quân đội của tộc Elf, v.v. + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +Đầu ra khi chạy chương trình: + +```java +This is the elven castle! +This is the elven king! +This is the elven Army! +``` + +Bây giờ, chúng ta có thể thiết kế một nhà máy cho các nhà máy vương quốc khác nhau. Trong ví dụ này, chúng tôi đã tạo `FactoryMaker`, chịu trách nhiệm trả về một thể hiện của` ElfKingdomFactory` hoặc `OrcKingdomFactory`. +Người dùng có thể sử dụng `FactoryMaker` để tạo ra nhà máy mà họ mong muốn, sau đó, `FactoryMaker` sẽ tạo ra các đối tượng cụ thể (là dẫn xuất của `Army`, `King`, `Castle`). +Trong ví dụ này, chúng tôi cũng sử dụng một enum để tham số hóa các loại nhà máy vương quốc mà khách hàng sẽ yêu cầu. + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + default -> throw new IllegalArgumentException("KingdomType not supported."); + }; + } +} + + public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + --Tương tự với nhà máy Orc + } +``` + +## Sơ đồ lớp + +![alt text](../../../abstract-factory/etc/abstract-factory.urm.png "Abstract Factory class diagram") + +## Ứng dụng +Sử dụng mẫu Nhà Máy Trừu Tượng khi + +* Hệ thống nên độc lập với cách mà nó khởi tạo/kết hợp/trình bày sản phẩm của nó. +* Hệ thống nên được cấu hình với một trong các họ sản phẩm. +* Họ của các đối tượng sản phẩm được thiết kế để sử dụng cùng nhau, và bạn cần áp đặt ràng buộc này. +* Bạn muốn cung cấp một thư viện lớp các sản phẩm, và bạn chỉ muốn tiết lộ giao diện (interface), ẩn giấu hiện thực hóa của chúng. +* Thời gian tồn tại của đối tượng phụ thuộc thì ngắn hơn thời gian tồn tại của đối tượng sử dụng. +* Bạn cần một/vài giá trị trong lúc chạy để khởi tạo một/vài đối tượng phụ thuộc cụ thể. +* Bạn muốn quyết định sản phẩm nào được gọi từ một họ trong lúc chạy. +* Bạn cần tính nhất quán giữa các sản phẩm. +* Bạn không muốn sửa mã nguồn khi thêm những sản phẩm mới hoặc họ của các sản phẩm vào chương trình. + +Ví dụ về ca sử dụng + +* Lựa chọn để gọi đến hiện thực hóa phù hợp của FileSystemAcmeService hoặc DatabaseAcmeService hoặc NetworkAcmeService trong lúc thực thi. +* Kiểm thử đơn vị trở nên cực kì dễ dàng. +* Công cụ giao diện cho các hệ điều hành khác nhau. + +## Hệ quả + +* Sự tiêm phụ thuộc (dependency injection) trong Java che đậy các lớp dịch vụ phụ thuộc nên nó có thể dẫn tới lỗi trong quá trình thực thi, điều mà lẽ ra có thể bắt được trong quá trình biên dịch. +* Trong khi mẫu này sử dụng hiệu quả với các đối tượng đã được định nghĩa sẵn, thêm một/vài đối tượng mới có thể sẽ khó khăn. +* Mã nguồn trở nên phức tạp hơn do nó có thêm giao diện (interface) và lớp (class) được giới thiệu đi kèm theo mẫu. + +## Hướng dẫn + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## Thông dụng + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## Mẫu liên quan + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## Tham khảo +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/vi/active-object/README.md b/localization/vi/active-object/README.md new file mode 100644 index 000000000000..fefed3903c4c --- /dev/null +++ b/localization/vi/active-object/README.md @@ -0,0 +1,127 @@ +--- +title: Active Object +category: Concurrency +language: vi +tag: + - Performance +--- + +## Mục tiêu + +Mẫu Đối Tượng Chủ Động (tiếng Anh: Active Object) chia tách việc thực thi hàm khỏi lời gọi hàm cho các đối tượng mà mỗi đối tượng nằm trong luồng điều khiển của chúng. +Mục tiêu là tận dụng khả năng xử lý đồng thời, bằng cách sử dụng phương thức bất đồng bộ và bộ lập lịch để xử lý các yêu cầu. + +## Giải thích + +Lớp hiện thực mẫu Đối Tượng Chủ Động sẽ bao gồm cơ chế tự đồng bộ (self-synchronization) nhưng không sử dụng đến phương thức/từ khóa 'synchronized'. + +Ví dụ thực tế + +> Tộc Orcs được biết đến với tính cách hoang dã và không thuần hóa được. Có thể coi như họ có một luồng điều khiển riêng do họ quyết định việc thực thi mà ta không can thiệp được. + +Để hiện thực hóa một sinh vật mà nó sở hữu riêng cơ chế điều khiển luồng và chỉ để lộ ra giao diện lập trình (API), chúng ta có thể sử dụng mẫu Đối Tượng Chủ Động. + +**Chương trình ví dụ** + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +Có thể thấy rằng mọi lớp kế thừa từ lớp `ActiveCreature` sẽ có riêng luồng điều khiển để gọi và thực thi phương thức. + +Ví dụ lớp `Orc`: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` + +Bây giờ, chúng ta có thể khởi tạo các sinh vật như Orcs, bảo chúng ăn (gọi hàm `eat()`) và tản bộ (gọi hàm `roam()`), và chúng sẽ thực thi trên luồng điều khiển của riêng chúng: + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## Sơ đồ lớp + +![alt text](../../../active-object/etc/active-object.urm.png "Active Object class diagram") + +## Hướng dẫn + +* [Android and Java Concurrency: The Active Object Pattern](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) \ No newline at end of file diff --git a/localization/vi/acyclic-visitor/README.md b/localization/vi/acyclic-visitor/README.md new file mode 100644 index 000000000000..11f7e0011d9b --- /dev/null +++ b/localization/vi/acyclic-visitor/README.md @@ -0,0 +1,157 @@ +--- +title: Acyclic Visitor +category: Behavioral +language: vi +tag: + - Extensibility +--- + +## Mục đích + +Cho phép thêm các hàm mới vào cấu trúc các lớp hiện có mà không làm ảnh hưởng đến cấu trúc của chúng, đồng thời tránh tạo ra các phụ thuộc vòng (dependency cycles) của Visitor Pattern trong Gang of Four. + +## Giải thích + +Ví dụ thực tế + +> Chúng ta có một hệ thống các lớp modem. Những modem trong hệ thống này cần được duyệt qua bởi một thuật toán bên ngoài dựa trên một tiêu chí lọc (ví dụ như chỉ lấy các loại modem tương thích với hệ điều hành Unix hoặc DOS). + +Nói đơn giản hơn + +> Acyclic Visitor cho phép thêm các hàm vào các hệ thống lớp hiện có mà không cần sửa đổi cấu trúc của chúng. + +Theo [WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) + +> Mẫu thiết kế Acyclic Visitor cho phép thêm các hàm mới vào các hệ thống lớp hiện có mà không ảnh hưởng đến các hệ thống đó, và không tạo ra các phụ thuộc vòng (dependency cycles) như là một phần không thể tránh của Visitor Pattern trong Gang of Four. + +**Mã nguồn mẫu** + +Dưới đây là cấu trúc của class `Modem`. + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + +Tiếp theo, là cấu trúc của lớp `ModemVisitor`. + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + ... + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + ... + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +Cuối cùng, chúng ta sẽ thấy các lớp visitor hoạt động. + +```java + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + var zoom = new Zoom(); + var hayes = new Hayes(); + hayes.accept(conDos); + zoom.accept(conDos); + hayes.accept(conUnix); + zoom.accept(conUnix); +``` + +Kết quả khi chạy chương trình: + +``` + // Hayes modem used with Dos configurator. + // Zoom modem used with Dos configurator. + // Only HayesVisitor is allowed to visit Hayes modem + // Zoom modem used with Unix configurator. +``` + +## Sơ đồ lớp +![alt text](../../../acyclic-visitor/etc/acyclic-visitor.png "Acyclic Visitor") + +## Áp dụng +Mẫu thiết kế này có thể được sử dụng trong các trường hợp: + +* Khi bạn cần thêm một hàm mới vào một hệ thống lớp hiện có mà không cần phải sửa đổi hoặc ảnh hưởng đến hệ thống đó. +* Khi có các hàm thao tác trên một hệ thống lớp nhưng những hàm này không nên thuộc về cùng cấu trúc của hệ thống đó. Ví dụ như vấn đề ConfigureForDOS / ConfigureForUnix / ConfigureForX. +* Khi bạn cần thực hiện các thao tác hoàn toàn khác nhau trên một đối tượng dựa vào kiểu của nó. +* Khi hệ thống lớp được duyệt sẽ thường xuyên được mở rộng với các lớp dẫn xuất mới của lớp Element. +* Khi việc biên dịch lại, liên kết lại, kiểm thử lại hoặc phân phối lại các lớp dẫn xuất của Element rất tốn kém. + +## Hướng dẫn + +* [Ví dụ về mẫu thiết kế Acyclic Visitor](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) + +## Kết luận + +Mặt tích cực: + +* Không có phụ thuộc vòng giữa các hệ thống lớp. +* Không cần phải biên dịch lại tất cả các lớp visitor nếu có một lớp mới được thêm vào. +* Không gây ra lỗi biên dịch ở các lớp visitor hiện có nếu hệ thống lớp có một thành viên mới. + +Mặt tiêu cực: + +* Vi phạm [Nguyên tắc thay thế của Liskov](https://java-design-patterns.com/principles/#liskov-substitution-principle) bằng cách cho thấy rằng nó có thể chấp nhận tất cả các lớp visitor nhưng thực sự chỉ quan tâm đến một số lớp visitor cụ thể. +* Phải tạo ra một cấu trúc song song các lớp visitor cho tất cả các thành viên trong hệ thống lớp có thể được duyệt. + +## Các mẫu liên quan + +* [Visitor Pattern](https://java-design-patterns.com/patterns/visitor/) + +## Người đóng góp + +* [Acyclic Visitor bởi Robert C. Martin](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor trên WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) diff --git a/localization/vi/adapter/README.md b/localization/vi/adapter/README.md new file mode 100644 index 000000000000..f135c54e71f4 --- /dev/null +++ b/localization/vi/adapter/README.md @@ -0,0 +1,135 @@ +--- +title: Adapter +category: Structural +language: vi +tag: + - Gang of Four +--- + +## Còn được gọi là +Wrapper + +## Mục đích +Chuyển đổi giao diện của một lớp thành một giao diện khác mà mình mong muốn. Adapter cho phép các lớp làm việc cùng nhau, mặc dù ban đầu chúng không thể làm việc cùng nhau do giao diện không tương thích. + +## Giải thích + +Ví dụ thực tế + +> Hãy tưởng tượng rằng bạn có một số hình ảnh trên thẻ nhớ của bạn và bạn cần chuyển chúng sang máy tính của bạn. Để chuyển chúng, bạn cần một loại adapter nào đó tương thích với các cổng máy tính của bạn để bạn có thể kết nối thẻ nhớ vào máy tính của bạn. Trong trường hợp này, đầu đọc thẻ là một cái adapter. +> Ví dụ nổi tiếng khác là adapter điện; một phích cắm ba chân không thể kết nối vào một ổ cắm hai chân, nó cần sử dụng một adapter điện để làm cho nó tương thích với ổ cắm hai chân. +> Một ví dụ khác là thông dịch viên dịch lời của người này cho người khác hiểu được. + +## Nói đơn giản hơn + +> Mẫu Adapter cho phép bạn bọc một đối tượng ban đầu không tương thích vào một adapter để làm cho nó tương thích với một lớp khác. + +Theo Wikipedia + +> Trong kỹ thuật phần mềm, mẫu thiết kế Adapter là một mẫu thiết kế phần mềm cho phép giao diện của một lớp hiện có được sử dụng như một giao diện khác. Nó thường được sử dụng để làm cho các lớp hiện có làm việc với các lớp khác mà không cần sửa đổi mã nguồn của chúng. + +**Mã nguồn mẫu** + +Hãy xem xét một thuyền trưởng chỉ có thể sử dụng thuyền chèo và không thể thả neo. + +Đầu tiên, chúng ta có các giao diện `RowingBoat` và `FishingBoat` + +```java +public interface RowingBoat { + void row(); +} + +@Slf4j +public class FishingBoat { + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } +} +``` + +Và thuyền trưởng mong đợi một lớp là triển khai của giao diện `RowingBoat` mà có thể di chuyển được + +```java +public class Captain { + + private final RowingBoat rowingBoat; + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +Bây giờ hãy nói rằng hải tặc đang đến và thuyền trưởng của chúng ta cần trốn thoát nhưng chỉ có một thuyền câu sẵn có. Chúng ta cần tạo một adapter cho phép thuyền trưởng vận hành thuyền câu với kỹ năng chèo của mình. + +```java +@Slf4j +public class FishingBoatAdapter implements RowingBoat { + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} +``` + +Và bây giờ `Captain` có thể sử dụng `FishingBoat` để trốn thoát khỏi hải tặc. + +```java +var captain = new Captain(new FishingBoatAdapter()); +captain.row(); +``` + +## Sơ đồ lớp +![alt text](../../../adapter/etc/adapter.urm.png "Adapter class diagram") + +## Áp dụng +Sử dụng mẫu Adapter khi: + +* Bạn muốn sử dụng một lớp hiện có, và giao diện của nó không phù hợp với giao diện bạn cần +* Bạn muốn tạo một lớp có thể tái sử dụng làm việc với các lớp không liên quan hoặc không thể dự đoán trước, tức là các lớp không nhất thiết phải có giao diện tương thích +* Bạn cần sử dụng nhiều lớp con hiện có, nhưng việc điều chỉnh giao diện của chúng thông qua việc kế thừa là không hiệu quả. Một đối tượng adapter có thể điều chỉnh giao diện của lớp cha của nó. +* Hầu hết các ứng dụng sử dụng thư viện bên ngoài sử dụng adapter như một lớp trung gian giữa ứng dụng và thư viện bên ngoài. Nếu muốn sử dụng thư viện khác, chỉ cần tạo một adapter cho thư viện mới mà không cần thay đổi mã nguồn của ứng dụng. + +## Hướng dẫn + +* [Dzone](https://dzone.com/articles/adapter-design-pattern-in-java) +* [Refactoring Guru](https://refactoring.guru/design-patterns/adapter/java/example) +* [Baeldung](https://www.baeldung.com/java-adapter-pattern) + +## Kết luận + +Lớp adapter và đối tượng adapter có những lợi ích và khả năng thích ứng khác nhau. Một lớp adapter + +* Chuyển đổi một lớp Adaptee để phù hợp với Target bằng cách ràng buộc với một lớp Adaptee cụ thể. Kết quả là, khi chúng ta muốn thích ứng một lớp và tất cả các lớp con của nó, thì lớp adapter sẽ không hoạt động. +* Cho phép Adapter ghi đè một số hành vi của Adaptee vì Adapter là một lớp con của Adaptee. +* Chỉ giới thiệu một đối tượng và không cần thêm con trỏ để truy cập gián tiếp đến Adaptee. + +Một đối tượng Adapter + +* Cho phép một Adapter làm việc với nhiều Adaptees, tức là chính Adaptee và tất cả các lớp con của nó (nếu có). Adapter cũng có thể thêm chức năng cho tất cả Adaptee cùng một lúc. +* Làm cho việc ghi đè hành vi của Adaptee trở nên khó khăn hơn. Nó sẽ yêu cầu việc kế thừa Adaptee và làm cho Adapter tham chiếu đến lớp con thay vì chính Adaptee. + +## Ví dụ trong thực tế + +* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +* [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +* [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + +## Người đóng góp + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/vi/aggregator-microservices/README.md b/localization/vi/aggregator-microservices/README.md new file mode 100644 index 000000000000..b36a388fc9cb --- /dev/null +++ b/localization/vi/aggregator-microservices/README.md @@ -0,0 +1,102 @@ +--- +title: Microservices Tổng Hợp +category: Architectural +language: vi +tag: +- Cloud distributed +- Decoupling +- Microservices +--- + +## Mục Đích +Người dùng chỉ cần thực hiện một lần gọi duy nhất đến dịch vụ tổng hợp, sau đó dịch vụ tổng hợp sẽ gọi dịch vụ con tương ứng. + +## Giải Thích + +Ví dụ thực tế + +> Trang web thị trường của chúng ta cần thông tin về sản phẩm và tồn kho hiện tại của chúng. Nó thực hiện gọi đến dịch vụ tổng hợp, sau đó dịch vụ tổng hợp gọi dịch vụ thông tin sản phẩm và dịch vụ tồn kho sản phẩm, cuối cùng trả lại thông tin kết hợp. + +## Nói đơn giản hơn + +> Microservices Tổng Hợp thu thập các phần dữ liệu từ các dịch vụ con khác nhau và trả về một tổng hợp để xử lý. + +Theo Stack Overflow + +> Microservices Tổng Hợp gọi nhiều dịch vụ để đạt được chức năng được yêu cầu bởi ứng dụng. + +**Mã nguồn mẫu** + +Hãy bắt đầu từ mô hình dữ liệu. Đây là lớp `Product` của chúng ta. + +```java +public class Product { + private String title; + private int productInventories; + // getters and setters -> + ... +} +``` + +Tiếp theo, chúng ta có thể giới thiệu Microservices `Aggregator` của chúng ta. Nó chứa các khách hàng `ProductInformationClient` và +`ProductInventoryClient` để gọi các dịch vụ con tương ứng. + +```java +@RestController +public class Aggregator { + + @Resource + private ProductInformationClient informationClient; + + @Resource + private ProductInventoryClient inventoryClient; + + @RequestMapping(path = "/product", method = RequestMethod.GET) + public Product getProduct() { + + var product = new Product(); + var productTitle = informationClient.getProductTitle(); + var productInventory = inventoryClient.getProductInventories(); + + //Fallback to error message + product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed")); + + //Fallback to default error inventory + product.setProductInventories(requireNonNullElse(productInventory, -1)); + + return product; + } +} +``` + +Dưới đây là bản thể của việc triển khai dịch vụ thông tin sản phẩm. Dịch vụ tồn kho cũng tương tự như thế, nó chỉ trả về số lượng tồn kho. + +```java +@RestController +public class InformationController { + @RequestMapping(value = "/information", method = RequestMethod.GET) + public String getProductTitle() { + return "The Product Title."; + } +} +``` + +Bây giờ, việc gọi `Aggregator` API REST của chúng ta sẽ trả về thông tin sản phẩm. + +```bash +curl http://localhost:50004/product +{"title":"The Product Title.","productInventories":5} +``` + +## Sơ Đồ Lớp +![alt text](../../../aggregator-microservices/aggregator-service/etc/aggregator-service.png "Aggregator Microservice") + + +## Các Trường Hợp Sử Dụng +Sử dụng mẫu Microservices Tổng Hợp khi bạn cần một API chung cho các dịch vụ Microservices khác nhau, bất kể thiết bị của khách hàng. + +## Người Đóng Góp + +* [Microservice Design Patterns](http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/) +* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=8b4e570267bc5fb8b8189917b461dc60) +* [Architectural Patterns: Uncover essential patterns in the most indispensable realm of enterprise architecture](https://www.amazon.com/gp/product/B077T7V8RC/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B077T7V8RC&linkId=c34d204bfe1b277914b420189f09c1a4) diff --git a/localization/vi/builder/README.md b/localization/vi/builder/README.md new file mode 100644 index 000000000000..b463ed5c64bc --- /dev/null +++ b/localization/vi/builder/README.md @@ -0,0 +1,166 @@ +--- +title: Builder +category: Creational +language: vi +tag: + - Gang of Four +--- + +## Mục tiêu + +Tách rời việc xây dựng một đối tượng phức tạp khỏi cách thể hiện của nó, để cùng một quá trình xây dựng có thể tạo ra các cách thể hiện khác nhau. + +## Giải thích + +Ví dụ thực tế + +> Hãy tưởng tượng một trình tạo nhân vật cho trò chơi nhập vai. Cách đơn giản nhất là để máy tính tạo nhân vật cho bạn. Nếu bạn muốn chọn các chi tiết về nhân vật như nghề nghiệp, giới tính, màu tóc, v.v. thì việc tạo nhân vật trở thành một quá trình từng bước và hoàn tất khi tất cả các lựa chọn đã sẵn sàng. + +Nói một cách đơn giản + +> Mẫu Builder cho phép bạn tạo ra các phiên bản khác nhau của một đối tượng trong khi tránh việc dùng hàm khởi tạo. Mẫu này hữu ích khi có thể có nhiều phiên bản của một đối tượng. Hoặc khi có nhiều bước liên quan tới việc tạo một đối tượng. + +Theo Wikipedia + +> Mẫu Builder là một mẫu thiết kế phần mềm dùng để tạo ra đối tượng, với mục đích tìm ra giải pháp cho phản thiết kế hàm khởi tạo quá nhiều tham số (telescoping constructor antipattern). + +Để giải thích rõ hơn về lỗi phản thiết kế hàm khởi tạo có quá nhiều tham số là gì. Ở một thời điểm nào đó, tất cả chúng ta đều đã thấy một hàm khởi tạo như bên dưới: + +```java +public Hero(Profession profession,String name,HairType hairType,HairColor hairColor,Armor armor,Weapon weapon){ + } +``` + +Như bạn có thể thấy, số lượng tham số của hàm khởi tạo có thể nhanh chóng trở nên rất nhiều, và có thể trở nên khó khăn cho việc sắp xếp các tham số. Hơn nữa, danh sách tham số này có thể tiếp tục tăng lên nếu bạn muốn bổ sung thêm tùy chọn trong tương lai. Đây được gọi là lỗi phản thiết kế hàm khởi tạo có quá nhiều tham số. + +**Ví dụ lập trình** + +Một giải pháp hợp lý hơn là sử dụng mẫu Builder. Trước hết, chúng ta có nhân vật anh hùng mà chúng ta muốn tạo ra: + +```java +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; + } +} +``` + +Sau đó chúng ta có lớp Builder: + +```java + 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); + } +} +``` + +Sau đó nó có thể được sử dụng như sau: + +```java +var mage=new Hero.Builder(Profession.MAGE,"Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build(); +``` + +## Class diagram + +![alt text](../../../builder/etc/builder.urm.png "Builder class diagram") + +## Ứng dụng + +Sử dụng mẫu Builder khi: + +* Thuật toán để tạo một đối tượng phức tạp phải độc lập với các bộ phận tạo nên đối tượng đó và cách chúng liên kết với nhau. +* Quá trình xây dựng phải cho phép các cách thể hiện khác nhau cho đối tượng được tạo ra. +* Đặc biệt hữu ích khi một sản phẩm cần nhiều bước để được tạo ra và khi các bước này cần được thực hiện theo một trình tự nhất định. + +## Các trường hợp sử dụng đã biết + +* Java.lang.StringBuilder +* Java.nio.ByteBuffer cũng như các bộ đệm tương tự như FloatBuffer, IntBuffer, và các bộ đệm khác. +* javax.swing.GroupLayout.Group#addComponent() + +## Hậu quả + +Ưu điểm: + +* Kiểm soát tốt hơn quá trình xây dựng đối tượng so với các mẫu tạo đối tượng khác. +* Hỗ trợ xây dựng đối tượng theo từng bước, hoãn các bước xây dựng hoặc chạy các bước đệ quy. +* Có thể xây dựng các đối tượng đòi hỏi quá trình kết hợp phức tạp các đối tượng con. Sản phẩm cuối cùng được tách rời khỏi các bộ phận tạo nên nó, cũng như quá trình liên kết chúng. +* Nguyên tắc Đơn Trách nhiệm. Bạn có thể tách rời mã xây dựng phức tạp khỏi logic nghiệp vụ của sản phẩm. + +Nhược điểm: + +* Tổng thể độ phức tạp của code có thể tăng lên vì mẫu đòi hỏi phải tạo nhiều lớp mới. + +## Hướng dẫn + +* [Refactoring Guru](https://refactoring.guru/design-patterns/builder) +* [Oracle Blog](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) +* [Journal Dev](https://www.journaldev.com/1425/builder-design-pattern-in-java) + +## Các trường hợp sử dụng đã biết + +* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) +* [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) cũng như các bộ đệm tương tự như FloatBuffer, IntBuffer, v.v. +* [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) +* Tất cả các triển khai của [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) +* [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## Mẫu liên quan + +* [Step Builder](https://java-design-patterns.com/patterns/step-builder/) là một biến thể của mẫu Builder tạo ra một đối tượng phức tạp theo cách tiếp cận từng bước. Mẫu Step Builder là một lựa chọn tốt khi bạn cần xây dựng một đối tượng với nhiều tham số tùy chọn, và bạn muốn tránh lỗi phản thiết kế hàm khởi tạo có quá nhiều tham số. + +## Ghi nhận + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) \ No newline at end of file diff --git a/localization/vi/game-loop/README.md b/localization/vi/game-loop/README.md new file mode 100644 index 000000000000..31c8fad0b5bb --- /dev/null +++ b/localization/vi/game-loop/README.md @@ -0,0 +1,275 @@ +--- +title: Game Loop (Vòng lặp trò chơi) +category: Behavioral +language: vi +tag: + - Concurrency + - Event-driven + - Game programming + - Performance +--- + +## Còn được gọi là + +* Game Cycle (Chu kỳ trò chơi) +* Main Game Loop (Vòng lặp trò chơi chính) + +## Mục tiêu + +Mẫu thiết kế Game Loop nhằm thực thi liên tục của một trò chơi, trong đó mỗi chu kỳ vòng lặp xử lý đầu vào, cập nhật trạng thái trò chơi, và hiển thị trạng thái trò chơi lên màn hình, duy trì trải nghiệm chơi mượt mà và tương tác. + +## Giải thích + +Ví dụ thực tế + +> Game loop là quá trình chính của tất cả các luồng hiển thị trò chơi. Nó hiện diện trong tất cả các trò chơi hiện đại. Nó điều khiển việc xử lý đầu vào, cập nhật trạng thái nội bộ, hiển thị, xử lý trí tuệ nhân tạo và tất cả các quá trình khác. + +Nói một cách đơn giản + +> Mẫu Game Loop đảm bảo rằng thời gian trò chơi thực thi với tốc độ bằng nhau trong tất cả các cấu hình phần cứng khác nhau. + +Theo Wikipedia + +> Thành phần trung tâm của bất kỳ trò chơi nào, từ góc độ lập trình, đều là game loop. Game loop cho phép trò chơi chạy trơn tru bất kể đầu vào của người dùng hoặc thiếu đầu vào. + +**Ví dụ lập trình** + +Hãy bắt đầu với một thứ gì đó đơn giản. Đây là lớp `Bullet` (Đạn). Đạn sẽ di chuyển trong trò chơi của chúng ta. Để dễ hình dung, ta cho nó có vị trí 1 chiều. + +```java +public class Bullet { + + private float position; + + public Bullet() { + position = 0.0f; + } + + public float getPosition() { + return position; + } + + public void setPosition(float position) { + this.position = position; + } +} +``` + +`GameController` có trách nhiệm di chuyển các đối tượng trong trò chơi, bao gồm cả đạn đã đề cập bên trên. + +```java +public class GameController { + + protected final Bullet bullet; + + public GameController() { + bullet = new Bullet(); + } + + public void moveBullet(float offset) { + var currentPosition = bullet.getPosition(); + bullet.setPosition(currentPosition + offset); + } + + public float getBulletPosition() { + return bullet.getPosition(); + } +} +``` + +Bây giờ chúng ta tạo ra một vòng lặp trò chơi (game loop). Hoặc thực tế trong ví dụ minh họa này, chúng ta có loại 3 vòng lặp trò chơi khác nhau. Hãy xem lớp cha `GameLoop` trước. + +```java +public enum GameStatus { + + RUNNING, + STOPPED +} + +public abstract class GameLoop { + + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + + protected volatile GameStatus status; + + protected GameController controller; + + private Thread gameThread; + + public GameLoop() { + controller = new GameController(); + status = GameStatus.STOPPED; + } + + public void run() { + status = GameStatus.RUNNING; + gameThread = new Thread(this::processGameLoop); + gameThread.start(); + } + + public void stop() { + status = GameStatus.STOPPED; + } + + public boolean isGameRunning() { + return status == GameStatus.RUNNING; + } + + protected void processInput() { + try { + var lag = new Random().nextInt(200) + 50; + Thread.sleep(lag); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + + protected void render() { + var position = controller.getBulletPosition(); + logger.info("Current bullet position: " + position); + } + + protected abstract void processGameLoop(); +} +``` + +Đây là cách hiện thực đầu tiên, `FrameBasedGameLoop` (Vòng lặp trò chơi dựa trên khung hình): + +```java +public class FrameBasedGameLoop extends GameLoop { + + @Override + protected void processGameLoop() { + while (isGameRunning()) { + processInput(); + update(); + render(); + } + } + + protected void update() { + controller.moveBullet(0.5f); + } +} +``` + +Cuối cùng, chúng ta sẽ thực thi tất cả các vòng lặp trò chơi. + +```java + try { + LOGGER.info("Start frame-based game loop:"); + var frameBasedGameLoop = new FrameBasedGameLoop(); + frameBasedGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + frameBasedGameLoop.stop(); + LOGGER.info("Stop frame-based game loop."); + + LOGGER.info("Start variable-step game loop:"); + var variableStepGameLoop = new VariableStepGameLoop(); + variableStepGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + variableStepGameLoop.stop(); + LOGGER.info("Stop variable-step game loop."); + + LOGGER.info("Start fixed-step game loop:"); + var fixedStepGameLoop = new FixedStepGameLoop(); + fixedStepGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + fixedStepGameLoop.stop(); + LOGGER.info("Stop variable-step game loop."); + + } catch (InterruptedException e) { + LOGGER.error(e.getMessage()); + } +``` + +Kết quả chương trình: + +```Start frame-based game loop: +Current bullet position: 0.5 +Current bullet position: 1.0 +Current bullet position: 1.5 +Current bullet position: 2.0 +Current bullet position: 2.5 +Current bullet position: 3.0 +Current bullet position: 3.5 +Current bullet position: 4.0 +Current bullet position: 4.5 +Current bullet position: 5.0 +Current bullet position: 5.5 +Current bullet position: 6.0 +Stop frame-based game loop. +Start variable-step game loop: +Current bullet position: 6.5 +Current bullet position: 0.038 +Current bullet position: 0.084 +Current bullet position: 0.145 +Current bullet position: 0.1805 +Current bullet position: 0.28 +Current bullet position: 0.32 +Current bullet position: 0.42549998 +Current bullet position: 0.52849996 +Current bullet position: 0.57799995 +Current bullet position: 0.63199997 +Current bullet position: 0.672 +Current bullet position: 0.778 +Current bullet position: 0.848 +Current bullet position: 0.8955 +Current bullet position: 0.9635 +Stop variable-step game loop. +Start fixed-step game loop: +Current bullet position: 0.0 +Current bullet position: 1.086 +Current bullet position: 0.059999995 +Current bullet position: 0.12999998 +Current bullet position: 0.24000004 +Current bullet position: 0.33999994 +Current bullet position: 0.36999992 +Current bullet position: 0.43999985 +Current bullet position: 0.5399998 +Current bullet position: 0.65999967 +Current bullet position: 0.68999964 +Current bullet position: 0.7299996 +Current bullet position: 0.79999954 +Current bullet position: 0.89999944 +Current bullet position: 0.98999935 +Stop variable-step game loop. +``` + +## Class diagram + +![alt text](../../../game-loop/etc/game-loop.urm.png "Game Loop pattern class diagram") + +## Ứng dụng + +Mẫu Game Loop được áp dụng trong mô phỏng thời gian thực và trò chơi, nơi trạng thái cần được cập nhật liên tục và nhất quán để đáp ứng đầu vào của người dùng và các sự kiện khác. + +## Các trường hợp ứng dụng đã biết + +* Trò chơi video, cả 2D và 3D, trên các nền tảng khác nhau. +* Mô phỏng thời gian thực yêu cầu tỷ lệ khung hình ổn định để cập nhật logic và hiển thị. + +## Hậu quả + +Ưu điểm: + +* Đảm bảo trò chơi thực thi mượt mà và nhất quán. +* Tạo điều kiện thuận lợi cho việc đồng bộ giữa trạng thái trò chơi, đầu vào người dùng và hiển thị lên màn hình. +* Cung cấp một cấu trúc rõ ràng để các nhà phát triển trò chơi quản lý chuyển động và thời gian trong trò chơi. + +Nhược điểm: + +* Có thể dẫn đến vấn đề hiệu suất nếu vòng lặp không được quản lý tốt, đặc biệt là trong các hàm cập nhật hoặc hiển thị tốn nhiều tài nguyên. +* Khó khăn trong việc quản lý tỷ lệ khung hình (frame rates) khác nhau trên các phần cứng khác nhau. + +## Các mẫu liên quan + +* [State](https://java-design-patterns.com/patterns/state/): Thường được sử dụng trong vòng lặp trò chơi để quản lý các trạng thái khác nhau của trò chơi (ví dụ: menu, đang chơi, tạm dừng). Mối quan hệ nằm ở việc quản lý hành vi cụ thể của trạng thái và chuyển đổi trạng thái một cách mượt mà trong vòng lặp trò chơi. +* [Observer](https://java-design-patterns.com/patterns/observer/): Hữu ích trong vòng lặp trò chơi để xử lý sự kiện, nơi các thực thể trò chơi có thể đăng ký và phản ứng với các sự kiện (ví dụ: va chạm, ghi điểm). + +## Tham khảo + +* [Game Programming Patterns - Game Loop](http://gameprogrammingpatterns.com/game-loop.html) +* [Game Programming Patterns](https://www.amazon.com/gp/product/0990582906/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0990582906&linkId=1289749a703b3fe0e24cd8d604d7c40b) +* [Game Engine Architecture, Third Edition](https://www.amazon.com/gp/product/1138035459/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1138035459&linkId=94502746617211bc40e0ef49d29333ac) +* [Real-Time Collision Detection](https://amzn.to/3W9Jj8T) \ No newline at end of file diff --git a/localization/zh/README.md b/localization/zh/README.md new file mode 100644 index 000000000000..6b810cd48e9a --- /dev/null +++ b/localization/zh/README.md @@ -0,0 +1,41 @@ + + +# 设计模式Java版 + +![Java CI with Maven](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI/badge.svg) [](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md)![License MIT](https://img.shields.io/badge/license-MIT-blue.svg) [](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg) [](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=alert_status) + +# 介绍 + +设计模式是程序员在设计应用程序或系统时可以用来解决常见问题的最佳形式化实践。 + +设计模式可以通过提供经过测试的,经过验证的开发范例来加快开发过程。 + +重用设计模式有助于防止引起重大问题的细微问题,并且还可以为熟悉模式的程序员和架构师们提高代码可读性。 + +# 入门 + +这个站点展示了Java设计模式。该解决方案是由开源社区中经验丰富的程序员和架构师开发的。可以通过他们高级描述或查看源代码来浏览这些设计模式。源代码示例得到了很好的注释,可以视为编程教程,以了解如何实现特定的模式。我们使用最流行的,久经考验的开源Java技术。 + +在深入学习该材料之前,您应该熟悉各种软件设计原则。 + +所有设计应尽可能简单。您应该从KISS,YAGNI开始,并做可能可行的最简单的事情。仅在实际可扩展性需要它们时才应引入复杂性和模式。 + +熟悉这些概念后,您可以通过以下任何一种方法开始深入研究模式 + +- 使用难度标签: `入门难度` , `中等难度`和`专家难度` 。 +- 使用模式分类`创建型` ,`行为型`和其他类别。 +- 搜索特定的模式。一个也找不到?请[在这里](https://github.com/iluwatar/java-design-patterns/issues)反馈新模式。 + +希望您在本站上找到的面向对象解决方案能够对您的体系结构很有用,并在学习它们的时候能够像我们开发它们一样有趣。 + +# 如何做出贡献 + +如果您愿意为该项目做出贡献,则可以在我们的[开发人员Wiki中](https://github.com/iluwatar/java-design-patterns/wiki)找到相关信息。我们将在[Gitter聊天室](https://gitter.im/iluwatar/java-design-patterns)为您提供帮助并回答您的问题。 + +# 许可证 + +该项目使用MIT许可证。 + + diff --git a/localization/zh/abstract-document/README.md b/localization/zh/abstract-document/README.md new file mode 100644 index 000000000000..cf19dfcf84cb --- /dev/null +++ b/localization/zh/abstract-document/README.md @@ -0,0 +1,181 @@ +--- +title: Abstract Document +shortTitle: Abstract Document +category: Structural +language: zh +tag: + - Extensibility +--- + +## 目的 + +使用动态属性,并在保持类型安全的同时实现非类型化语言的灵活性。 + +## 解释 + +抽象文档模式使您能够处理其他非静态属性。 此模式使用特征的概念来实现类型安全,并将不同类的属性分离为一组接口。 + +真实世界例子 + +> 考虑由多个部分组成的汽车。 但是,我们不知道特定汽车是否真的拥有所有零件,或者仅仅是零件中的一部分。 我们的汽车是动态而且非常灵活的。 + +通俗的说 + +> 抽象文档模式允许在对象不知道的情况下将属性附加到对象。 + +维基百科说 + +> 面向对象的结构设计模式,用于组织松散类型的键值存储中的对象并使用类型化的视图公开数据。 该模式的目的是在强类型语言中实现组件之间的高度灵活性,在这种语言中,可以在不丢失类型安全支持的情况下,将新属性动态地添加到对象树中。 该模式利用特征将类的不同属性分成不同的接口。 + +**程序示例** + +让我们首先定义基类`Document`和`AbstractDocument`。 它们基本上使对象拥有属性映射和任意数量的子对象。 + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + Stream children(String key, Function, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map properties; + + protected AbstractDocument(Map properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public Stream children(String key, Function, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + ... +} +``` +接下来,我们定义一个枚举“属性”和一组类型,价格,模型和零件的接口。 这使我们能够为Car类创建静态外观的界面。 + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} +public interface HasModel extends Document { + + default Optional getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} +``` + +现在我们准备介绍`Car`。 + +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map properties) { + super(properties); + } +} +``` + +最后是完整示例中的`Car`构造和使用方式。 + +```java + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); + + // Constructing parts and car + // Here is our car: + // model: 300SL + // price: 10000 + // parts: + // wheel/15C/100 + // door/Lambo/300 +``` + +## 类图 + +![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain") + +## 适用性 + +使用抽象文档模式当 + +* 需要即时添加新属性 +* 你想要一种灵活的方式来以树状结构组织域 +* 你想要更宽松的耦合系统 + +## 鸣谢 + +* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492) diff --git a/localization/zh/abstract-document/etc/abstract-document.png b/localization/zh/abstract-document/etc/abstract-document.png new file mode 100644 index 000000000000..6bc0b29a4e77 Binary files /dev/null and b/localization/zh/abstract-document/etc/abstract-document.png differ diff --git a/localization/zh/abstract-factory/README.md b/localization/zh/abstract-factory/README.md new file mode 100644 index 000000000000..eca9f0d1fb30 --- /dev/null +++ b/localization/zh/abstract-factory/README.md @@ -0,0 +1,214 @@ +--- +title: Abstract Factory +shortTitle: Abstract Factory +category: Creational +language: zh +tag: + - Gang of Four +--- + +## 或称 + +工具包 + +## 目的 + +提供一个用于创建相关对象家族的接口,而无需指定其具体类。 + +## 解释 + +真实世界例子 + +> 要创建一个王国,我们需要具有共同主题的对象。精灵王国需要精灵国王、精灵城堡和精灵军队,而兽人王国需要兽人国王、兽人城堡和兽人军队。王国中的对象之间存在依赖关系。 + +通俗的说 + +> 工厂的工厂; 一个将单个但相关/从属的工厂分组在一起而没有指定其具体类别的工厂。 + +维基百科上说 + +> 抽象工厂模式提供了一种封装一组具有共同主题的单个工厂而无需指定其具体类的方法 + +**程序示例** + +翻译上面的王国示例。 首先,我们为王国中的对象提供了一些接口和实现。 + +```java +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 -> ... + +``` + +然后我们有了王国工厂的抽象和实现 + +```java +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(); + } +} +``` + +现在我们有了抽象工厂,使我们可以制作相关对象的系列,即精灵王国工厂创建了精灵城堡,国王和军队等。 + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +程序输出: + +```java +This is the Elven castle! +This is the Elven king! +This is the Elven Army! +``` + +现在,我们可以为不同的王国工厂设计工厂。 在此示例中,我们创建了FactoryMaker,负责返回ElfKingdomFactory或OrcKingdomFactory的实例。 客户可以使用FactoryMaker来创建所需的具体工厂,该工厂随后将生产不同的具体对象(军队,国王,城堡)。 在此示例中,我们还使用了一个枚举来参数化客户要求的王国工厂类型。 + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + return switch (type) { + case ELF -> new ElfKingdomFactory(); + case ORC -> new OrcKingdomFactory(); + default -> throw new IllegalArgumentException("KingdomType not supported."); + }; + } +} + + public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + --similar use of the orc factory + } +``` + +## 类图 + +![alt text](./etc/abstract-factory.urm.png "Abstract Factory class diagram") + + +## 适用性 + +在以下情况下使用抽象工厂模式 + +* 该系统应独立于其产品的创建,组成和表示方式 +* 系统应配置有多个产品系列之一 +* 相关产品对象系列旨在一起使用,你需要强制执行此约束 +* 你想提供产品的类库,并且只想暴露它们的接口,而不是它们的实现。 +* 从概念上讲,依赖项的生存期比使用者的生存期短。 +* 你需要一个运行时值来构建特定的依赖关系 +* 你想决定在运行时从系列中调用哪种产品。 +* 你需要提供一个或更多仅在运行时才知道的参数,然后才能解决依赖关系。 +* 当你需要产品之间的一致性时 +* 在向程序添加新产品或产品系列时,您不想更改现有代码。 + +示例场景 + +* 在运行时在FileSystemAcmeService ,DatabaseAcmeService 或NetworkAcmeService中选择并调用一个 +* 单元测试用例的编写变得更加容易 +* 适用于不同操作系统的UI工具 + +## 后果: + +* Java中的依赖注入会隐藏服务类的依赖关系,这些依赖关系可能导致运行时错误,而这些错误在编译时会被捕获。 +* 虽然在创建预定义对象时模式很好,但是添加新对象可能会很困难。 +* 由于引入了许多新的接口和类,因此代码变得比应有的复杂。 + +## 教程 + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## 已知使用 + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## 相关模式 + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/zh/abstract-factory/etc/abstract-factory.urm.png b/localization/zh/abstract-factory/etc/abstract-factory.urm.png new file mode 100644 index 000000000000..836858a2c652 Binary files /dev/null and b/localization/zh/abstract-factory/etc/abstract-factory.urm.png differ diff --git a/localization/zh/active-object/README.md b/localization/zh/active-object/README.md new file mode 100644 index 000000000000..ba35892e81c2 --- /dev/null +++ b/localization/zh/active-object/README.md @@ -0,0 +1,123 @@ +--- +title: Active Object +shortTitle: Active Object +category: Concurrency +language: zh +tag: + - Performance +--- + + +## 目的 +活动对象设计模式使每个驻留在其控制线程中的对象的方法执行与方法调用脱钩。 目的是通过使用异步方法调用和用于处理请求的调度程序来引入并发。 + +## 解释 + +实现活动对象模式的类将包含自同步机制,而无需使用“同步”方法。 + +真实世界例子 + +>兽人以其野性和顽强的灵魂而著称。 似乎他们有基于先前行为的控制线程。 + +要实现具有自己的控制机制线程并仅公开其API而不公开自己的执行,我们可以使用活动对象模式。 + +**程序示例** + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam and the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +我们可以看到,任何将扩展ActiveCreature的类都将具有自己的控制线程来执行和调用方法。 + +例如,兽人类: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` + +现在,我们可以创建多个生物,例如兽人,告诉他们吃东西和散步,然后他们将在自己的控制线程上执行它: + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## 类图 + +![alt text](./etc/active-object.urm.png "Active Object class diagram") diff --git a/localization/zh/active-object/etc/active-object.urm.png b/localization/zh/active-object/etc/active-object.urm.png new file mode 100644 index 000000000000..c14f66144ee2 Binary files /dev/null and b/localization/zh/active-object/etc/active-object.urm.png differ diff --git a/localization/zh/acyclic-visitor/README.md b/localization/zh/acyclic-visitor/README.md new file mode 100644 index 000000000000..ea76ae45cf46 --- /dev/null +++ b/localization/zh/acyclic-visitor/README.md @@ -0,0 +1,156 @@ +--- +title: Acyclic Visitor +shortTitle: Acyclic Visitor +category: Behavioral +language: zh +tag: + - Extensibility +--- + +## 目的 + +允许将新功能添加到现有的类层次结构中,而不会影响这些层次结构,也不会有四人帮访客模式中那样循环依赖的问题。 + +## 解释 + +真实世界例子 + +> 我们有一个调制解调器类的层次结构。 需要使用基于过滤条件的外部算法(是Unix或DOS兼容的调制解调器)来访问此层次结构中的调制解调器。 + +通俗地说 + +> 非循环访问者允许将功能添加到现有的类层次结构中,而无需修改层次结构 + +[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) 上说 + +> 非循环访客模式允许将新功能添加到现有的类层次结构中,而不会影响这些层次结构,也不会创建四人帮访客模式中固有的循环依赖问题。 + +**程序示例** + +这是调制解调器的层次结构。 + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + +下面我们介绍`调制解调器访问者`类结构。 + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + ... + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + ... + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +最后,这里是访问者的实践。 + +```java + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + var zoom = new Zoom(); + var hayes = new Hayes(); + hayes.accept(conDos); + zoom.accept(conDos); + hayes.accept(conUnix); + zoom.accept(conUnix); +``` + +程序输出: + +``` + // Hayes modem used with Dos configurator. + // Zoom modem used with Dos configurator. + // Only HayesVisitor is allowed to visit Hayes modem + // Zoom modem used with Unix configurator. +``` + +## 类图 + +![alt text](./etc/acyclic-visitor.png "Acyclic Visitor") + +## 适用性 + +以下情况可以使用此模式: + +* 需要在现有层次结构中添加新功能而无需更改或影响该层次结构时。 +* 当某些功能在层次结构上运行,但不属于层次结构本身时。 例如 ConfigureForDOS / ConfigureForUnix / ConfigureForX问题。 +* 当您需要根据对象的类型对对象执行非常不同的操作时。 +* 当访问的类层次结构将经常使用元素类的新派生进行扩展时。 +* 当重新编译,重新链接,重新测试或重新分发派生元素非常昂贵时。 + +## 结果 + +好处: + +* 类层次结构之间没有依赖关系循环。 +* 如果添加了新访客,则无需重新编译所有访客。 +* 如果类层次结构具有新成员,则不会导致现有访问者中的编译失败。 + +坏处: + +* 通过证明它可以接受所有访客,但实际上仅对特定访客感兴趣,从而违反了[Liskov的替代原则](https://java-design-patterns.com/principles/#liskov-substitution-principle) +* 必须为可访问的类层次结构中的所有成员创建访问者的并行层次结构。 + +## 相关的模式 + +* [Visitor Pattern](https://java-design-patterns.com/patterns/visitor/) + +## 鸣谢 + +* [Acyclic Visitor by Robert C. Martin](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor in WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) diff --git a/localization/zh/acyclic-visitor/etc/acyclic-visitor.png b/localization/zh/acyclic-visitor/etc/acyclic-visitor.png new file mode 100644 index 000000000000..7b4df13d80f8 Binary files /dev/null and b/localization/zh/acyclic-visitor/etc/acyclic-visitor.png differ diff --git a/localization/zh/adapter/README.md b/localization/zh/adapter/README.md new file mode 100644 index 000000000000..09bccc9c6b17 --- /dev/null +++ b/localization/zh/adapter/README.md @@ -0,0 +1,136 @@ +--- +title: Adapter +shortTitle: Adapter +category: Structural +language: zh +tag: + - Gang of Four +--- + +## 又被称为 +包装器 + +## 目的 +将一个接口转换成另一个客户所期望的接口。适配器让那些本来因为接口不兼容的类可以合作无间。 + +## 解释 + +现实世界例子 + +> 考虑有这么一种情况,在你的存储卡中有一些照片,你想将其传到你的电脑中。为了传送数据,你需要某种能够兼容你电脑接口的适配器以便你的储存卡能连上你的电脑。在这种情况下,读卡器就是一个适配器。 +> 另一个例子就是注明的电源适配器;三脚插头不能插在两脚插座上,需要一个电源适配器来使其能够插在两脚插座上。 +> 还有一个例子就是翻译官,他翻译一个人对另一个人说的话。 + +用直白的话来说 + +> 适配器模式让你可以把不兼容的对象包在适配器中,以让其兼容其他类。 + +维基百科中说 + +> 在软件工程中,适配器模式是一种可以让现有类的接口把其作为其他接口来使用的设计模式。它经常用来使现有的类和其他类能够工作并且不用修改其他类的源代码。 + +**编程样例(对象适配器)** + +假如有一个船长他只会划船,但不会航行。 + +首先我们有接口`RowingBoat`和`FishingBoat` + +```java +public interface RowingBoat { + void row(); +} + +@Slf4j +public class FishingBoat { + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } +} +``` +船长希望有一个`RowingBoat`接口的实现,这样就可以移动 + +```java +public class Captain { + + private final RowingBoat rowingBoat; + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +现在海盗来了,我们的船长需要逃跑但是只有一个渔船可用。我们需要创建一个可以让船长使用其划船技能来操作渔船的适配器。 + +```java +@Slf4j +public class FishingBoatAdapter implements RowingBoat { + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} + +``` + +现在 `船长` 可以使用`FishingBoat`接口来逃离海盗了。 + +```java +var captain = new Captain(new FishingBoatAdapter()); +captain.row(); +``` + +## 类图 +![alt text](./etc/adapter.urm.png "Adapter class diagram") + + +## 应用 +使用适配器模式当 + +* 你想使用一个已有类,但是它的接口不能和你需要的所匹配 +* 你需要创建一个可重用类,该类与不相关或不可预见的类进行协作,即不一定具有兼容接口的类 +* 你需要使用一些现有的子类,但是子类化他们每一个的子类来进行接口的适配是不现实的。一个对象适配器可以适配他们父类的接口。 +* 大多数使用第三方类库的应用使用适配器作为一个在应用和第三方类库间的中间层来使应用和类库解耦。如果必须使用另一个库,则只需使用一个新库的适配器而无需改变应用程序的代码。 + +## 后果: +类和对象适配器有不同的权衡取舍。一个类适配器 + +* 适配被适配者到目标接口,需要保证只有一个具体的被适配者类。作为结果,当我们想适配一个类和它所有的子类时,类适配器将不会起作用。 +* 可以让适配器重写一些被适配者的行为,因为适配器是被适配者的子类。 +* 只引入了一个对象,并且不需要其他指针间接访问被适配者。 + +对象适配器 + +* 一个适配器可以和许多被适配者工作,也就是被适配者自己和所有它的子类。适配器同时可以为所有被适配者添加功能。 +* 覆盖被适配者的行为变得更难。需要子类化被适配者然后让适配器引用这个子类不是被适配者。 + + +## 现实世界的案例 + +* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +* [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +* [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) + +``` + +``` \ No newline at end of file diff --git a/localization/zh/adapter/etc/adapter.urm.png b/localization/zh/adapter/etc/adapter.urm.png new file mode 100644 index 000000000000..341ad67699d9 Binary files /dev/null and b/localization/zh/adapter/etc/adapter.urm.png differ diff --git a/localization/zh/aggregator-microservices/README.md b/localization/zh/aggregator-microservices/README.md new file mode 100644 index 000000000000..bbdf83ec4981 --- /dev/null +++ b/localization/zh/aggregator-microservices/README.md @@ -0,0 +1,106 @@ +--- +title: Aggregator Microservices +shortTitle: Aggregator Microservices +category: Architectural +language: zh +tag: +- Cloud distributed +- Decoupling +- Microservices +--- + +## 意图 + +用户对聚合器服务进行一次调用,然后聚合器将调用每个相关的微服务。 + +## 解释 + +真实世界例子 + +> 我们的网络市场需要有关产品及其当前库存的信息。 它调用聚合服务,聚合服务依次调用产品信息微服务和产品库存微服务,返回组合信息。 + +通俗地说 + +> 聚合器微服务从各种微服务中收集数据,并返回一个聚合数据以进行处理。 + +Stack Overflow上说 + +> 聚合器微服务调用多个服务以实现应用程序所需的功能。 + +**程序示例** + +让我们从数据模型开始。 这是我们的`产品`。 + +```java +public class Product { + private String title; + private int productInventories; + // getters and setters -> + ... +} +``` + +接下来,我们将介绍我们的聚合器微服务。 它包含用于调用相应微服务的客户端`ProductInformationClient`和` ProductInventoryClient`。 + +```java +@RestController +public class Aggregator { + + @Resource + private ProductInformationClient informationClient; + + @Resource + private ProductInventoryClient inventoryClient; + + @RequestMapping(path = "/product", method = RequestMethod.GET) + public Product getProduct() { + + var product = new Product(); + var productTitle = informationClient.getProductTitle(); + var productInventory = inventoryClient.getProductInventories(); + + //Fallback to error message + product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed")); + + //Fallback to default error inventory + product.setProductInventories(requireNonNullElse(productInventory, -1)); + + return product; + } +} +``` + +这是产品信息微服务的精华实现。 库存微服务类似,它只返回库存计数。 + +```java +@RestController +public class InformationController { + @RequestMapping(value = "/information", method = RequestMethod.GET) + public String getProductTitle() { + return "The Product Title."; + } +} +``` + +Now calling our `Aggregator` REST API returns the product information. + +现在调用我们的聚合器 REST API会返回产品信息。 + +```bash +curl http://localhost:50004/product +{"title":"The Product Title.","productInventories":5} +``` + +## 类图 + +![alt text](./etc/aggregator-service.png "Aggregator Microservice") + +## 适用性 + +当需要各种微服务的统一API时,无论客户端设备如何,都可以使用Aggregator微服务模式。 + +## 鸣谢 + +* [Microservice Design Patterns](http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/) +* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=8b4e570267bc5fb8b8189917b461dc60) +* [Architectural Patterns: Uncover essential patterns in the most indispensable realm of enterprise architecture](https://www.amazon.com/gp/product/B077T7V8RC/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B077T7V8RC&linkId=c34d204bfe1b277914b420189f09c1a4) diff --git a/localization/zh/aggregator-microservices/etc/aggregator-service.png b/localization/zh/aggregator-microservices/etc/aggregator-service.png new file mode 100644 index 000000000000..75ee82328bbe Binary files /dev/null and b/localization/zh/aggregator-microservices/etc/aggregator-service.png differ diff --git a/localization/zh/ambassador/README.md b/localization/zh/ambassador/README.md new file mode 100644 index 000000000000..1ddc4188c9d6 --- /dev/null +++ b/localization/zh/ambassador/README.md @@ -0,0 +1,195 @@ +--- +title: Ambassador +shortTitle: Ambassador +category: Structural +language: zh +tag: + - Decoupling + - Cloud distributed +--- + +## 目的 + +在客户端上提供帮助程序服务实例,并从共享资源上转移常用功能。 + +## 解释 + +真实世界例子 + +> 远程服务有许多客户端访问它提供的功能。 该服务是旧版应用程序,无法更新。 用户的大量请求导致连接问题。新的请求频率规则需要同时实现延迟检测和客户端日志功能。 + +通俗的说 + +> 使用“大使”模式,我们可以实现来自客户端的频率较低的轮询以及延迟检查和日志记录。 + +微软文档做了如下阐述 + +> 可以将大使服务视为与客户端位于同一位置的进程外代理。 此模式对于以语言不可知的方式减轻常见的客户端连接任务(例如监视,日志记录,路由,安全性(如TLS)和弹性模式)的工作很有用。 它通常与旧版应用程序或其他难以修改的应用程序一起使用,以扩展其网络功能。 它还可以使专业团队实现这些功能。 + +**程序示例** + +有了上面的介绍我们将在这个例子中模仿功能。我们有一个用远程服务实现的接口,同时也是大使服务。 + +```java +interface RemoteServiceInterface { + long doRemoteFunction(int value) throws Exception; +} +``` + +表示为单例的远程服务。 + +```java +public class RemoteService implements RemoteServiceInterface { + + private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class); + private static RemoteService service = null; + + static synchronized RemoteService getRemoteService() { + if (service == null) { + service = new RemoteService(); + } + return service; + } + + private RemoteService() {} + + @Override + public long doRemoteFunction(int value) { + long waitTime = (long) Math.floor(Math.random() * 1000); + + try { + sleep(waitTime); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep interrupted", e); + } + + return waitTime >= 200 ? value * 10 : -1; + } +} +``` + +服务大使添加了像日志和延迟检测的额外功能 + +```java +public class ServiceAmbassador implements RemoteServiceInterface { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceAmbassador.class); + private static final int RETRIES = 3; + private static final int DELAY_MS = 3000; + + ServiceAmbassador() { + } + + @Override + public long doRemoteFunction(int value) { + return safeCall(value); + } + + private long checkLatency(int value) { + var startTime = System.currentTimeMillis(); + var result = RemoteService.getRemoteService().doRemoteFunction(value); + var timeTaken = System.currentTimeMillis() - startTime; + + LOGGER.info("Time taken (ms): " + timeTaken); + return result; + } + + private long safeCall(int value) { + var retries = 0; + var result = (long) FAILURE; + + for (int i = 0; i < RETRIES; i++) { + if (retries >= RETRIES) { + return FAILURE; + } + + if ((result = checkLatency(value)) == FAILURE) { + LOGGER.info("Failed to reach remote: (" + (i + 1) + ")"); + retries++; + try { + sleep(DELAY_MS); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep state interrupted", e); + } + } else { + break; + } + } + return result; + } +} +``` + +客户端具有用于与远程服务进行交互的本地服务大使: + +```java +public class Client { + + private static final Logger LOGGER = LoggerFactory.getLogger(Client.class); + private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador(); + + long useService(int value) { + var result = serviceAmbassador.doRemoteFunction(value); + LOGGER.info("Service result: " + result); + return result; + } +} +``` + +这是两个使用该服务的客户端。 + +```java +public class App { + public static void main(String[] args) { + var host1 = new Client(); + var host2 = new Client(); + host1.useService(12); + host2.useService(73); + } +} +``` + +Here's the output for running the example: + +```java +Time taken (ms): 111 +Service result: 120 +Time taken (ms): 931 +Failed to reach remote: (1) +Time taken (ms): 665 +Failed to reach remote: (2) +Time taken (ms): 538 +Failed to reach remote: (3) +Service result: -1 +``` + +## 类图 + +![alt text](./etc/ambassador.urm.png "Ambassador class diagram") + +## 适用性 + +大使适用于无法修改或极难修改的旧式远程服务。 可以在客户端上实现连接性的功能,而无需更改远程服务。 + +* 大使提供了用于远程服务的本地接口。 +* 大使在客户端上提供日志记录,断路,重试和安全性。 + +## 典型用例 + +* 控制对另一个对象的访问 +* 实现日志 +* 卸载远程服务任务 +* 简化网络连接 + +## 已知使用 + +* [Kubernetes-native API gateway for microservices](https://github.com/datawire/ambassador) + +## 相关模式 + +* [Proxy](https://java-design-patterns.com/patterns/proxy/) + +## 鸣谢 + +* [Ambassador pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador) +* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://books.google.co.uk/books?id=6BJNDwAAQBAJ&pg=PT35&lpg=PT35&dq=ambassador+pattern+in+real+world&source=bl&ots=d2e7GhYdHi&sig=Lfl_MDnCgn6lUcjzOg4GXrN13bQ&hl=en&sa=X&ved=0ahUKEwjk9L_18rrbAhVpKcAKHX_KA7EQ6AEIWTAI#v=onepage&q=ambassador%20pattern%20in%20real%20world&f=false) diff --git a/localization/zh/ambassador/etc/ambassador.urm.png b/localization/zh/ambassador/etc/ambassador.urm.png new file mode 100644 index 000000000000..9b50a02ad356 Binary files /dev/null and b/localization/zh/ambassador/etc/ambassador.urm.png differ diff --git a/localization/zh/api-gateway/README.md b/localization/zh/api-gateway/README.md new file mode 100644 index 000000000000..7b8996a5769c --- /dev/null +++ b/localization/zh/api-gateway/README.md @@ -0,0 +1,137 @@ +--- +title: API Gateway +shortTitle: API Gateway +category: Architectural +language: zh +tag: + - Cloud distributed + - Decoupling + - Microservices +--- + +## 目的 + +API网关将所有对微服务的调用聚合到一起。用户对API网关进行一次调用,然后API网关调用每个相关的微服务。 + +## 解释 + +使用微服务模式,客户端可能需要来自多个不同微服务的数据。 如果客户端直接调用每个微服务,则可能会导致更长的加载时间,因为客户端将不得不为每个调用的微服务发出网络请求。此外,让客户端调用每个微服务会直接将客户端与该微服务相关联-如果微服务的内部实现发生了变化(例如,如果将来某个时候合并了两个微服务),或者微服务的位置(主机和端口) 更改,则必须更新使用这些微服务的每个客户端。 + +API网关模式的目的是缓解其中的一些问题。 在API网关模式中,在客户端和微服务之间放置了一个附加实体(API网关)。API网关的工作是将对微服务的调用进行聚合。 客户端不是一次单独调用每个微服务,而是一次调用API网关。 然后,API网关调用客户端所需的每个微服务。 + +真实世界例子 + +> 我们正在为电子商务站点实现微服务和API网关模式。 在此系统中,API网关调用Image和Price微服务。 + +通俗地说 + +> 对于使用微服务架构实现的系统,API是聚合微服务调用的入口点。 + +维基百科说 + +> API网关是充当API前置,接收API请求,执行限制和安全策略,将请求传递到后端服务,然后将响应传递回请求者的服务器。网关通常包括一个转换引擎,以实时地编排和修改请求和响应。 网关可以提供收集分析数据和提供缓存等功能。网关还可以提供支持身份验证,授权,安全性,审计和法规遵从性的功能。 + +**程序示例** + +此实现展示了电子商务站点的API网关模式。` ApiGateway`分别使用` ImageClientImpl`和` PriceClientImpl`来调用Image和Price微服务。 在桌面设备上查看该网站的客户可以看到价格信息和产品图片,因此` ApiGateway`会调用这两种微服务并在`DesktopProduct`模型中汇总数据。 但是,移动用户只能看到价格信息。 他们看不到产品图片。 对于移动用户,`ApiGateway`仅检索价格信息,并将其用于填充`MobileProduct`模型。 + +这个是图像微服务的实现。 + +```java +public interface ImageClient { + String getImagePath(); +} + +public class ImageClientImpl implements ImageClient { + @Override + public String getImagePath() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50005/image-path")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +这里是价格服务的实现。 + +```java +public interface PriceClient { + String getPrice(); +} + +public class PriceClientImpl implements PriceClient { + + @Override + public String getPrice() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50006/price")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +在这里,我们可以看到API网关如何将请求映射到微服务。 + +```java +public class ApiGateway { + + @Resource + private ImageClient imageClient; + + @Resource + private PriceClient priceClient; + + @RequestMapping(path = "/desktop", method = RequestMethod.GET) + public DesktopProduct getProductDesktop() { + var desktopProduct = new DesktopProduct(); + desktopProduct.setImagePath(imageClient.getImagePath()); + desktopProduct.setPrice(priceClient.getPrice()); + return desktopProduct; + } + + @RequestMapping(path = "/mobile", method = RequestMethod.GET) + public MobileProduct getProductMobile() { + var mobileProduct = new MobileProduct(); + mobileProduct.setPrice(priceClient.getPrice()); + return mobileProduct; + } +} +``` + +## 类图 +![alt text](./etc/api-gateway.png "API Gateway") + +## 适用性 + +在以下情况下使用API网关模式 + +* 你正在使用微服务架构,并且需要聚合单点来进行微服务调用。 + +## 鸣谢 + +* [microservices.io - API Gateway](http://microservices.io/patterns/apigateway.html) +* [NGINX - Building Microservices: Using an API Gateway](https://www.nginx.com/blog/building-microservices-using-an-api-gateway/) +* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=ac7b6a57f866ac006a309d9086e8cfbd) +* [Building Microservices: Designing Fine-Grained Systems](https://www.amazon.com/gp/product/1491950358/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1491950358&linkId=4c95ca9831e05e3f0dadb08841d77bf1) diff --git a/localization/zh/api-gateway/etc/api-gateway.png b/localization/zh/api-gateway/etc/api-gateway.png new file mode 100644 index 000000000000..bb3ec2e2e1a8 Binary files /dev/null and b/localization/zh/api-gateway/etc/api-gateway.png differ diff --git a/localization/zh/arrange-act-assert/README.md b/localization/zh/arrange-act-assert/README.md new file mode 100644 index 000000000000..c115589509bf --- /dev/null +++ b/localization/zh/arrange-act-assert/README.md @@ -0,0 +1,138 @@ +--- +title: Arrange/Act/Assert +shortTitle: Arrange/Act/Assert +category: Idiom +language: zh +tag: + - Testing +--- + +## 或称 + +Given/When/Then + +## 意图 + +安排/执行/断言(AAA)是组织单元测试的一种模式。 + +它将测试分为三个清晰而独特的步骤: + +1. 安排:执行测试所需的设置和初始化。 +2. 执行:采取测试所需的行动。 +3. 断言:验证测试结果。 + +## 解释 + +这种模式有几个明显的好处。 它在测试的设置,操作和结果之间建立了清晰的分隔。 这种结构使代码更易于阅读和理解。 如果按顺序排列步骤并格式化代码以将它们分开,则可以扫描测试并快速了解其功能。 + +当您编写测试时,它还会强制执行一定程度的纪律。 您必须清楚地考虑您的测试将执行的三个步骤。 由于您已经有了大纲,因此可以使同时编写测试变得更加自然。 + +真实世界例子 + +> 我们需要为一个类编写全面而清晰的单元测试套件。 + +通俗地说 + +> 安排/执行/断言是一种测试模式,将测试分为三个清晰的步骤以方便维护。 + +WikiWikiWeb 上说 + +> 安排/执行/断言是用于在单元测试方法中排列和格式化代码的模式。 + +**程序示例** + +让我们首先介绍要进行单元测试的`Cash`类。 + +```java +public class Cash { + + private int amount; + + Cash(int amount) { + this.amount = amount; + } + + void plus(int addend) { + amount += addend; + } + + boolean minus(int subtrahend) { + if (amount >= subtrahend) { + amount -= subtrahend; + return true; + } else { + return false; + } + } + + int count() { + return amount; + } +} +``` + +然后我们根据安排/ 执行 / 断言模式编写单元测试。 注意每个单元测试的步骤是分开的清晰的。 + +```java +class CashAAATest { + + @Test + void testPlus() { + //Arrange + var cash = new Cash(3); + //Act + cash.plus(4); + //Assert + assertEquals(7, cash.count()); + } + + @Test + void testMinus() { + //Arrange + var cash = new Cash(8); + //Act + var result = cash.minus(5); + //Assert + assertTrue(result); + assertEquals(3, cash.count()); + } + + @Test + void testInsufficientMinus() { + //Arrange + var cash = new Cash(1); + //Act + var result = cash.minus(6); + //Assert + assertFalse(result); + assertEquals(1, cash.count()); + } + + @Test + void testUpdate() { + //Arrange + var cash = new Cash(5); + //Act + cash.plus(6); + var result = cash.minus(3); + //Assert + assertTrue(result); + assertEquals(8, cash.count()); + } +} +``` + +## 适用性 + +使用 安排/执行/断言 模式当 + +* 你需要结构化你的单元测试代码这样它们可以更好的阅读,维护和增强。 + +## 鸣谢 + +* [Arrange, Act, Assert: What is AAA Testing?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx) +* [Bill Wake: 3A – Arrange, Act, Assert](https://xp123.com/articles/3a-arrange-act-assert/) +* [Martin Fowler: GivenWhenThen](https://martinfowler.com/bliki/GivenWhenThen.html) +* [xUnit Test Patterns: Refactoring Test Code](https://www.amazon.com/gp/product/0131495054/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0131495054&linkId=99701e8f4af2f7e8dd50d720c9b63dbf) +* [Unit Testing Principles, Practices, and Patterns](https://www.amazon.com/gp/product/1617296279/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617296279&linkId=74c75cf22a63c3e4758ae08aa0a0cc35) +* [Test Driven Development: By Example](https://www.amazon.com/gp/product/0321146530/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321146530&linkId=5c63a93d8c1175b84ca5087472ef0e05) diff --git a/localization/zh/async-method-invocation/README.md b/localization/zh/async-method-invocation/README.md new file mode 100644 index 000000000000..b8bc62ae3577 --- /dev/null +++ b/localization/zh/async-method-invocation/README.md @@ -0,0 +1,158 @@ +--- +title: Async Method Invocation +shortTitle: Async Method Invocation +category: Concurrency +language: zh +tag: + - Reactive +--- + +## 意图 + +异步方法调用是一个调用线程在等待任务结果时不会阻塞的模式。模式为多个独立的任务提供并行的处理方式并且通过回调或等到它们全部完成来接收任务结果。 + +## 解释 + +真实世界例子 + +> 发射火箭是一项令人激动的事务。任务指挥官发出了发射命令,经过一段不确定的时间后,火箭要么成功发射,要么惨遭失败。 + +通俗地说 + +> 异步方法调用开始任务处理,并在任务完成之前立即返回。 任务处理的结果稍后返回给调用方。 + +维基百科说 + +> 在多线程计算机编程中,异步方法调用(AMI),也称为异步方法调用或异步模式,是一种设计模式,其中在等待被调用的代码完成时不会阻塞调用站点。 而是在执行结果到达时通知调用线程。轮询调用结果是不希望的选项。 + +**程序示例** + +在此示例中,我们正在发射太空火箭并部署月球漫游车。该应用演示了异步方法调用模式。 模式的关键部分是`AsyncResult`(用于异步评估值的中间容器),`AsyncCallback`(可以在任务完成时被执行)和`AsyncExecutor`(用于管理异步任务的执行)。 + +```java +public interface AsyncResult { + boolean isCompleted(); + T getValue() throws ExecutionException; + void await() throws InterruptedException; +} +``` + +```java +public interface AsyncCallback { + void onComplete(T value, Optional ex); +} +``` + +```java +public interface AsyncExecutor { + AsyncResult startProcess(Callable task); + AsyncResult startProcess(Callable task, AsyncCallback callback); + T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException; +} +``` + +`ThreadAsyncExecutor`是`AsyncExecutor`的实现。 接下来将突出显示其一些关键部分。 + +```java +public class ThreadAsyncExecutor implements AsyncExecutor { + + @Override + public AsyncResult startProcess(Callable task) { + return startProcess(task, null); + } + + @Override + public AsyncResult startProcess(Callable task, AsyncCallback callback) { + var result = new CompletableResult<>(callback); + new Thread( + () -> { + try { + result.setValue(task.call()); + } catch (Exception ex) { + result.setException(ex); + } + }, + "executor-" + idx.incrementAndGet()) + .start(); + return result; + } + + @Override + public T endProcess(AsyncResult asyncResult) + throws ExecutionException, InterruptedException { + if (!asyncResult.isCompleted()) { + asyncResult.await(); + } + return asyncResult.getValue(); + } +} +``` + +然后,我们准备发射一些火箭,看看一切是如何协同工作的。 + +```java +public static void main(String[] args) throws Exception { + // 构造一个将执行异步任务的新执行程序 + var executor = new ThreadAsyncExecutor(); + + // 以不同的处理时间开始一些异步任务,最后两个使用回调处理程序 + final var asyncResult1 = executor.startProcess(lazyval(10, 500)); + final var asyncResult2 = executor.startProcess(lazyval("test", 300)); + final var asyncResult3 = executor.startProcess(lazyval(50L, 700)); + final var asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Deploying lunar rover")); + final var asyncResult5 = + executor.startProcess(lazyval("callback", 600), callback("Deploying lunar rover")); + + // 在当前线程中模拟异步任务正在它们自己的线程中执行 + Thread.sleep(350); // 哦,兄弟,我们在这很辛苦 + log("Mission command is sipping coffee"); + + // 等待任务完成 + final var result1 = executor.endProcess(asyncResult1); + final var result2 = executor.endProcess(asyncResult2); + final var result3 = executor.endProcess(asyncResult3); + asyncResult4.await(); + asyncResult5.await(); + + // log the results of the tasks, callbacks log immediately when complete + // 记录任务结果的日志, 回调的日志会在回调完成时立刻记录 + log("Space rocket <" + result1 + "> launch complete"); + log("Space rocket <" + result2 + "> launch complete"); + log("Space rocket <" + result3 + "> launch complete"); +} +``` + +这是程序控制台的输出。 + +```java +21:47:08.227 [executor-2] INFO com.iluwatar.async.method.invocation.App - Space rocket launched successfully +21:47:08.269 [main] INFO com.iluwatar.async.method.invocation.App - Mission command is sipping coffee +21:47:08.318 [executor-4] INFO com.iluwatar.async.method.invocation.App - Space rocket <20> launched successfully +21:47:08.335 [executor-4] INFO com.iluwatar.async.method.invocation.App - Deploying lunar rover <20> +21:47:08.414 [executor-1] INFO com.iluwatar.async.method.invocation.App - Space rocket <10> launched successfully +21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - Space rocket launched successfully +21:47:08.519 [executor-5] INFO com.iluwatar.async.method.invocation.App - Deploying lunar rover +21:47:08.616 [executor-3] INFO com.iluwatar.async.method.invocation.App - Space rocket <50> launched successfully +21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - Space rocket <10> launch complete +21:47:08.617 [main] INFO com.iluwatar.async.method.invocation.App - Space rocket launch complete +21:47:08.618 [main] INFO com.iluwatar.async.method.invocation.App - Space rocket <50> launch complete +``` + +# 类图 + +![alt text](./etc/async-method-invocation.png "Async Method Invocation") + +## 适用性 + +在以下情况下使用异步方法调用模式 + +* 您有多个可以并行运行的独立任务 +* 您需要提高一组顺序任务的性能 +* 您的处理能力或长时间运行的任务数量有限,并且调用方不应等待任务执行完毕 + +## 真实世界例子 + +* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html) +* [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) +* [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) +* [Task-based Asynchronous Pattern](https://msdn.microsoft.com/en-us/library/hh873175.aspx) diff --git a/localization/zh/async-method-invocation/etc/async-method-invocation.png b/localization/zh/async-method-invocation/etc/async-method-invocation.png new file mode 100644 index 000000000000..764895d7a217 Binary files /dev/null and b/localization/zh/async-method-invocation/etc/async-method-invocation.png differ diff --git a/localization/zh/balking/README.md b/localization/zh/balking/README.md new file mode 100644 index 000000000000..de7c25717f89 --- /dev/null +++ b/localization/zh/balking/README.md @@ -0,0 +1,129 @@ +--- +title: Balking +shortTitle: Balking +category: Concurrency +language: zh +tag: + - Decoupling +--- + +## 意图 + +止步模式用于防止对象在不完整或不合适的状态下执行某些代码。 + +## 解释 + +真实世界例子 + +> 洗衣机中有一个开始按钮,用于启动衣物洗涤。当洗衣机处于非活动状态时,按钮将按预期工作,但是如果已经在洗涤,则按钮将不起任何作用。 + +通俗地说 + +> 使用止步模式,仅当对象处于特定状态时才执行特定代码。 + +维基百科说 + +> 禁止模式是一种软件设计模式,仅当对象处于特定状态时才对对象执行操作。例如,一个对象读取zip压缩文件并在压缩文件没打开的时候调用get方法,对象将在请求的时候”止步“。 + +**程序示例** + +在此示例中,` WashingMachine`是一个具有两个状态的对象,可以处于两种状态:ENABLED和WASHING。 如果机器已启用,则使用线程安全方法将状态更改为WASHING。 另一方面,如果已经进行了清洗并且任何其他线程执行`wash()`,则它将不执行该操作,而是不执行任何操作而返回。 + +这里是`WashingMachine` 类相关的部分。 + +```java +@Slf4j +public class WashingMachine { + + private final DelayProvider delayProvider; + private WashingMachineState washingMachineState; + + public WashingMachine(DelayProvider delayProvider) { + this.delayProvider = delayProvider; + this.washingMachineState = WashingMachineState.ENABLED; + } + + public WashingMachineState getWashingMachineState() { + return washingMachineState; + } + + public void wash() { + synchronized (this) { + var machineState = getWashingMachineState(); + LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState); + if (this.washingMachineState == WashingMachineState.WASHING) { + LOGGER.error("Cannot wash if the machine has been already washing!"); + return; + } + this.washingMachineState = WashingMachineState.WASHING; + } + LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); + this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing); + } + + public synchronized void endOfWashing() { + washingMachineState = WashingMachineState.ENABLED; + LOGGER.info("{}: Washing completed.", Thread.currentThread().getId()); + } +} +``` + +这里是一个`WashingMachine`所使用的`DelayProvider`简单接口。 + +```java +public interface DelayProvider { + void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task); +} +``` + +现在,我们使用`WashingMachine`介绍该应用程序。 + +```java + public static void main(String... args) { + final var washingMachine = new WashingMachine(); + var executorService = Executors.newFixedThreadPool(3); + for (int i = 0; i < 3; i++) { + executorService.execute(washingMachine::wash); + } + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + LOGGER.error("ERROR: Waiting on executor service shutdown!"); + Thread.currentThread().interrupt(); + } + } +``` + +下面是程序的输出。 + +``` +14:02:52.268 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Actual machine state: ENABLED +14:02:52.272 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Doing the washing +14:02:52.272 [pool-1-thread-3] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-3: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-3] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.273 [pool-1-thread-1] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-1: Actual machine state: WASHING +14:02:52.273 [pool-1-thread-1] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing! +14:02:52.324 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - 14: Washing completed. +``` + +## 类图 + +![alt text](./etc/balking.png "Balking") + +## 适用性 + + +使用止步模式当 + +* 您只想在对象处于特定状态时才对其调用操作 +* 对象通常仅处于容易暂时停止但状态未知的状态 + +## 相关模式 + +* [保护性暂挂模式](https://java-design-patterns.com/patterns/guarded-suspension/) +* [双重检查锁模式](https://java-design-patterns.com/patterns/double-checked-locking/) + +## 鸣谢 + +* [Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML, 2nd Edition, Volume 1](https://www.amazon.com/gp/product/0471227293/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0471227293&linkId=0e39a59ffaab93fb476036fecb637b99) diff --git a/localization/zh/balking/etc/balking.png b/localization/zh/balking/etc/balking.png new file mode 100644 index 000000000000..f409eaacbb95 Binary files /dev/null and b/localization/zh/balking/etc/balking.png differ diff --git a/localization/zh/bridge/README.md b/localization/zh/bridge/README.md new file mode 100644 index 000000000000..53771df805da --- /dev/null +++ b/localization/zh/bridge/README.md @@ -0,0 +1,204 @@ +--- +title: Bridge +shortTitle: Bridge +category: Structural +language: zh +tag: + - Gang of Four +--- + +## 又被称为 + +手柄/身体模式 + +## 目的 + +将抽象与其实现分离,以便二者可以独立变化。 + +## 解释 + +真实世界例子 + +> 考虑一下你拥有一种具有不同附魔的武器,并且应该允许将具有不同附魔的不同武器混合使用。 你会怎么做? 为每个附魔创建每种武器的多个副本,还是只是创建单独的附魔并根据需要为武器设置它? 桥接模式使您可以进行第二次操作。 + +通俗的说 + +> 桥接模式是一个更推荐组合而不是继承的模式。将实现细节从一个层次结构推送到具有单独层次结构的另一个对象。 + +维基百科说 + +> 桥接模式是软件工程中使用的一种设计模式,旨在“将抽象与其实现分离,从而使两者可以独立变化” + +**程序示例** + +翻译一下上面的武器示例。下面我们有武器的类层级: + +```java +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; + } +} +``` + +这里是单独的附魔类结构: + +```java +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."); + } +} +``` + +这里是两种层次结构的实践: + +```java +var 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. + +var 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. +``` + + + +## 类图 + +![alt text](./etc/bridge.urm.png "Bridge class diagram") + +## 适用性 + +使用桥接模式当 + +* 你想永久性的避免抽象和他的实现之间的绑定。有可能是这种情况,当实现需要被选择或者在运行时切换。 +* 抽象和他们的实现应该能通过写子类来扩展。这种情况下,桥接模式让你可以组合不同的抽象和实现并独立的扩展他们。 +* 对抽象的实现的改动应当不会对客户产生影响;也就是说,他们的代码不必重新编译。 +* 你有种类繁多的类。这样的类层次结构表明需要将一个对象分为两部分。Rumbaugh 使用术语“嵌套归纳”来指代这种类层次结构。 +* 你想在多个对象间分享一种实现(可能使用引用计数),这个事实应该对客户隐藏。一个简单的示例是Coplien的String类,其中多个对象可以共享同一字符串表示形式 + +## 教程 + +* [Bridge Pattern Tutorial](https://www.journaldev.com/1491/bridge-design-pattern-java) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/zh/bridge/etc/bridge.urm.png b/localization/zh/bridge/etc/bridge.urm.png new file mode 100644 index 000000000000..785585bf8163 Binary files /dev/null and b/localization/zh/bridge/etc/bridge.urm.png differ diff --git a/localization/zh/builder/README.md b/localization/zh/builder/README.md new file mode 100644 index 000000000000..87f581a2c420 --- /dev/null +++ b/localization/zh/builder/README.md @@ -0,0 +1,138 @@ +--- +title: Builder +shortTitle: Builder +category: Creational +language: zh +tag: + - Gang of Four + +--- + +## 目的 + +将复杂对象的构造与其表示分开,以便同一构造过程可以创建不同的表示。 + +## 解释 + +现实世界例子 + +> 想象一个角色扮演游戏的角色生成器。最简单的选择是让计算机为你创建角色。但是如果你想选择一些像专业,性别,发色等角色细节时,这个角色生成就变成了一个渐进的过程。当所有选择完成时,该过程也将完成。 + +用通俗的话说 + +> 允许你创建不同口味的对象同时避免构造器污染。当一个对象可能有几种口味,或者一个对象的创建涉及到很多步骤时会很有用。 + +维基百科说 + +> 建造者模式是一种对象创建的软件设计模式,旨在为伸缩构造器反模式寻找一个解决方案。 + +说了这么多,让我补充一下什么是伸缩构造函数反模式。我们肯定都见过像下面这样的构造器: + +```java +public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) { +} +``` + +就像你看到的构造器参数的数量很快就会失控同时参数的排列方式可能变得难以理解。另外,如果您将来希望添加更多选项,则此参数列表可能会继续增长。这就被称伸缩构造器反模式。 + +**编程示例** + +明智的选择是使用建造者模式。首先我们有一个英雄要创建。 + +```java +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; + } +} +``` + +然后我们有创建者 + +```java + 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); + } + } +``` + +然后可以这样使用 + +```java +var mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build(); +``` + +## 类图 + +![alt text](./etc/builder.urm.png "Builder class diagram") + +## 适用性 + +使用建造者模式当 + +* 创建复杂对象的算法应独立于组成对象的零件及其组装方式 +* 构造过程必须允许所构造的对象具有不同的表示形式 + +## Java世界例子 + +* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) +* [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) as well as similar buffers such as FloatBuffer, IntBuffer and so on. +* [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) +* All implementations of [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) +* [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) \ No newline at end of file diff --git a/localization/zh/builder/etc/builder.urm.png b/localization/zh/builder/etc/builder.urm.png new file mode 100644 index 000000000000..d77808d36097 Binary files /dev/null and b/localization/zh/builder/etc/builder.urm.png differ diff --git a/localization/zh/business-delegate/README.md b/localization/zh/business-delegate/README.md new file mode 100644 index 000000000000..337e90ea6ea4 --- /dev/null +++ b/localization/zh/business-delegate/README.md @@ -0,0 +1,154 @@ +--- +title: Business Delegate +shortTitle: Business Delegate +category: Structural +language: zh +tag: + - Decoupling +--- + +## 意图 + +业务委托模式在表示层和业务层之间添加了一个抽象层。 通过使用该模式,我们获得了各层之间的松散耦合,并封装了有关如何定位,连接到组成应用程序的业务对象以及与之交互的逻辑。 + +## 解释 + +真实世界例子 + +> 手机应用程序承诺将现有的任何电影流式传输到您的手机。它捕获用户的搜索字符串,并将其传递给业务委托层。业务委托层选择最合适的视频流服务,然后从那里播放视频。 + +通俗的说 + +> 业务委托模式在表示层和业务层之间添加了一个抽象层。 + +维基百科说 + +> 业务委托是一种Java EE设计模式。 该模式旨在减少业务服务与连接的表示层之间的耦合,并隐藏服务的实现细节(包括EJB体系结构的查找和可访问性)。 业务代表充当适配器,以从表示层调用业务对象。 + +**程序示例** + +首先,我们有视频流服务的抽象类和一些它的实现。 + +```java +public interface VideoStreamingService { + void doProcessing(); +} + +@Slf4j +public class NetflixService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("NetflixService is now processing"); + } +} + +@Slf4j +public class YouTubeService implements VideoStreamingService { + @Override + public void doProcessing() { + LOGGER.info("YouTubeService is now processing"); + } +} +``` + +然后我们有一个查找服务来决定我们使用哪个视频流服务。 + +```java +@Setter +public class BusinessLookup { + + private NetflixService netflixService; + private YouTubeService youTubeService; + + public VideoStreamingService getBusinessService(String movie) { + if (movie.toLowerCase(Locale.ROOT).contains("die hard")) { + return netflixService; + } else { + return youTubeService; + } + } +} +``` + +业务委托类使用业务查找服务将电影播放请求路由到合适的视频流服务。 + +```java +@Setter +public class BusinessDelegate { + + private BusinessLookup lookupService; + + public void playbackMovie(String movie) { + VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie); + videoStreamingService.doProcessing(); + } +} +``` + +移动客户端利用业务委托来调用业务层。 + +```java +public class MobileClient { + + private final BusinessDelegate businessDelegate; + + public MobileClient(BusinessDelegate businessDelegate) { + this.businessDelegate = businessDelegate; + } + + public void playbackMovie(String movie) { + businessDelegate.playbackMovie(movie); + } +} +``` + +最后我们展示完整示例。 + +```java + public static void main(String[] args) { + + // prepare the objects + var businessDelegate = new BusinessDelegate(); + var businessLookup = new BusinessLookup(); + businessLookup.setNetflixService(new NetflixService()); + businessLookup.setYouTubeService(new YouTubeService()); + businessDelegate.setLookupService(businessLookup); + + // create the client and use the business delegate + var client = new MobileClient(businessDelegate); + client.playbackMovie("Die Hard 2"); + client.playbackMovie("Maradona: The Greatest Ever"); + } +``` + +这是控制台的输出。 + +``` +21:15:33.790 [main] INFO com.iluwatar.business.delegate.NetflixService - NetflixService is now processing +21:15:33.794 [main] INFO com.iluwatar.business.delegate.YouTubeService - YouTubeService is now processing +``` + +## 类图 + +![alt text](./etc/business-delegate.urm.png "Business Delegate") + +## 相关模式 + +* [服务定位器模式](https://java-design-patterns.com/patterns/service-locator/) + +## 适用性 + +使用业务委托模式当 + +* 你希望表示层和业务层之间的松散耦合 +* 你想编排对多个业务服务的调用 +* 你希望封装查找服务和服务调用 + +## 教程 + +* [Business Delegate Pattern at TutorialsPoint](https://www.tutorialspoint.com/design_pattern/business_delegate_pattern.htm) + +## 鸣谢 + +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Core J2EE Patterns: Best Practices and Design Strategies](https://www.amazon.com/gp/product/0130648841/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0130648841&linkId=a0100de2b28c71ede8db1757fb2b5947) diff --git a/localization/zh/business-delegate/etc/business-delegate.urm.png b/localization/zh/business-delegate/etc/business-delegate.urm.png new file mode 100644 index 000000000000..4dca6c263b99 Binary files /dev/null and b/localization/zh/business-delegate/etc/business-delegate.urm.png differ diff --git a/localization/zh/bytecode/README.md b/localization/zh/bytecode/README.md new file mode 100644 index 000000000000..e7b4a5717b5a --- /dev/null +++ b/localization/zh/bytecode/README.md @@ -0,0 +1,233 @@ +--- +title: Bytecode +shortTitle: Bytecode +category: Behavioral +language: zh +tag: + - Game programming +--- + +## 意图 + +允许编码行为作为虚拟机的指令。 + +## 解释 + +真实世界例子 + +> 一个团队正在开发一款新的巫师对战游戏。巫师的行为需要经过精心的调整和上百次的游玩测试。每次当游戏设计师想改变巫师行为时都让程序员去修改代码这是不妥的,所以巫师行为以数据驱动的虚拟机方式实现。 + +通俗地说 + +> 字节码模式支持由数据而不是代码驱动的行为。 + +[Gameprogrammingpatterns.com](https://gameprogrammingpatterns.com/bytecode.html) 中做了如下阐述: + +> 指令集定义了可以执行的低级操作。一系列指令被编码为字节序列。虚拟机一次一条地执行这些指令,中间的值用栈处理。通过组合指令,可以定义复杂的高级行为。 + +**程序示例** + +其中最重要的游戏对象是`巫师`类。 + +```java +@AllArgsConstructor +@Setter +@Getter +@Slf4j +public class Wizard { + + private int health; + private int agility; + private int wisdom; + private int numberOfPlayedSounds; + private int numberOfSpawnedParticles; + + public void playSound() { + LOGGER.info("Playing sound"); + numberOfPlayedSounds++; + } + + public void spawnParticles() { + LOGGER.info("Spawning particles"); + numberOfSpawnedParticles++; + } +} +``` + +下面我们展示虚拟机可用的指令。每个指令对于如何操作栈中的数据都有自己的语义。例如,增加指令,其取得栈顶的两个元素并把结果压入栈中。 + +```java +@AllArgsConstructor +@Getter +public enum Instruction { + + LITERAL(1), // e.g. "LITERAL 0", push 0 to stack + SET_HEALTH(2), // e.g. "SET_HEALTH", pop health and wizard number, call set health + SET_WISDOM(3), // e.g. "SET_WISDOM", pop wisdom and wizard number, call set wisdom + SET_AGILITY(4), // e.g. "SET_AGILITY", pop agility and wizard number, call set agility + PLAY_SOUND(5), // e.g. "PLAY_SOUND", pop value as wizard number, call play sound + SPAWN_PARTICLES(6), // e.g. "SPAWN_PARTICLES", pop value as wizard number, call spawn particles + GET_HEALTH(7), // e.g. "GET_HEALTH", pop value as wizard number, push wizard's health + GET_AGILITY(8), // e.g. "GET_AGILITY", pop value as wizard number, push wizard's agility + GET_WISDOM(9), // e.g. "GET_WISDOM", pop value as wizard number, push wizard's wisdom + ADD(10), // e.g. "ADD", pop 2 values, push their sum + DIVIDE(11); // e.g. "DIVIDE", pop 2 values, push their division + // ... +} +``` + +我们示例的核心是`虚拟机`类。 它将指令作为输入并执行它们以提供游戏对象行为。 + +```java +@Getter +@Slf4j +public class VirtualMachine { + + private final Stack stack = new Stack<>(); + + private final Wizard[] wizards = new Wizard[2]; + + public VirtualMachine() { + wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), + 0, 0); + wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), + 0, 0); + } + + public VirtualMachine(Wizard wizard1, Wizard wizard2) { + wizards[0] = wizard1; + wizards[1] = wizard2; + } + + public void execute(int[] bytecode) { + for (var i = 0; i < bytecode.length; i++) { + Instruction instruction = Instruction.getInstruction(bytecode[i]); + switch (instruction) { + case LITERAL: + // Read the next byte from the bytecode. + int value = bytecode[++i]; + // Push the next value to stack + stack.push(value); + break; + case SET_AGILITY: + var amount = stack.pop(); + var wizard = stack.pop(); + setAgility(wizard, amount); + break; + case SET_WISDOM: + amount = stack.pop(); + wizard = stack.pop(); + setWisdom(wizard, amount); + break; + case SET_HEALTH: + amount = stack.pop(); + wizard = stack.pop(); + setHealth(wizard, amount); + break; + case GET_HEALTH: + wizard = stack.pop(); + stack.push(getHealth(wizard)); + break; + case GET_AGILITY: + wizard = stack.pop(); + stack.push(getAgility(wizard)); + break; + case GET_WISDOM: + wizard = stack.pop(); + stack.push(getWisdom(wizard)); + break; + case ADD: + var a = stack.pop(); + var b = stack.pop(); + stack.push(a + b); + break; + case DIVIDE: + a = stack.pop(); + b = stack.pop(); + stack.push(b / a); + break; + case PLAY_SOUND: + wizard = stack.pop(); + getWizards()[wizard].playSound(); + break; + case SPAWN_PARTICLES: + wizard = stack.pop(); + getWizards()[wizard].spawnParticles(); + break; + default: + throw new IllegalArgumentException("Invalid instruction value"); + } + LOGGER.info("Executed " + instruction.name() + ", Stack contains " + getStack()); + } + } + + public void setHealth(int wizard, int amount) { + wizards[wizard].setHealth(amount); + } + // other setters -> + // ... +} +``` + +现在我们可以展示使用虚拟机的完整示例。 + +```java + public static void main(String[] args) { + + var vm = new VirtualMachine( + new Wizard(45, 7, 11, 0, 0), + new Wizard(36, 18, 8, 0, 0)); + + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_HEALTH")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_AGILITY")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); + vm.execute(InstructionConverterUtil.convertToByteCode("GET_WISDOM")); + vm.execute(InstructionConverterUtil.convertToByteCode("ADD")); + vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 2")); + vm.execute(InstructionConverterUtil.convertToByteCode("DIVIDE")); + vm.execute(InstructionConverterUtil.convertToByteCode("ADD")); + vm.execute(InstructionConverterUtil.convertToByteCode("SET_HEALTH")); + } +``` + +下面是控制台输出。 + +``` +16:20:10.193 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0] +16:20:10.196 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_HEALTH, Stack contains [0, 45] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_AGILITY, Stack contains [0, 45, 7] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 7, 0] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_WISDOM, Stack contains [0, 45, 7, 11] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 45, 18] +16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 18, 2] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed DIVIDE, Stack contains [0, 45, 9] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 54] +16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed SET_HEALTH, Stack contains [] +``` + +## 类图 + +![alt text](./etc/bytecode.urm.png "Bytecode class diagram") + +## 适用性 + + + +当您需要定义很多行为并且游戏的实现语言不合适时,请使用字节码模式,因为: + +* 它的等级太低,使得编程变得乏味或容易出错。 +* 由于编译时间慢或其他工具问题,迭代它需要很长时间。 +* 它有太多的信任。 如果您想确保定义的行为不会破坏游戏,您需要将其与代码库的其余部分进行沙箱化。 + +## 相关模式 + +* [Interpreter](https://java-design-patterns.com/patterns/interpreter/) + +## 鸣谢 + +* [Game programming patterns](http://gameprogrammingpatterns.com/bytecode.html) diff --git a/localization/zh/bytecode/etc/bytecode.urm.png b/localization/zh/bytecode/etc/bytecode.urm.png new file mode 100644 index 000000000000..51335fa0a4b4 Binary files /dev/null and b/localization/zh/bytecode/etc/bytecode.urm.png differ diff --git a/localization/zh/caching/README.md b/localization/zh/caching/README.md new file mode 100644 index 000000000000..4d0c1b930829 --- /dev/null +++ b/localization/zh/caching/README.md @@ -0,0 +1,26 @@ +--- +title: Caching +shortTitle: Caching +category: Behavioral +language: zh +tag: + - Performance + - Cloud distributed +--- + +## 目的 +为了避免昂贵的资源重新获取,方法是在资源使用后不立即释放资源。资源保留其身份,保留在某些快速访问的存储中,并被重新使用,以避免再次获取它们。 + +## 类图 +![alt text](./etc/caching.png "Caching") + +## 适用性 +在以下情况下使用缓存模式 + +* 重复获取,初始化和释放同一资源会导致不必要的性能开销。 + +## 鸣谢 + +* [Write-through, write-around, write-back: Cache explained](http://www.computerweekly.com/feature/Write-through-write-around-write-back-Cache-explained) +* [Read-Through, Write-Through, Write-Behind, and Refresh-Ahead Caching](https://docs.oracle.com/cd/E15357_01/coh.360/e15723/cache_rtwtwbra.htm#COHDG5177) +* [Cache-Aside pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/cache-aside) diff --git a/localization/zh/caching/etc/caching.png b/localization/zh/caching/etc/caching.png new file mode 100644 index 000000000000..b6ed703ab8b7 Binary files /dev/null and b/localization/zh/caching/etc/caching.png differ diff --git a/localization/zh/callback/README.md b/localization/zh/callback/README.md new file mode 100644 index 000000000000..937de469a077 --- /dev/null +++ b/localization/zh/callback/README.md @@ -0,0 +1,78 @@ +--- +title: Callback +shortTitle: Callback +category: Idiom +language: zh +tag: + - Reactive +--- + +## 目的 +回调是一部分被当为参数来传递给其他代码的可执行代码,接收方的代码可以在一些方便的时候来调用它。 + +## 解释 + +真实世界例子 + +> 我们需要被通知当执行的任务结束时。我们为调用者传递一个回调方法然后等它调用通知我们。 + +通俗的讲 + + +> 回调是一个用来传递给调用者的方法,它将在定义的时刻被调用。 + +维基百科说 + +> 在计算机编程中,回调又被称为“稍后调用”函数,可以是任何可执行的代码用来作为参数传递给其他代码;其它代码被期望在给定时间内调用回调方法。 + +**编程示例** + +回调是一个只有一个方法的简单接口。 + +```java +public interface Callback { + + void call(); +} +``` + +下面我们定义一个任务它将在任务执行完成后执行回调。 + +```java +public abstract class Task { + + final void executeWith(Callback callback) { + execute(); + Optional.ofNullable(callback).ifPresent(Callback::call); + } + + public abstract void execute(); +} + +public final class SimpleTask extends Task { + + private static final Logger LOGGER = getLogger(SimpleTask.class); + + @Override + public void execute() { + LOGGER.info("Perform some important activity and after call the callback method."); + } +} +``` + +最后这里是我们如何执行一个任务然后接收一个回调当它完成时。 + +```java + var task = new SimpleTask(); + task.executeWith(() -> LOGGER.info("I'm done now.")); +``` +## 类图 +![alt text](./etc/callback.png "Callback") + +## 适用性 +使用回调模式当 +* 当一些同步或异步架构动作必须在一些定义好的活动执行后执行时。 + +## Java例子 + +* [CyclicBarrier](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) 构造函数可以接受回调,该回调将在每次障碍被触发时触发。 diff --git a/localization/zh/callback/etc/callback.png b/localization/zh/callback/etc/callback.png new file mode 100644 index 000000000000..7b499f79fcaa Binary files /dev/null and b/localization/zh/callback/etc/callback.png differ diff --git a/localization/zh/chain/README.md b/localization/zh/chain/README.md new file mode 100644 index 000000000000..63c7f2b39f78 --- /dev/null +++ b/localization/zh/chain/README.md @@ -0,0 +1,158 @@ +--- +title: Chain of responsibility +shortTitle: Chain of responsibility +category: Behavioral +language: zh +tag: + - Gang of Four +--- + +## 目的 +通过给多个对象一个处理请求的机会,避免请求的发送者和它的接收者耦合。串联接收对象并在链条中传递请求直到一个对象处理它。 + +## 解释 + +真实世界例子 + +> 兽王大声命令他的军队。最近响应的是指挥官,然后是军官,然后是士兵。指挥官,军官,士兵这里就形成了一个责任链。 + +通俗的说 + +> 它帮助构建一串对象。请求从一个对象中进入并结束然后进入到一个个对象中直到找到合适的处理器。 + +维基百科说 + +> 在面向对象设计中,责任链模式是一种由源命令对象和一系列处理对象组成的设计模式。每个处理对象包含了其定义的可处理的命令对象类型的逻辑。剩下的会传递给链条中的下一个处理对象。 + +**程序示例** + +用上面的兽人来翻译我们的示例。首先我们有请求类 + +```java +public class Request { + + private final RequestType requestType; + private final String requestDescription; + private boolean handled; + + public Request(final RequestType requestType, final String requestDescription) { + this.requestType = Objects.requireNonNull(requestType); + this.requestDescription = Objects.requireNonNull(requestDescription); + } + + public String getRequestDescription() { return requestDescription; } + + public RequestType getRequestType() { return requestType; } + + public void markHandled() { this.handled = true; } + + public boolean isHandled() { return this.handled; } + + @Override + public String toString() { return getRequestDescription(); } +} + +public enum RequestType { + DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX +} +``` + +然后是请求处理器的层次结构 + +```java +@Slf4j +public abstract class RequestHandler { + private final RequestHandler next; + + public RequestHandler(RequestHandler next) { + this.next = next; + } + + public void handleRequest(Request req) { + if (next != null) { + next.handleRequest(req); + } + } + + protected void printHandling(Request req) { + LOGGER.info("{} handling request \"{}\"", this, req); + } + + @Override + public abstract String toString(); +} + +public class OrcCommander extends RequestHandler { + public OrcCommander(RequestHandler handler) { + super(handler); + } + + @Override + public void handleRequest(Request req) { + if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) { + printHandling(req); + req.markHandled(); + } else { + super.handleRequest(req); + } + } + + @Override + public String toString() { + return "Orc commander"; + } +} + +// OrcOfficer和OrcSoldier的定义与OrcCommander类似 + +``` + +然后我们有兽王下达命令并形成链条 + +```java +public class OrcKing { + RequestHandler chain; + + public OrcKing() { + buildChain(); + } + + private void buildChain() { + chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null))); + } + + public void makeRequest(Request req) { + chain.handleRequest(req); + } +} +``` + +然后这样使用它 + +```java +var king = new OrcKing(); +king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); // Orc commander handling request "defend castle" +king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); // Orc officer handling request "torture prisoner" +king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); // Orc soldier handling request "collect tax" +``` + +## 类图 +![alt text](./etc/chain-of-responsibility.urm.png "Chain of Responsibility class diagram") + +## 适用性 +使用责任链模式当 + +* 多于一个对象可能要处理请求,并且处理器并不知道一个优先级。处理器应自动确定。 +* 你想对多个对象之一发出请求而无需明确指定接收者 +* 处理请求的对象集合应该被动态指定时 + +## Java世界例子 + +* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) +* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) +* [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/zh/chain/etc/chain-of-responsibility.urm.png b/localization/zh/chain/etc/chain-of-responsibility.urm.png new file mode 100644 index 000000000000..c3a4c80ba322 Binary files /dev/null and b/localization/zh/chain/etc/chain-of-responsibility.urm.png differ diff --git a/localization/zh/circuit-breaker/README.md b/localization/zh/circuit-breaker/README.md new file mode 100644 index 000000000000..6658a2f1a15f --- /dev/null +++ b/localization/zh/circuit-breaker/README.md @@ -0,0 +1,314 @@ +--- +title: Circuit Breaker +shortTitle: Circuit Breaker +category: Behavioral +language: zh +tag: + - Performance + - Decoupling + - Cloud distributed +--- + +## 意图 + +以这样一种方式处理昂贵的远程服务调用,即单个服务/组件的故障不会导致整个应用程序宕机,我们可以尽快重新连接到服务。 + +## 解释 + +真实世界例子 + +> 想象一个 Web 应用程序,它同时具有用于获取数据的本地文件/图像和远程服务。 这些远程服务有时可能健康且响应迅速,或者由于各种原因可能在某 个时间点变得缓慢和无响应。因此,如果其中一个远程服务缓慢或未成功响应,我们的应用程序将尝试使用多个线程/进程从远程服务获取响应,很快它们都会挂起(也称为 [线程饥饿][thread starvation](https://en.wikipedia.org/wiki/Starvation_(computer_science)))导致我们的整个 Web 应用程序崩溃。我们应该能够检测到这种情况并向用户显示适当的消息,以便他/她可以探索不受远程服务故障影响的应用程序的其他部分。 同时,其他正常工作的服务应保持正常运行,不受此故障的影响。 +> + +通俗地说 + +> 断路器允许优雅地处理失败的远程服务。当我们应用程序的所有部分彼此高度解耦时,它特别有用,一个组件的故障并不意味着其他部分将停止工作。 + +维基百科说 + +> 断路器是现代软件开发中使用的一种设计模式。 它用于检测故障并封装防止故障不断重复发生、维护期间、临时外部系统故障或意外系统困难的逻辑。 + +## 程序示例 + +So, how does this all come together? With the above example in mind we will imitate the +functionality in a simple example. A monitoring service mimics the web app and makes both local and +remote calls. + +那么,这一切是如何结合在一起的呢? 记住上面的例子,我们将在一个简单的例子中模仿这个功能。 监控服务模仿 Web 应用程序并进行本地和远程调用。 + +服务架构如下: + +![alt text](./etc/ServiceDiagram.png "Service Diagram") + +在代码方面,最终用户应用程序是: + +```java +@Slf4j +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) { + + var serverStartTime = System.nanoTime(); + + var delayedService = new DelayedRemoteService(serverStartTime, 5); + var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2, + 2000 * 1000 * 1000); + + var quickService = new QuickRemoteService(); + var quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, 2, + 2000 * 1000 * 1000); + + // 创建一个可以进行本地和远程调用的监控服务对象 + var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, + quickServiceCircuitBreaker); + + // 获取本地资源 + LOGGER.info(monitoringService.localResourceResponse()); + + // 从延迟服务中获取响应 2 次,以满足失败阈值 + LOGGER.info(monitoringService.delayedServiceResponse()); + LOGGER.info(monitoringService.delayedServiceResponse()); + + // 在超过故障阈值限制后获取延迟服务断路器的当前状态 + // 现在是打开状态 + LOGGER.info(delayedServiceCircuitBreaker.getState()); + + // 同时,延迟服务宕机,从健康快速服务获取响应 + LOGGER.info(monitoringService.quickServiceResponse()); + LOGGER.info(quickServiceCircuitBreaker.getState()); + + // 等待延迟的服务响应 + try { + LOGGER.info("Waiting for delayed service to become responsive"); + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // 检查延时断路器的状态,应该是HALF_OPEN + LOGGER.info(delayedServiceCircuitBreaker.getState()); + + // 从延迟服务中获取响应,现在应该是健康的 + LOGGER.info(monitoringService.delayedServiceResponse()); + // 获取成功响应后,它的状态应该是关闭。 + LOGGER.info(delayedServiceCircuitBreaker.getState()); + } +} +``` + +监控服务类: + +```java +public class MonitoringService { + + private final CircuitBreaker delayedService; + + private final CircuitBreaker quickService; + + public MonitoringService(CircuitBreaker delayedService, CircuitBreaker quickService) { + this.delayedService = delayedService; + this.quickService = quickService; + } + + // 假设:本地服务不会失败,无需将其包装在断路器逻辑中 + public String localResourceResponse() { + return "Local Service is working"; + } + + /** + * Fetch response from the delayed service (with some simulated startup time). + * + * @return response string + */ + public String delayedServiceResponse() { + try { + return this.delayedService.attemptRequest(); + } catch (RemoteServiceException e) { + return e.getMessage(); + } + } + + /** + * Fetches response from a healthy service without any failure. + * + * @return response string + */ + public String quickServiceResponse() { + try { + return this.quickService.attemptRequest(); + } catch (RemoteServiceException e) { + return e.getMessage(); + } + } +} +``` +可以看出,它直接调用获取本地资源,但它将对远程(昂贵)服务的调用包装在断路器对象中,防止故障如下: + +```java +public class DefaultCircuitBreaker implements CircuitBreaker { + + private final long timeout; + private final long retryTimePeriod; + private final RemoteService service; + long lastFailureTime; + private String lastFailureResponse; + int failureCount; + private final int failureThreshold; + private State state; + private final long futureTime = 1000 * 1000 * 1000 * 1000; + + /** + * Constructor to create an instance of Circuit Breaker. + * + * @param timeout Timeout for the API request. Not necessary for this simple example + * @param failureThreshold Number of failures we receive from the depended service before changing + * state to 'OPEN' + * @param retryTimePeriod Time period after which a new request is made to remote service for + * status check. + */ + DefaultCircuitBreaker(RemoteService serviceToCall, long timeout, int failureThreshold, + long retryTimePeriod) { + this.service = serviceToCall; + // 我们从关闭状态开始希望一切都是正常的 + this.state = State.CLOSED; + this.failureThreshold = failureThreshold; + // API的超时时间. + // 用于在超过限制时中断对远程资源的调用 + this.timeout = timeout; + this.retryTimePeriod = retryTimePeriod; + //An absurd amount of time in future which basically indicates the last failure never happened + this.lastFailureTime = System.nanoTime() + futureTime; + this.failureCount = 0; + } + + // 重置所有 + @Override + public void recordSuccess() { + this.failureCount = 0; + this.lastFailureTime = System.nanoTime() + futureTime; + this.state = State.CLOSED; + } + + @Override + public void recordFailure(String response) { + failureCount = failureCount + 1; + this.lastFailureTime = System.nanoTime(); + // Cache the failure response for returning on open state + this.lastFailureResponse = response; + } + + // 根据 failureThreshold、failureCount 和 lastFailureTime 评估当前状态。 + protected void evaluateState() { + if (failureCount >= failureThreshold) { //Then something is wrong with remote service + if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) { + // 我们已经等得够久了,应该尝试检查服务是否已启动 + state = State.HALF_OPEN; + } else { + // 服务可能仍会出现故障 + state = State.OPEN; + } + } else { + // 一切正常 + state = State.CLOSED; + } + } + + @Override + public String getState() { + evaluateState(); + return state.name(); + } + + /** + * Break the circuit beforehand if it is known service is down Or connect the circuit manually if + * service comes online before expected. + * + * @param state State at which circuit is in + */ + @Override + public void setState(State state) { + this.state = state; + switch (state) { + case OPEN -> { + this.failureCount = failureThreshold; + this.lastFailureTime = System.nanoTime(); + } + case HALF_OPEN -> { + this.failureCount = failureThreshold; + this.lastFailureTime = System.nanoTime() - retryTimePeriod; + } + default -> this.failureCount = 0; + } + } + + /** + * Executes service call. + * + * @return Value from the remote resource, stale response or a custom exception + */ + @Override + public String attemptRequest() throws RemoteServiceException { + evaluateState(); + if (state == State.OPEN) { + // 如果电路处于打开状态,则返回缓存的响应 + return this.lastFailureResponse; + } else { + // 如果电路未打开,则发出 API 请求 + try { + //在实际应用程序中,这将在线程中运行,并且将利用断路器的超时参数来了解服务 + // 是否正在工作。 在这里,我们根据服务器响应本身模拟 + var response = service.call(); + // api 响应正常,重置所有。 + recordSuccess(); + return response; + } catch (RemoteServiceException ex) { + recordFailure(ex.getMessage()); + throw ex; + } + } + } +} +``` + +上述模式如何防止失败? 让我们通过它实现的这个有限状态机来理解。 + +![alt text](./etc/StateDiagram.png "State Diagram") + +- 我们使用某些参数初始化断路器对象:`timeout`、`failureThreshold` 和 `retryTimePeriod`,这有助于确定 API 的弹性。 +- 最初,我们处于“关闭”状态,没有发生对 API 的远程调用。 +- 每次调用成功时,我们都会将状态重置为开始时的状态。 +- 如果失败次数超过某个阈值,我们将进入“open”状态,这就像开路一样,阻止远程服务调用,从而节省资源。 (这里,我们从 API 返回名为 ```stale response``` 的响应) +- 一旦超过重试超时时间,我们就会进入“半开”状态并再次调用远程服务以检查服务是否正常工作,以便我们可以提供新鲜内容。 失败将其设置回“打开”状态,并在重试超时时间后进行另一次尝试,而成功将其设置为“关闭”状态,以便一切重新开始正常工作。 + +## 类图 + +![alt text](./etc/circuit-breaker.urm.png "Circuit Breaker class diagram") + +## 适用性 + +在以下情况下使用断路器模式 + +- 构建一个容错应用程序,其中某些服务的故障不应导致整个应用程序宕机。 +- 构建一个持续运行(永远在线)的应用程序,这样它的组件就可以在不完全关闭的情况下升级。 + +## 相关模式 + +- [Retry Pattern](https://github.com/iluwatar/java-design-patterns/tree/master/retry) + +## 真实世界例子 + +* [Spring Circuit Breaker module](https://spring.io/guides/gs/circuit-breaker) +* [Netflix Hystrix API](https://github.com/Netflix/Hystrix) + +## 鸣谢 + +* [Understanding Circuit Breaker Pattern](https://itnext.io/understand-circuitbreaker-design-pattern-with-simple-practical-example-92a752615b42) +* [Martin Fowler on Circuit Breaker](https://martinfowler.com/bliki/CircuitBreaker.html) +* [Fault tolerance in a high volume, distributed system](https://medium.com/netflix-techblog/fault-tolerance-in-a-high-volume-distributed-system-91ab4faae74a) +* [Circuit Breaker pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker) diff --git a/localization/zh/circuit-breaker/etc/ServiceDiagram.png b/localization/zh/circuit-breaker/etc/ServiceDiagram.png new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/localization/zh/circuit-breaker/etc/StateDiagram.png b/localization/zh/circuit-breaker/etc/StateDiagram.png new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/localization/zh/circuit-breaker/etc/circuit-breaker.urm.png b/localization/zh/circuit-breaker/etc/circuit-breaker.urm.png new file mode 100644 index 000000000000..fc90318ec8da Binary files /dev/null and b/localization/zh/circuit-breaker/etc/circuit-breaker.urm.png differ diff --git a/localization/zh/cloud-static-content-hosting/README.md b/localization/zh/cloud-static-content-hosting/README.md new file mode 100644 index 000000000000..78f696d533dd --- /dev/null +++ b/localization/zh/cloud-static-content-hosting/README.md @@ -0,0 +1,132 @@ +--- +title: Static Content Hosting +shortTitle: Static Content Hosting +category: Cloud +language: zh +tag: +- Cloud distributed +--- + +## 意图 + +将静态内容部署到基于云的存储服务,该服务可以将它们直接交付给客户端。 这可以减少对昂贵计算实例的需求。 + +## 解释 + +真实世界例子 + +> 全球性的营销网站(静态内容)需要快速的部署以开始吸引潜在的客户。为了将托管费用和维护成本降至最低,使用云托管存储服务和内容交付网络。 + +通俗地说 + +> 静态内容托管模式利用云原生存储服务来存储内容和全球内容交付网络,将其缓存在世界各地的多个数据中心。 在静态网站上,单个网页包含静态内容。 它们还可能包含客户端脚本,例如 Javascript。相比之下,动态网站依赖于服务器端处理,包括服务器端脚本,如 PHP、JSP 或 ASP.NET。 + +维基百科说 + +> 与由 Web 应用程序生成的动态网页相反,静态网页(有时称为平面网页或固定网页)是完全按照存储的方式传送到用户的网页浏览器的网页。静态网页适用于从不或很少需要更新的内容,尽管现代 +> Web 模板系统正在改变这一点。可以将大量静态页面作为文件进行维护,没有自动化工具(例如静态站点生成器)是不切实际的。 + +**示例** + +![alt text](./etc/static-content-hosting.png "Static Content Hosting") + +在这个例子中我们使用AWS S3创建一个静态网站,并利用 AWS Cloudfront 在全球范围内分发内容。 + +1. 首先你需要一个AWS账户,你可以在这个创建一个免费的:[AWS Free Tier](https://aws.amazon.com/free/free-tier/) + +2. 登陆 [AWS控制台](https://console.aws.amazon.com/console/home?nc2=h_ct&src=header-signin) + +3. 进入身份和接入管理服务 (IAM) . + +4. 创建一个仅具有此应用程序必要权限的IAM用户。 + + * 点击 `用户` + * 点击 `添加用户`. 选择你想要的 `用户名`, `接入类型`应该是 `编程式接入`. 点击 `下一步: 权限`. + * 选择 `直接附加已存在的策略`. 选择 `AmazonS3FullAccess` 和 `CloudFrontFullAccess`. Click `下一步: 标签`. + * 没有需要的标签, 所以直接点击 `下一步: 回顾`. + * 检查呈现的信息,没问题的话点击`创建用户` + * 完成这个示例所需要的`访问秘钥Id`和`访问秘钥密码`将会呈现在你面前,请妥善保管。 + * 点击 `关闭`. + +5. [安装AWS 命令行工具 (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv1.html) 来获得编程式访问AWS云。 + +6. 使用`aws configure`命令来配置AWS CLI [说明书](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config) + +7. 为web站点创建AWS S3 bucket。 注意S3 bucket名字必须要在全球范围内唯一。 + + + * 语法是 `aws s3 mb ` [说明书](https://docs.aws.amazon.com/cli/latest/userguide/cli-services-s3-commands.html#using-s3-commands-managing-buckets-creating) + * 比如 `aws s3 mb s3://my-static-website-jh34jsjmg` + * 使用列出现有存储桶的命令`aws s3 ls`验证存储桶是否已成功创建 + +8. 使用命令`aws s3 website`来配置bucket作为web站点。 [说明书](https://docs.aws.amazon.com/cli/latest/reference/s3/website.html). + + * 比如`aws s3 website s3://my-static-website-jh34jsjmg --index-document index.html --error-document error.html` + +9. 上传内容到bucket中。 + * 首先创建内容,至少包含`index.html`和`error.html`文档。 + * 上传内容到你的bucket中。 [说明书](https://docs.aws.amazon.com/cli/latest/userguide/cli-services-s3-commands.html#using-s3-commands-managing-objects-copy) + * 比如`aws s3 cp index.html s3://my-static-website-jh34jsjmg` and `aws s3 cp error.html s3://my-static-website-jh34jsjmg` + +10. 然后我们需要设置bucket的策略以允许读取访问。 + + * 使用以下内容创建`policy.json`(注意需要将bucket名称替换为自己的)。 + + ```json + { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "PublicReadGetObject", + "Effect": "Allow", + "Principal": "*", + "Action": "s3:GetObject", + "Resource": "arn:aws:s3:::my-static-website-jh34jsjmg/*" + } + ] + } + ``` + + * 根据这些设置桶策略[说明书](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-policy.html) + * 比如 `aws s3api put-bucket-policy --bucket my-static-website-jh34jsjmg --policy file://policy.json` + +11. 使用浏览器测试web站点。 + + * web站点的URL格式是 `http://.s3-website-.amazonaws.com` + * 比如 这个站点创建在 `eu-west-1` 区域 ,名字是 `my-static-website-jh34jsjmg` 所以它可以通过 `http://my-static-website-jh34jsjmg.s3-website-eu-west-1.amazonaws.com`来访问。 + +12. 为web站点创建CloudFormation 分发。 + + * 语法文档在这里 [this reference](https://docs.aws.amazon.com/cli/latest/reference/cloudfront/create-distribution.html) + * 比如,最简单的方式是使用命令l `aws cloudfront create-distribution --origin-domain-name my-static-website-jh34jsjmg.s3.amazonaws.com --default-root-object index.html` + * 也支持JSON格式的配置 比如使用 `--distribution-config file://dist-config.json` 来传递分发的配置文件参数 + * 命令的舒勇将显示准确的分配配置项,包括包括可用于测试的生成的 CloudFront 域名,例如 `d2k3xwnaqa8nqx.cloudfront.net` + * CloudFormation 分发部署需要一些时间,但一旦完成,您的网站就会从全球各地的数据中心提供服务! + +13. 就是这样! 您已经实现了一个静态网站,其内容分发网络以闪电般的速度在世界各地提供服务。 + + * 要更新网站,您需要更新 S3 存储桶中的对象并使 CloudFront 分配中的对象无效 + * 要从 AWS CLI 执行此操作,请参阅 [this reference](https://docs.aws.amazon.com/cli/latest/reference/cloudfront/create-invalidation.html) + * 您可能想要做的进一步开发是通过 https 提供内容并为您的站点添加域名 + +## 适用性 + +当您想要执行以下操作时,请使用静态内容托管模式: + +* 最小化包含一些静态资源的网站和应用程序的托管成本。 +* 使用静态内容构建全球可用的网站 +* 监控网站流量、带宽使用、成本等。 + +## 典型用例 + +* 具有全球影响力的网站 +* 静态网站生成器生成的内容 +* 没有动态内容要求的网站 + +## 真实世界例子 + +* [Java Design Patterns web site](https://java-design-patterns.com) + +## 鸣谢 + +* [Static Content Hosting pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/static-content-hosting) diff --git a/localization/zh/cloud-static-content-hosting/etc/static-content-hosting.png b/localization/zh/cloud-static-content-hosting/etc/static-content-hosting.png new file mode 100644 index 000000000000..6e0baa95e0f9 Binary files /dev/null and b/localization/zh/cloud-static-content-hosting/etc/static-content-hosting.png differ diff --git a/localization/zh/collection-pipeline/README.md b/localization/zh/collection-pipeline/README.md new file mode 100644 index 000000000000..725067421486 --- /dev/null +++ b/localization/zh/collection-pipeline/README.md @@ -0,0 +1,28 @@ +--- +title: Collection Pipeline +shortTitle: Collection Pipeline +category: Functional +language: zh +tag: + - Reactive +--- + +## 释义 +**集合管道(Collection Pipeline)**包含**函数组合(Function Composition)**和**集合管道(Collection Pipeline)**两组合概念,这是两种函数式编程模式,你可以在代码中结合这两种模式来进行集合迭代。 +在函数式编程中,可以通过一系列较小的模块化函数或操作来编排复杂的操作。这一系列函数被称为函数组合。当一个数据集合流经一个函数组合时,它就成为一个集合管道。函数组合和集合管道是函数式编程中经常使用的两种设计模式。 + +## 类图 +![alt text](./etc/collection-pipeline.png "Collection Pipeline") + +## 适用场景 +在以下场景适用集合管道模式: + +* 当你想执行一组连续的算子操作,其中一个算子收集的输出需要被输入到下一个算子中 +* 当你在代码中需要使用大量的中间状态语句时 +* 当你在代码中使用大量的循环语句时 + +## 引用 + +* [Function composition and the Collection Pipeline pattern](https://www.ibm.com/developerworks/library/j-java8idioms2/index.html) +* [Martin Fowler](https://martinfowler.com/articles/collection-pipeline/) +* [Java8 Streams](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html) \ No newline at end of file diff --git a/localization/zh/collection-pipeline/etc/collection-pipeline.png b/localization/zh/collection-pipeline/etc/collection-pipeline.png new file mode 100644 index 000000000000..67d52629cb86 Binary files /dev/null and b/localization/zh/collection-pipeline/etc/collection-pipeline.png differ diff --git a/localization/zh/combinator/README.md b/localization/zh/combinator/README.md new file mode 100644 index 000000000000..79ac664f4ee9 --- /dev/null +++ b/localization/zh/combinator/README.md @@ -0,0 +1,208 @@ +--- +title: Combinator +shortTitle: Combinator +category: Idiom +language: zh +tag: + - Reactive +--- + +## 或称 + +构图模式 + +## 目的 + +功能模式代表了一种以组合功能为中心的图书馆组织风格。 +简单地说,有一些类型 T,一些用于构造类型 T 的“原始”值的函数,以及一些可以以各种方式组合类型 T 的值以构建更复杂的类型 T 值的“组合器”。 + +## 解释 + +真实世界例子 + +> 在计算机科学中,组合逻辑被用作计算的简化模型,用于可计算性理论和证明理论。 尽管组合逻辑很简单,但它捕获了计算的许多基本特征。 +> + +通俗的说 +> 组合器允许从先前定义的“事物”创建新的“事物”。 +> + +维基百科说 + +> 组合器是一个高阶函数,仅使用函数应用程序和之前定义的组合器来定义其参数的结果。 +> + +**程序示例** + +翻译上面的组合器示例。 首先,我们有一个由几个方法`contains`, `not`, `or`, `and`组成的接口。 + +```java +// 用于查找文本中的行的功能界面。 +public interface Finder { + + // 在文本中查找行的函数。 + List find(String text); + + // 函数{@link #find(String)}的简单实现。 + static Finder contains(String word) { + return txt -> Stream.of(txt.split("\n")) + .filter(line -> line.toLowerCase().contains(word.toLowerCase())) + .collect(Collectors.toList()); + } + + // 组合器:not。 + default Finder not(Finder notFinder) { + return txt -> { + List res = this.find(txt); + res.removeAll(notFinder.find(txt)); + return res; + }; + } + + // 组合器:or。 + default Finder or(Finder orFinder) { + return txt -> { + List res = this.find(txt); + res.addAll(orFinder.find(txt)); + return res; + }; + } + + // 组合器:and。 + default Finder and(Finder andFinder) { + return + txt -> this + .find(txt) + .stream() + .flatMap(line -> andFinder.find(line).stream()) + .collect(Collectors.toList()); + } + ... +} +``` + +然后我们还有另一个组合器用于一些复杂的查找器`advancedFinder`, `filteredFinder`, `specializedFinder`和`expandedFinder`。 + +```java +// 由简单取景器组成的复杂取景器。 +public class Finders { + + private Finders() { + } + + // Finder 用于查找复杂的查询。 + public static Finder advancedFinder(String query, String orQuery, String notQuery) { + return + Finder.contains(query) + .or(Finder.contains(orQuery)) + .not(Finder.contains(notQuery)); + } + + // 过滤查找器也会查找包含排除查询的查询。 + public static Finder filteredFinder(String query, String... excludeQueries) { + var finder = Finder.contains(query); + + for (String q : excludeQueries) { + finder = finder.not(Finder.contains(q)); + } + return finder; + } + + // 专门查询。 每个下一个查询都会在上一个结果中查找。 + public static Finder specializedFinder(String... queries) { + var finder = identMult(); + + for (String query : queries) { + finder = finder.and(Finder.contains(query)); + } + return finder; + } + + // 扩展查询。 寻找替代品。 + public static Finder expandedFinder(String... queries) { + var finder = identSum(); + + for (String query : queries) { + finder = finder.or(Finder.contains(query)); + } + return finder; + } + ... +} +``` + +现在我们已经创建了组合器的接口和方法。 现在我们有一个处理这些组合器的应用程序。 + +```java +var queriesOr = new String[]{"many", "Annabel"}; +var finder = Finders.expandedFinder(queriesOr); +var res = finder.find(text()); +LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res); + +var queriesAnd = new String[]{"Annabel", "my"}; +finder = Finders.specializedFinder(queriesAnd); +res = finder.find(text()); +LOGGER.info("the result of specialized(and) query[{}] is {}", queriesAnd, res); + +finder = Finders.advancedFinder("it was", "kingdom", "sea"); +res = finder.find(text()); +LOGGER.info("the result of advanced query is {}", res); + +res = Finders.filteredFinder(" was ", "many", "child").find(text()); +LOGGER.info("the result of filtered query is {}", res); + +private static String text() { + return + "It was many and many a year ago,\n" + + "In a kingdom by the sea,\n" + + "That a maiden there lived whom you may know\n" + + "By the name of ANNABEL LEE;\n" + + "And this maiden she lived with no other thought\n" + + "Than to love and be loved by me.\n" + + "I was a child and she was a child,\n" + + "In this kingdom by the sea;\n" + + "But we loved with a love that was more than love-\n" + + "I and my Annabel Lee;\n" + + "With a love that the winged seraphs of heaven\n" + + "Coveted her and me."; + } +``` + +**程序输出:** + +```java +the result of expanded(or) query[[many, Annabel]] is [It was many and many a year ago,, By the name of ANNABEL LEE;, I and my Annabel Lee;] +the result of specialized(and) query[[Annabel, my]] is [I and my Annabel Lee;] +the result of advanced query is [It was many and many a year ago,] +the result of filtered query is [But we loved with a love that was more than love-] +``` + +现在我们可以设计我们的应用程序,使其具有查询查找功能`expandedFinder`, `specializedFinder`, `advancedFinder`, `filteredFinder`,这些功能均派生自`contains`, `or`, `not`, `and`。 + + +## 类图 +![alt text](./etc/combinator.urm.png "Combinator class diagram") + +## 适用性 +在以下情况下使用组合器模式: + +- 您可以从更简单的值创建更复杂的值,但具有相同的类型(它们的组合) + +## 好处 + +- 从开发人员的角度来看,API 由领域中的术语组成。 +- 组合阶段和应用阶段之间有明显的区别。 +- 首先构造一个实例,然后执行它。 +- 这使得该模式适用于并行环境。 + + +## 现实世界的例子 + +- java.util.function.Function#compose +- java.util.function.Function#andThen + +## 鸣谢 + +- [Example for java](https://gtrefs.github.io/code/combinator-pattern/) +- [Combinator pattern](https://wiki.haskell.org/Combinator_pattern) +- [Combinatory logic](https://wiki.haskell.org/Combinatory_logic) diff --git a/localization/zh/combinator/etc/combinator.urm.png b/localization/zh/combinator/etc/combinator.urm.png new file mode 100644 index 000000000000..80fdd36340bb Binary files /dev/null and b/localization/zh/combinator/etc/combinator.urm.png differ diff --git a/localization/zh/command/README.md b/localization/zh/command/README.md new file mode 100644 index 000000000000..d8b93b363e91 --- /dev/null +++ b/localization/zh/command/README.md @@ -0,0 +1,252 @@ +--- +title: Command +shortTitle: Command +category: Behavioral +language: zh +tag: + - Gang of Four +--- + +## 或称 +行动, 事务模式 + +## 目的 +将请求封装为对象,从而使你可以将具有不同请求的客户端参数化,队列或记录请求,并且支持可撤销操作。 + +## 解释 +真实世界例子 + +> 有一个巫师在地精上施放咒语。咒语在地精上一一执行。第一个咒语使地精缩小,第二个使他不可见。然后巫师将咒语一个个的反转。这里的每一个咒语都是一个可撤销的命令对象。 + +用通俗的话说 + +> 用命令对象的方式存储请求以在将来时可以执行它或撤销它。 + +维基百科说 + +> 在面向对象编程中,命令模式是一种行为型设计模式,它把在稍后执行的一个动作或触发的一个事件所需要的所有信息封装到一个对象中。 + +**编程示例** + +这是巫师和地精的示例代码。让我们从巫师类开始。 + +```java +public class Wizard { + + private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class); + + private final Deque undoStack = new LinkedList<>(); + private final Deque redoStack = new LinkedList<>(); + + public Wizard() {} + + public void castSpell(Command command, Target target) { + LOGGER.info("{} casts {} at {}", this, command, target); + command.execute(target); + undoStack.offerLast(command); + } + + public void undoLastSpell() { + if (!undoStack.isEmpty()) { + var previousSpell = undoStack.pollLast(); + redoStack.offerLast(previousSpell); + LOGGER.info("{} undoes {}", this, previousSpell); + previousSpell.undo(); + } + } + + public void redoLastSpell() { + if (!redoStack.isEmpty()) { + var previousSpell = redoStack.pollLast(); + undoStack.offerLast(previousSpell); + LOGGER.info("{} redoes {}", this, previousSpell); + previousSpell.redo(); + } + } + + @Override + public String toString() { + return "Wizard"; + } +} +``` + +接下来我们介绍咒语层级 + +```java +public interface Command { + + void execute(Target target); + + void undo(); + + void redo(); + + String toString(); +} + +public class InvisibilitySpell implements Command { + + private Target target; + + @Override + public void execute(Target target) { + target.setVisibility(Visibility.INVISIBLE); + this.target = target; + } + + @Override + public void undo() { + if (target != null) { + target.setVisibility(Visibility.VISIBLE); + } + } + + @Override + public void redo() { + if (target != null) { + target.setVisibility(Visibility.INVISIBLE); + } + } + + @Override + public String toString() { + return "Invisibility spell"; + } +} + +public class ShrinkSpell implements Command { + + private Size oldSize; + private Target target; + + @Override + public void execute(Target target) { + oldSize = target.getSize(); + target.setSize(Size.SMALL); + this.target = target; + } + + @Override + public void undo() { + if (oldSize != null && target != null) { + var temp = target.getSize(); + target.setSize(oldSize); + oldSize = temp; + } + } + + @Override + public void redo() { + undo(); + } + + @Override + public String toString() { + return "Shrink spell"; + } +} +``` + +最后我们有咒语的目标地精。 + +```java +public abstract class Target { + + private static final Logger LOGGER = LoggerFactory.getLogger(Target.class); + + private Size size; + + private Visibility visibility; + + public Size getSize() { + return size; + } + + public void setSize(Size size) { + this.size = size; + } + + public Visibility getVisibility() { + return visibility; + } + + public void setVisibility(Visibility visibility) { + this.visibility = visibility; + } + + @Override + public abstract String toString(); + + public void printStatus() { + LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); + } +} + +public class Goblin extends Target { + + public Goblin() { + setSize(Size.NORMAL); + setVisibility(Visibility.VISIBLE); + } + + @Override + public String toString() { + return "Goblin"; + } + +} +``` + +最后是整个示例的实践。 + +```java +var wizard = new Wizard(); +var goblin = new Goblin(); +goblin.printStatus(); +// Goblin, [size=normal] [visibility=visible] +wizard.castSpell(new ShrinkSpell(), goblin); +// Wizard casts Shrink spell at Goblin +goblin.printStatus(); +// Goblin, [size=small] [visibility=visible] +wizard.castSpell(new InvisibilitySpell(), goblin); +// Wizard casts Invisibility spell at Goblin +goblin.printStatus(); +// Goblin, [size=small] [visibility=invisible] +wizard.undoLastSpell(); +// Wizard undoes Invisibility spell +goblin.printStatus(); +// Goblin, [size=small] [visibility=visible] +``` + +## 类图 +![alt text](./etc/command.png "Command") + +## 适用性 +使用命令模式当你想 + +* 通过操作将对象参数化。您可以使用回调函数(即,已在某处注册以便稍后调用的函数)以过程语言表示这种参数化。命令是回调的一种面向对象替代方案。 +* 在不同的时间指定,排队和执行请求。一个命令对象的生存期可以独立于原始请求。如果请求的接收方可以以地址空间无关的方式来表示,那么你可以将请求的命令对象传输到其他进程并在那里执行请求。 +* 支持撤销。命令的执行操作可以在命令本身中存储状态以反转其效果。命令接口必须有添加的反执行操作,该操作可以逆转上一次执行调用的效果。执行的命令存储在历史列表中。无限撤消和重做通过分别向后和向前遍历此列表来实现,分别调用unexecute和execute。 +* 支持日志记录更改,以便在系统崩溃时可以重新应用它们。通过使用加载和存储操作扩展命令接口,你可以保留更改的永久日志。从崩溃中恢复涉及从磁盘重新加载记录的命令,并通过执行操作重新执行它们。 +* 通过原始的操作来构建一个以高级操作围绕的系统。这种结构在支持事务的信息系统中很常见。事务封装了一组数据更改。命令模式提供了一种对事务进行建模的方法。命令具有公共接口,让你以相同的方式调用所有事务。该模式还可以通过新的事务来轻松扩展系统。 + +## 典型用例 + +* 保留请求历史 +* 实现回调功能 +* 实现撤销功能 + +## Java世界例子 + +* [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) +* [org.junit.runners.model.Statement](https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/model/Statement.java) +* [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki) +* [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/zh/command/etc/command.png b/localization/zh/command/etc/command.png new file mode 100644 index 000000000000..0f026464ecc4 Binary files /dev/null and b/localization/zh/command/etc/command.png differ diff --git a/localization/zh/commander/README.md b/localization/zh/commander/README.md new file mode 100644 index 000000000000..8d75337d9e4d --- /dev/null +++ b/localization/zh/commander/README.md @@ -0,0 +1,25 @@ +--- +title: Commander +shortTitle: Commander +category: Concurrency +language: zh +tag: + - Cloud distributed +--- + +## 目的 + +> 用于处理执行分布式事务时可能遇到的所有问题。 + +## 类图 +![alt text](./etc/commander.urm.png "Commander class diagram") + +## 适用场合 +当我们需要提交两个数据库去完成事务,提交不是原子性且可能因此造成问题时,适合用这个设计模式。 + +## 解释 +处理分布式事务很棘手,但如果我们不仔细处理,可能会带来不想要的后果。假设我们有一个电子商务网站,它有一个支付微服务和一个运输微服务。如果当前运输可用,但支付服务不可用,或者反之,当我们已经收到用户的订单后,我们应该如何处理?我们需要有一个机制来处理这些情况。我们必须将订单指向其中一个服务(在这个例子中是运输),然后将订单添加到另一个服务的数据库中(在这个例子中是支付),因为两个数据库不能原子地更新。如果我们当前无法做到这一点,应该有一个队列,可以将这个请求排队,并且必须有一个机制,允许队列中出现失败。所有这些都需要通过不断的重试,在保证幂等性(即使请求多次,变化只应用一次)的情况下,由一个指挥类来完成,以达到最终一致性的状态。 + +## 鸣谢 + +* [Distributed Transactions: The Icebergs of Microservices](https://www.grahamlea.com/2016/08/distributed-transactions-microservices-icebergs/) diff --git a/localization/zh/commander/etc/commander.urm.png b/localization/zh/commander/etc/commander.urm.png new file mode 100644 index 000000000000..6b5ebba75bd6 Binary files /dev/null and b/localization/zh/commander/etc/commander.urm.png differ diff --git a/localization/zh/composite-entity/README.md b/localization/zh/composite-entity/README.md new file mode 100644 index 000000000000..aa904246ab75 --- /dev/null +++ b/localization/zh/composite-entity/README.md @@ -0,0 +1,120 @@ +--- +title: Composite Entity +shortTitle: Composite Entity +category: Structural +language: zh +tag: + - Enterprise Integration Pattern +--- + +## 含义 + +复合实体模式用于对一组相关联的持久化对象进行建模、描述和管理,用于取代对这组对象描述为单独粒度的实体。 + +## 解释 + +现实例子 + +> 对于一个控制台对象,需要管理许多接口功能。通过使用复合实体模式,将消息对象、信号对象等依赖性对象组合在一起,直接使用单个对象对其进行控制。 + +简单地说 + +> 复合实体模式允许使用一个统一对象来管理一组相互关联的对象 + +**编程示例** + +我们需要一个通用的解决方案来解决上述的控制台问题。我们引入了以下的通用复合对象。 + +```java +public abstract class DependentObject { + + T data; + + public void setData(T message) { + this.data = message; + } + + public T getData() { + return data; + } +} + +public abstract class CoarseGrainedObject { + + DependentObject[] dependentObjects; + + public void setData(T... data) { + IntStream.range(0, data.length).forEach(i -> dependentObjects[i].setData(data[i])); + } + + public T[] getData() { + return (T[]) Arrays.stream(dependentObjects).map(DependentObject::getData).toArray(); + } +} + +``` + +专用的 `console` 复合实体继承自这个基类,如下所示。 + +```java +public class MessageDependentObject extends DependentObject { + +} + +public class SignalDependentObject extends DependentObject { + +} + +public class ConsoleCoarseGrainedObject extends CoarseGrainedObject { + + @Override + public String[] getData() { + super.getData(); + return new String[]{ + dependentObjects[0].getData(), dependentObjects[1].getData() + }; + } + + public void init() { + dependentObjects = new DependentObject[]{ + new MessageDependentObject(), new SignalDependentObject()}; + } +} + +public class CompositeEntity { + + private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); + + public void setData(String message, String signal) { + console.setData(message, signal); + } + + public String[] getData() { + return console.getData(); + } +} +``` + +现在我们使用 `console` 复合实体来进行消息对象、信号对象的分配。 + +```java +var console = new CompositeEntity(); +console.init(); +console.setData("No Danger", "Green Light"); +Arrays.stream(console.getData()).forEach(LOGGER::info); +console.setData("Danger", "Red Light"); +Arrays.stream(console.getData()).forEach(LOGGER::info); +``` + +## 类图 + +![alt text](./etc/composite_entity.urm.png "Composite Entity Pattern") + +## 适用场景 + +复合实体模式适用于以下场景: + +* 你想要通过一个对象来管理多个依赖对象,已调整对象之间的细化程度。同时将依赖对象的生命周期托管到这个粗粒度的复合实体对象。 +## 引用 + +* [Composite Entity Pattern in wikipedia](https://en.wikipedia.org/wiki/Composite_entity_pattern) \ No newline at end of file diff --git a/localization/zh/composite-entity/etc/composite_entity.urm.png b/localization/zh/composite-entity/etc/composite_entity.urm.png new file mode 100644 index 000000000000..d6c29a718837 Binary files /dev/null and b/localization/zh/composite-entity/etc/composite_entity.urm.png differ diff --git a/localization/zh/composite/README.md b/localization/zh/composite/README.md new file mode 100644 index 000000000000..88d05c9cc6fb --- /dev/null +++ b/localization/zh/composite/README.md @@ -0,0 +1,173 @@ +--- +title: Composite +shortTitle: Composite +category: Structural +language: zh +tag: + - Gang of Four +--- + +## 目的 + +将对象组合成树结构以表示部分整体层次结构。 组合可以使客户统一对待单个对象和组合对象。 + +## 解释 + +真实世界例子 + +> 每个句子由单词组成,单词又由字符组成。这些对象中的每一个都是可打印的,它们可以在它们之前或之后打印一些内容,例如句子始终以句号结尾,单词始终在其前面有空格。 + +通俗的说 + +> 组合模式使客户能够以统一的方式对待各个对象。 + +维基百科说 + +> 在软件工程中,组合模式是一种分区设计模式。组合模式中,一组对象将像一个对象的单独实例一样被对待。组合的目的是将对象“组成”树状结构,以表示部分整体层次结构。实现组合模式可使客户统一对待单个对象和组合对象。 + +**程序示例** + +使用上面的句子例子。 这里我们有基类`LetterComposite`和不同的可打印类型`Letter`,`Word`和`Sentence`。 + +```java +public abstract class LetterComposite { + + private final 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(); + children.forEach(LetterComposite::print); + printThisAfter(); + } +} + +public class Letter extends LetterComposite { + + private final char character; + + public Letter(char c) { + this.character = c; + } + + @Override + protected void printThisBefore() { + System.out.print(character); + } +} + +public class Word extends LetterComposite { + + public Word(List letters) { + letters.forEach(this::add); + } + + public Word(char... letters) { + for (char letter : letters) { + this.add(new Letter(letter)); + } + } + + @Override + protected void printThisBefore() { + System.out.print(" "); + } +} + +public class Sentence extends LetterComposite { + + public Sentence(List words) { + words.forEach(this::add); + } + + @Override + protected void printThisAfter() { + System.out.print("."); + } +} +``` + +然后我们有一个消息携带者来携带消息。 + +```java +public class Messenger { + + LetterComposite messageFromOrcs() { + + var words = List.of( + new Word('W', 'h', 'e', 'r', 'e'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'h', 'i', 'p'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'a', 'y') + ); + + return new Sentence(words); + + } + + LetterComposite messageFromElves() { + + var words = List.of( + new Word('M', 'u', 'c', 'h'), + new Word('w', 'i', 'n', 'd'), + new Word('p', 'o', 'u', 'r', 's'), + new Word('f', 'r', 'o', 'm'), + new Word('y', 'o', 'u', 'r'), + new Word('m', 'o', 'u', 't', 'h') + ); + + return new Sentence(words); + + } + +} +``` + +然后它可以这样使用: + +```java +var orcMessage = new Messenger().messageFromOrcs(); +orcMessage.print(); // Where there is a whip there is a way. +var elfMessage = new Messenger().messageFromElves(); +elfMessage.print(); // Much wind pours from your mouth. +``` + +## 类图 + +![alt text](./etc/composite.urm.png "Composite class diagram") + +## 适用性 + +使用组合模式当 + +* 你想要表示对象的整体层次结构 +* 你希望客户能够忽略组合对象和单个对象之间的差异。 客户将统一对待组合结构中的所有对象。 + +## 真实世界例子 + +* [java.awt.Container](http://docs.oracle.com/javase/8/docs/api/java/awt/Container.html) and [java.awt.Component](http://docs.oracle.com/javase/8/docs/api/java/awt/Component.html) +* [Apache Wicket](https://github.com/apache/wicket) component tree, see [Component](https://github.com/apache/wicket/blob/91e154702ab1ff3481ef6cbb04c6044814b7e130/wicket-core/src/main/java/org/apache/wicket/Component.java) and [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/zh/composite/etc/composite.urm.png b/localization/zh/composite/etc/composite.urm.png new file mode 100644 index 000000000000..93c160f6450a Binary files /dev/null and b/localization/zh/composite/etc/composite.urm.png differ diff --git a/localization/zh/converter/README.md b/localization/zh/converter/README.md new file mode 100644 index 000000000000..2164f712c74b --- /dev/null +++ b/localization/zh/converter/README.md @@ -0,0 +1,100 @@ +--- +title: Converter +shortTitle: Converter +category: Creational +language: zh +tag: + - Decoupling +--- + +## 目的 + +转换器模式的目的是提供相应类型之间双向转换的通用方法,允许进行干净的实现,而类型之间无需相互了解。此外,Converter模式引入了双向集合映射,从而将样板代码减少到最少。 + +## 解释 + +真实世界例子 + +> 在真实的应用中经常有这种情况,数据库层包含需要被转换成业务逻辑层DTO来使用的实体。对于潜在的大量类进行类似的映射,我们需要一种通用的方法来实现这一点。 + +通俗的说 + +> 转换器模式让一个类的实例映射成另一个类的实例变得简单 + +**程序示例** + +我们需要一个通用的方案来解决映射问题。让我们来介绍一个通用的转换器。 + +```java +public class Converter { + + private final Function fromDto; + private final Function fromEntity; + + public Converter(final Function fromDto, final Function fromEntity) { + this.fromDto = fromDto; + this.fromEntity = fromEntity; + } + + public final U convertFromDto(final T dto) { + return fromDto.apply(dto); + } + + public final T convertFromEntity(final U entity) { + return fromEntity.apply(entity); + } + + public final List createFromDtos(final Collection dtos) { + return dtos.stream().map(this::convertFromDto).collect(Collectors.toList()); + } + + public final List createFromEntities(final Collection entities) { + return entities.stream().map(this::convertFromEntity).collect(Collectors.toList()); + } +} +``` + +专属的转换器像下面一样从基类继承。 + +```java +public class UserConverter extends Converter { + + public UserConverter() { + super(UserConverter::convertToEntity, UserConverter::convertToDto); + } + + private static UserDto convertToDto(User user) { + return new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), user.getUserId()); + } + + private static User convertToEntity(UserDto dto) { + return new User(dto.getFirstName(), dto.getLastName(), dto.isActive(), dto.getEmail()); + } + +} +``` + +现在,在User和UserDto之间的映射变得轻而易举。 + +```java +var userConverter = new UserConverter(); +var dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); +var user = userConverter.convertFromDto(dtoUser); +``` + +## 类图 + +![alt text](./etc/converter.png "Converter Pattern") + +## 适用性 + +在下面这些情况下使用转换器模式: + +* 如果你的类型在逻辑上相互对应,并需要在它们之间转换实体 +* 当你想根据上下文提供不同的类型转换方式时 +* 每当你引入DTO(数据传输对象)时你可能都需要将其转换为 + DO + +## 鸣谢 + +* [Converter](http://www.xsolve.pl/blog/converter-pattern-in-java-8/) diff --git a/localization/zh/converter/etc/converter.png b/localization/zh/converter/etc/converter.png new file mode 100644 index 000000000000..01435ef5ae29 Binary files /dev/null and b/localization/zh/converter/etc/converter.png differ diff --git a/localization/zh/crtp/README.md b/localization/zh/crtp/README.md new file mode 100644 index 000000000000..297c89fdccbb --- /dev/null +++ b/localization/zh/crtp/README.md @@ -0,0 +1,135 @@ +--- +title: Curiously Recurring Template Pattern +shortTitle: Curiously Recurring Template Pattern +language: zh +category: Structural +tag: +- Extensibility +- Instantiation +--- + +## 名称/分类 + +Curiously Recurring Template Pattern,CRTP,奇异递归模板模式 + +## 别名 + +递归类型绑定,递归泛型 + +## 目的 + +允许派生组件从与派生类型兼容的基本组件继承某些功能。 + +## 解释 + +真实世界的例子 + +> 对于正在策划赛事的综合格斗推广活动来说,确保在相同重量级的运动员之间组织比赛至关重要。这样可以防止体型明显不同的拳手之间的不匹配,例如重量级拳手与雏量级拳手的对决。 + +用通俗的话来讲 + +> 使类型中的某些方法接受特定于其子类型的参数。 + +维基百科介绍 + +> 奇异递归模板模式(curiously recurring template pattern,CRTP)是C++模板编程时的一种惯用法:其中类X派生自使用X本身作为模板参数的类模板实例化。 + +**程序示例** + +让我们来定义通用接口Fighter + +```java +public interface Fighter { + + void fight(T t); + +} +``` + +MmaFighter类用于实例化按重量级别区分的拳手 + +``` Java +public class MmaFighter> implements Fighter { + + private final String name; + private final String surname; + private final String nickName; + private final String speciality; + + public MmaFighter(String name, String surname, String nickName, String speciality) { + this.name = name; + this.surname = surname; + this.nickName = nickName; + this.speciality = speciality; + } + + @Override + public void fight(T opponent) { + LOGGER.info("{} is going to fight against {}", this, opponent); + } + + @Override + public String toString() { + return name + " \"" + nickName + "\" " + surname; + } +``` + +以下是 MmaFighter 的一些子类型 + +```Java +class MmaBantamweightFighter extends MmaFighter { + + public MmaBantamweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } + +} + +public class MmaHeavyweightFighter extends MmaFighter { + + public MmaHeavyweightFighter(String name, String surname, String nickName, String speciality) { + super(name, surname, nickName, speciality); + } + +} +``` + +允许拳手与相同重量级的对手交手,如果对手是不同重量级,则会出现错误 + +``` Java +MmaBantamweightFighter fighter1 = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai"); +MmaBantamweightFighter fighter2 = new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo"); +fighter1.fight(fighter2); // This is fine + +MmaHeavyweightFighter fighter3 = new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing"); +MmaHeavyweightFighter fighter4 = new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu"); +fighter3.fight(fighter4); // This is fine too + +fighter1.fight(fighter3); // This will raise a compilation error +``` + +## 类图 + +![alt text](etc/crtp.png "CRTP class diagram") + +## 适用性 + +在以下情况下使用CRTP + +* 在对象层次结构中链接方法时存在类型冲突 +* 您想使用一个参数化的类方法,该方法可以接受类的子类作为参数,从而可以应用于继承自类的对象 +* 您希望某些方法仅适用于相同类型的实例,例如实现相互比较。 + +## 教程 + +* [The NuaH Blog](https://nuah.livejournal.com/328187.html) +* Yogesh Umesh Vaity answer to [What does "Recursive type bound" in Generics mean?](https://stackoverflow.com/questions/7385949/what-does-recursive-type-bound-in-generics-mean) + +## 已知用途 + +* [java.lang.Enum](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Enum.html) + +## 鸣谢 + +* [How do I decrypt "Enum>"?](http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ106) +* Chapter 5 Generics, Item 30 in [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) diff --git a/localization/zh/crtp/etc/crtp.png b/localization/zh/crtp/etc/crtp.png new file mode 100644 index 000000000000..a348c8af6175 Binary files /dev/null and b/localization/zh/crtp/etc/crtp.png differ diff --git a/localization/zh/dao/README.md b/localization/zh/dao/README.md new file mode 100644 index 000000000000..0d9370e83618 --- /dev/null +++ b/localization/zh/dao/README.md @@ -0,0 +1,161 @@ +--- +title: Data Access Object +shortTitle: Data Access Object +category: Architectural +language: zh +tag: + - Data access +--- + +## 目的 + +对象为某种类型的数据库或其他持久性机制提供了抽象接口。 + +## 解释 + +真实世界例子 + +> 有一组客户数据需要持久化到数据库中。 我们需要整个额外的增删改查操作以便操作客户数据。 + +通俗的说 + +> DAO是我们通过基本持久性机制提供的接口。 + +维基百科说 + +> 在计算机软件中,数据访问对象(DAO)是一种模式,可为某种类型的数据库或其他持久性机制提供抽象接口。 + +**程序示例** + +通过我们的客户示例,下面是基本的`客户`实体。 + +```java +public class Customer { + + private int id; + private String firstName; + private String lastName; + + public Customer(int id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + // getters and setters -> + ... +} +``` + +这是`CustomerDao`接口及其两个不同的实现。 + +Here's the `CustomerDao` interface and two different implementations for it. `InMemoryCustomerDao` +将简单的客户数据映射保存在内存中 而`DBCustomerDao`是真正的RDBMS实现。 + +```java +public interface CustomerDao { + + Stream getAll() throws Exception; + + Optional getById(int id) throws Exception; + + boolean add(Customer customer) throws Exception; + + boolean update(Customer customer) throws Exception; + + boolean delete(Customer customer) throws Exception; +} + +public class InMemoryCustomerDao implements CustomerDao { + + private final Map idToCustomer = new HashMap<>(); + + // implement the interface using the map + ... +} + +public class DbCustomerDao implements CustomerDao { + + private static final Logger LOGGER = LoggerFactory.getLogger(DbCustomerDao.class); + + private final DataSource dataSource; + + public DbCustomerDao(DataSource dataSource) { + this.dataSource = dataSource; + } + + // implement the interface using the data source + ... +``` + +最后,这是我们使用DAO管理客户数据的方式。 + +```java + final var dataSource = createDataSource(); + createSchema(dataSource); + final var customerDao = new DbCustomerDao(dataSource); + + addCustomers(customerDao); + log.info(ALL_CUSTOMERS); + try (var customerStream = customerDao.getAll()) { + customerStream.forEach((customer) -> log.info(customer.toString())); + } + log.info("customerDao.getCustomerById(2): " + customerDao.getById(2)); + final var customer = new Customer(4, "Dan", "Danson"); + customerDao.add(customer); + log.info(ALL_CUSTOMERS + customerDao.getAll()); + customer.setFirstName("Daniel"); + customer.setLastName("Danielson"); + customerDao.update(customer); + log.info(ALL_CUSTOMERS); + try (var customerStream = customerDao.getAll()) { + customerStream.forEach((cust) -> log.info(cust.toString())); + } + customerDao.delete(customer); + log.info(ALL_CUSTOMERS + customerDao.getAll()); + + deleteSchema(dataSource); +``` + +程序输出: + +```java +customerDao.getAllCustomers(): +Customer{id=1, firstName='Adam', lastName='Adamson'} +Customer{id=2, firstName='Bob', lastName='Bobson'} +Customer{id=3, firstName='Carl', lastName='Carlson'} +customerDao.getCustomerById(2): Optional[Customer{id=2, firstName='Bob', lastName='Bobson'}] +customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@7cef4e59 +customerDao.getAllCustomers(): +Customer{id=1, firstName='Adam', lastName='Adamson'} +Customer{id=2, firstName='Bob', lastName='Bobson'} +Customer{id=3, firstName='Carl', lastName='Carlson'} +Customer{id=4, firstName='Daniel', lastName='Danielson'} +customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@2db0f6b2 +customerDao.getAllCustomers(): +Customer{id=1, firstName='Adam', lastName='Adamson'} +Customer{id=2, firstName='Bob', lastName='Bobson'} +Customer{id=3, firstName='Carl', lastName='Carlson'} +customerDao.getCustomerById(2): Optional[Customer{id=2, firstName='Bob', lastName='Bobson'}] +customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@12c8a2c0 +customerDao.getAllCustomers(): +Customer{id=1, firstName='Adam', lastName='Adamson'} +Customer{id=2, firstName='Bob', lastName='Bobson'} +Customer{id=3, firstName='Carl', lastName='Carlson'} +Customer{id=4, firstName='Daniel', lastName='Danielson'} +customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@6ec8211c +``` + +## 类图 + +![alt text](./etc/dao.png "Data Access Object") + +## 适用性 + +在以下情况下,请使用数据访问对象:: + +* 当您要巩固如何访问数据层时。 +* 当您要避免编写多个数据检索/持久层时。 + +## 鸣谢 + +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) diff --git a/localization/zh/dao/etc/dao.png b/localization/zh/dao/etc/dao.png new file mode 100644 index 000000000000..452e72ba10ac Binary files /dev/null and b/localization/zh/dao/etc/dao.png differ diff --git a/localization/zh/data-bus/README.md b/localization/zh/data-bus/README.md new file mode 100644 index 000000000000..5ce08a8ca22f --- /dev/null +++ b/localization/zh/data-bus/README.md @@ -0,0 +1,29 @@ +--- +title: Data Bus +shortTitle: Data Bus +category: Architectural +language: zh +tag: + - Decoupling +--- + +## 含义 + +数据总线模式(译者:实际上,就是 Event-Bus 消息总线模式)允许在一个应用程序的组件之间收发消息/事件,而不需要这些组件相互感知,它们只需要知道所发送/接收的消息/事件的类型即可。 + +## 类图 +![data bus pattern uml diagram](./etc/data-bus.urm.png "Data Bus pattern") + +## 适用场景 +可以在以下场景使用数据总线模式: + +* 你希望由你的组件自己决定要接收哪些信息/事件 +* 你希望实现多对多的通信 +* 你希望你的组件不需要感知彼此 + +## 相关模式 +数据总线类似于以下设计模式: + +* 中介者模式(Mediator pattern),由数据总线成员自己决定是否要接受任何给定的消息。 +* 观察者模式(Observer pattern),但进一步支持了多对多的通信。 +* 发布/订阅模式(Publish/Subscribe pattern),但是数据总线将发布者和订阅者解耦。 \ No newline at end of file diff --git a/localization/zh/data-bus/etc/data-bus.urm.png b/localization/zh/data-bus/etc/data-bus.urm.png new file mode 100644 index 000000000000..8bd2148174e4 Binary files /dev/null and b/localization/zh/data-bus/etc/data-bus.urm.png differ diff --git a/localization/zh/data-mapper/README.md b/localization/zh/data-mapper/README.md new file mode 100644 index 000000000000..59388b364e75 --- /dev/null +++ b/localization/zh/data-mapper/README.md @@ -0,0 +1,24 @@ +--- +title: Data Mapper +shortTitle: Data Mapper +category: Architectural +language: zh +tag: + - Decoupling +--- + +## 含义 +一个用于在持久化对象和数据库之间传输数据的映射器,同时保持它们之间和映射器本身的独立性。 + +## 类图 +![alt text](./etc/data-mapper.png "Data Mapper") + +## 适用场景 +数据映射器适用于以下场景: + +* 当你想把数据对象从数据库访问层解耦时时 +* 当你想编写多个数据查询/持久化实现时 + +## 引用 + +* [Data Mapper](http://richard.jp.leguen.ca/tutoring/soen343-f2010/tutorials/implementing-data-mapper/) \ No newline at end of file diff --git a/localization/zh/data-mapper/etc/data-mapper.png b/localization/zh/data-mapper/etc/data-mapper.png new file mode 100644 index 000000000000..bcda8054aac8 Binary files /dev/null and b/localization/zh/data-mapper/etc/data-mapper.png differ diff --git a/localization/zh/data-transfer-object/README.md b/localization/zh/data-transfer-object/README.md new file mode 100644 index 000000000000..38a637aec091 --- /dev/null +++ b/localization/zh/data-transfer-object/README.md @@ -0,0 +1,110 @@ +--- +title: Data Transfer Object +shortTitle: Data Transfer Object +category: Architectural +language: zh +tag: + - Performance +--- + +## 目的 + +次将具有多个属性的数据从客户端传递到服务器,以避免多次调用远程服务器。 + +## 解释 + +真实世界例子 + +> 我们需要从远程数据库中获取有关客户的信息。 我们不使用一次查询一个属性,而是使用DTO一次传送所有相关属性。 + +通俗的说 + +> 使用DTO,可以通过单个后端查询获取相关信息。 + +维基百科说 + +> 在编程领域,数据传输对象(DTO)是在进程之间承载数据的对象。 使用它的动机是,通常依靠远程接口(例如Web服务)来完成进程之间的通信,在这种情况下,每个调用都是昂贵的操作。 +> +> 因为每个(方法)调用的大部分成本与客户端和服务器之间的往返时间有关,所以减少调用数量的一种方法是使用一个对象(DTO)来聚合将要在多次调用间传输的数据,但仅由一个调用提供。 + +**程序示例** + +让我们来介绍我们简单的`CustomerDTO` 类 + +```java +public class CustomerDto { + private final String id; + private final String firstName; + private final String lastName; + + 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; + } +} +``` + +`CustomerResource` 类充当客户信息的服务器。 + +```java +public class CustomerResource { + private final List customers; + + public CustomerResource(List customers) { + this.customers = customers; + } + + public List getAllCustomers() { + return customers; + } + + public void save(CustomerDto customer) { + customers.add(customer); + } + + public void delete(String customerId) { + customers.removeIf(customer -> customer.getId().equals(customerId)); + } +} +``` + +现在拉取客户信息变得简单自从我们有了DTOs。 + +```java + var allCustomers = customerResource.getAllCustomers(); + allCustomers.forEach(customer -> LOGGER.info(customer.getFirstName())); + // Kelly + // Alfonso +``` + +## 类图 + +![alt text](./etc/data-transfer-object.urm.png "data-transfer-object") + +## 适用性 + +使用数据传输对象模式当 + +* 客户端请求多种信息。信息都是相关的 +* 当你想提高获取资源的性能 +* 你想降低远程方法调用的次数 + +## 鸣谢 + +* [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) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321127420&linkCode=as2&tag=javadesignpat-20&linkId=014237a67c9d46f384b35e10151956bd) diff --git a/localization/zh/data-transfer-object/etc/data-transfer-object.urm.png b/localization/zh/data-transfer-object/etc/data-transfer-object.urm.png new file mode 100644 index 000000000000..46facff8dee4 Binary files /dev/null and b/localization/zh/data-transfer-object/etc/data-transfer-object.urm.png differ diff --git a/localization/zh/decorator/README.md b/localization/zh/decorator/README.md new file mode 100644 index 000000000000..a1a46ef83e69 --- /dev/null +++ b/localization/zh/decorator/README.md @@ -0,0 +1,134 @@ +--- +title: Decorator +shortTitle: Decorator +category: Structural +language: zh +tag: + - Gang Of Four + - Extensibility +--- + +## 或称 +包装器 + +## 目的 +动态的为对象附加额外的职责。装饰器为子类提供了灵活的替代方案,以扩展功能。 + +## 解释 + +真实世界例子 + +> 附近的山丘上住着一个愤怒的巨魔。通常它是徒手的,但有时它有武器。为了武装巨魔不必创建新的巨魔,而是用合适的武器动态的装饰它。 + +通俗的说 + +> 装饰者模式让你可以在运行时通过把对象包装进一个装饰类对象中来动态的改变一个对象的行为。 + +维基百科说 + +> 在面向对象的编程中,装饰器模式是一种设计模式,它允许将行为静态或动态地添加到单个对象中,而不会影响同一类中其他对象的行为。装饰器模式通常对于遵守单一责任原则很有用,因为它允许将功能划分到具有唯一关注领域的类之间。 + +**程序示例** + +以巨魔的为例。首先我有有一个简单的巨魔,实现了巨魔接口。 + +```java +public interface Troll { + void attack(); + int getAttackPower(); + void fleeBattle(); +} + +@Slf4j +public class SimpleTroll implements Troll { + + @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!"); + } +} +``` + +下面我们想为巨魔添加球棒。我们可以用装饰者来动态的实现。 + +```java +@Slf4j +public class ClubbedTroll implements Troll { + + private final 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(); + } +} +``` + +这里是巨魔的实战 + +```java +// simple troll +var 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 +var clubbedTroll = new ClubbedTroll(troll); +clubbedTroll.attack(); // The troll tries to grab you! The troll swings at you with a club! +clubbedTroll.fleeBattle(); // The troll shrieks in horror and runs away! +``` + +## 类图 +![alt text](./etc/decorator.urm.png "Decorator pattern class diagram") + +## 适用性 +使用装饰者 + +* 动态透明地向单个对象添加职责,即不影响其他对象 +* 对于可以撤销的责任 +* 当通过子类化进行扩展是不切实际的。有时可能会有大量的独立扩展,并且会产生大量的子类来支持每种组合。 否则类定义可能被隐藏或无法用于子类化。 + +## 教程 +* [Decorator Pattern Tutorial](https://www.journaldev.com/1540/decorator-design-pattern-in-java-example) + +## Java世界的例子 + * [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), + [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) and [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) + * [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-) + * [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-) + * [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-) + + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/zh/decorator/etc/decorator.urm.png b/localization/zh/decorator/etc/decorator.urm.png new file mode 100644 index 000000000000..141c0563f0c6 Binary files /dev/null and b/localization/zh/decorator/etc/decorator.urm.png differ diff --git a/localization/zh/delegation/README.md b/localization/zh/delegation/README.md new file mode 100644 index 000000000000..3932d895d501 --- /dev/null +++ b/localization/zh/delegation/README.md @@ -0,0 +1,28 @@ +--- +title: Delegation +shortTitle: Delegation +category: Structural +language: zh +tag: + - Decoupling +--- + +## 或称 +代理模式 + +## 目的 +它是一种让对象将某种行为向外部表达,但实际上将实现该行为的责任委托给关联对象的技术。 + +## 类图 +![alt text](./etc/delegation.png "Delegate") + +## 适用性 +使用委托模式以实现以下目的 + +* 降低类的耦合性 +* 组件的行为相同,但是意识到这种情况将来可能会改变。 + +## 鸣谢 + +* [Delegate Pattern: Wikipedia ](https://en.wikipedia.org/wiki/Delegation_pattern) +* [Proxy Pattern: Wikipedia ](https://en.wikipedia.org/wiki/Proxy_pattern) diff --git a/localization/zh/delegation/etc/delegation.png b/localization/zh/delegation/etc/delegation.png new file mode 100644 index 000000000000..375ef4d6b00f Binary files /dev/null and b/localization/zh/delegation/etc/delegation.png differ diff --git a/localization/zh/dependency-injection/README.md b/localization/zh/dependency-injection/README.md new file mode 100644 index 000000000000..2b0ae7b036b3 --- /dev/null +++ b/localization/zh/dependency-injection/README.md @@ -0,0 +1,100 @@ +--- +title: Dependency Injection +shortTitle: Dependency Injection +category: Creational +language: zh +tag: + - Decoupling +--- + +## 目的 + +依赖注入是一种软件设计模式,其中一个或多个依赖项(或服务)被注入或通过引用传递到一个依赖对象(或客户端)中,并成为客户端状态的一部分。该模式将客户的依赖关系的创建与其自身的行为分开,这使程序设计可以松散耦合,并遵循控制反转和单一职责原则。 + +## 解释 + +真实世界例子 + +> 老巫师喜欢不时地装满烟斗抽烟。 但是,他不想只依赖一个烟草品牌,而是希望能够互换使用它们。 + +通俗的说 + +> 依赖注入将客户端依赖的创建与其自身行为分开。 + +维基百科说 + +> 在软件工程中,依赖注入是一种对象接收其依赖的其他对象的技术。 这些其他对象称为依赖项。 + +**程序示例** + +先介绍一下烟草接口和具体的品牌。 + +```java +public abstract class Tobacco { + + private static final Logger LOGGER = LoggerFactory.getLogger(Tobacco.class); + + public void smoke(Wizard wizard) { + LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(), + this.getClass().getSimpleName()); + } +} + +public class SecondBreakfastTobacco extends Tobacco { +} + +public class RivendellTobacco extends Tobacco { +} + +public class OldTobyTobacco extends Tobacco { +} +``` + +下面是老巫师的类的层次结构。 + +```java +public interface Wizard { + + void smoke(); +} + +public class AdvancedWizard implements Wizard { + + private final Tobacco tobacco; + + public AdvancedWizard(Tobacco tobacco) { + this.tobacco = tobacco; + } + + @Override + public void smoke() { + tobacco.smoke(this); + } +} +``` + +最后我们可以看到给老巫师任意品牌的烟草是多么的简单。 + +```java + var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco()); + advancedWizard.smoke(); +``` + +## 类图 + +![alt text](./etc/dependency-injection.png "Dependency Injection") + +## 适用性 + +使用依赖注入当: + +- 当你需要从对象中移除掉具体的实现内容时 + +* 使用模拟对象或存根隔离地启用类的单元测试 + +## 鸣谢 + +* [Dependency Injection Principles, Practices, and Patterns](https://www.amazon.com/gp/product/161729473X/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=161729473X&linkId=57079257a5c7d33755493802f3b884bd) +* [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.com/gp/product/0132350882/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0132350882&linkCode=as2&tag=javadesignpat-20&linkId=2c390d89cc9e61c01b9e7005c7842871) +* [Java 9 Dependency Injection: Write loosely coupled code with Spring 5 and Guice](https://www.amazon.com/gp/product/1788296257/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=1788296257&linkId=4e9137a3bf722a8b5b156cce1eec0fc1) +* [Google Guice Tutorial: Open source Java based dependency injection framework](https://www.amazon.com/gp/product/B083P7DZ8M/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B083P7DZ8M&linkId=04f0f902c877921e45215b624a124bfe) diff --git a/localization/zh/dependency-injection/etc/dependency-injection.png b/localization/zh/dependency-injection/etc/dependency-injection.png new file mode 100644 index 000000000000..2a92c9eb228b Binary files /dev/null and b/localization/zh/dependency-injection/etc/dependency-injection.png differ diff --git a/localization/zh/dirty-flag/README.md b/localization/zh/dirty-flag/README.md new file mode 100644 index 000000000000..9a7bb8f77c41 --- /dev/null +++ b/localization/zh/dirty-flag/README.md @@ -0,0 +1,28 @@ +--- +title: Dirty Flag +shortTitle: Dirty Flag +category: Behavioral +language: zh +tag: + - Game programming + - Performance +--- + +## 或称 +* 是否脏 模式 + +## 目的 +避免昂贵资源的重新获取。资源保留其身份,保留在某些快速访问的存储中,并被重新使用以避免再次获取它们。 + +## 类图 +![alt text](./etc/dirty-flag.png "Dirty Flag") + +## 适用性 +在以下情况下使用脏标志模式 + +* 重复获取,初始化,释放相同资源所导致不必要的性能开销 + +## 鸣谢 + +* [Design Patterns: Dirty Flag](https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) diff --git a/localization/zh/dirty-flag/etc/dirty-flag.png b/localization/zh/dirty-flag/etc/dirty-flag.png new file mode 100644 index 000000000000..98d4f679d17c Binary files /dev/null and b/localization/zh/dirty-flag/etc/dirty-flag.png differ diff --git a/localization/zh/double-checked-locking/README.md b/localization/zh/double-checked-locking/README.md new file mode 100644 index 000000000000..539127027ec7 --- /dev/null +++ b/localization/zh/double-checked-locking/README.md @@ -0,0 +1,20 @@ +--- +title: Double Checked Locking +shortTitle: Double Checked Locking +category: Idiom +language: zh +tag: + - Performance +--- + +## 含义 +通过先测试锁定标准("锁提示")而不实际获取锁的方式来减少获取锁的开销。只有当锁定标准检查表明需要锁定时,才进行实际的锁定逻辑。 + +## 类图 +![alt text](./etc/double_checked_locking_1.png "Double Checked Locking") + +## 适用场景 +在以下场景适合使用双重锁检查模式: + +* 在创建对象时有存在并发的访问。如单例模式中,你想创建同一个类的单个实例,如果存在两个或更多的线程对实例进行判空,仅仅检查该该实例是否为空可能是不够的。 +* 在一个方法上存在并发访问,该方法的行为是根据一些约束条件而改变,而这些约束条件在该方法中也会发生变化。 \ No newline at end of file diff --git a/localization/zh/double-checked-locking/etc/double_checked_locking_1.png b/localization/zh/double-checked-locking/etc/double_checked_locking_1.png new file mode 100644 index 000000000000..cced091b9d67 Binary files /dev/null and b/localization/zh/double-checked-locking/etc/double_checked_locking_1.png differ diff --git a/localization/zh/facade/README.md b/localization/zh/facade/README.md new file mode 100644 index 000000000000..9d8689b8d879 --- /dev/null +++ b/localization/zh/facade/README.md @@ -0,0 +1,191 @@ +--- +title: Facade +shortTitle: Facade +category: Structural +language: zh +tag: + - Gang Of Four + - Decoupling +--- + +## 目的 +为一个子系统中的一系列接口提供一个统一的接口。外观定义了一个更高级别的接口以便子系统更容易使用。 + +## 解释 + +真实世界的例子 + +> 一个金矿是怎么工作的?“嗯,矿工下去然后挖金子!”你说。这是你所相信的因为你在使用一个金矿对外提供的一个简单接口,在内部它要却要做很多事情。这个简单的接口对复杂的子系统来说就是一个外观。 + +用通俗的话说 + +> 外观模式为一个复杂的子系统提供一个简单的接口。 + +维基百科说 + +> 外观是为很大体量的代码(比如类库)提供简单接口的一种对象。 + +**程序示例** + +使用上面金矿的例子。这里我们有矮人的矿工等级制度。 + +```java + +@Slf4j +public abstract class DwarvenMineWorker { + + public void goToSleep() { + LOGGER.info("{} goes to sleep.", name()); + } + + public void wakeUp() { + LOGGER.info("{} wakes up.", name()); + } + + public void goHome() { + LOGGER.info("{} goes home.", name()); + } + + public void goToMine() { + LOGGER.info("{} goes to the mine.", name()); + } + + private void action(Action action) { + switch (action) { + case GO_TO_SLEEP -> goToSleep(); + case WAKE_UP -> wakeUp(); + case GO_HOME -> goHome(); + case GO_TO_MINE -> goToMine(); + case WORK -> work(); + default -> LOGGER.info("Undefined action"); + } + } + + public void action(Action... actions) { + Arrays.stream(actions).forEach(this::action); + } + + public abstract void work(); + + public abstract String name(); + + enum Action { + GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK + } +} + +@Slf4j +public class DwarvenTunnelDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} creates another promising tunnel.", name()); + } + + @Override + public String name() { + return "Dwarven tunnel digger"; + } +} + +@Slf4j +public class DwarvenGoldDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} digs for gold.", name()); + } + + @Override + public String name() { + return "Dwarf gold digger"; + } +} + +@Slf4j +public class DwarvenCartOperator extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} moves gold chunks out of the mine.", name()); + } + + @Override + public String name() { + return "Dwarf cart operator"; + } +} + +``` + +为了操纵所有这些矿工我们有了这个外观 + +```java +public class DwarvenGoldmineFacade { + + private final List workers; + + public DwarvenGoldmineFacade() { + workers = List.of( + new DwarvenGoldDigger(), + new DwarvenCartOperator(), + new DwarvenTunnelDigger()); + } + + public void startNewDay() { + makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); + } + + public void digOutGold() { + makeActions(workers, DwarvenMineWorker.Action.WORK); + } + + public void endDay() { + makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); + } + + private static void makeActions(Collection workers, + DwarvenMineWorker.Action... actions) { + workers.forEach(worker -> worker.action(actions)); + } +} +``` + +现在来使用外观 + +```java +DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade(); +facade.startNewDay(); +// Dwarf gold digger wakes up. +// Dwarf gold digger goes to the mine. +// Dwarf cart operator wakes up. +// Dwarf cart operator goes to the mine. +// Dwarven tunnel digger wakes up. +// Dwarven tunnel digger goes to the mine. +facade.digOutGold(); +// Dwarf gold digger digs for gold. +// Dwarf cart operator moves gold chunks out of the mine. +// Dwarven tunnel digger creates another promising tunnel. +facade.endDay(); +// Dwarf gold digger goes home. +// Dwarf gold digger goes to sleep. +// Dwarf cart operator goes home. +// Dwarf cart operator goes to sleep. +// Dwarven tunnel digger goes home. +// Dwarven tunnel digger goes to sleep. +``` + +## 类图 +![alt text](./etc/facade.urm.png "Facade pattern class diagram") + +## 适用性 +使用外观模式当 + +* 你想为一个复杂的子系统提供一个简单的接口。随着子系统的发展,它们通常会变得更加复杂。多数模式在应用时会导致更多和更少的类。这使子系统更可重用,更易于自定义,但是对于不需要自定义它的客户来说,使用它也变得更加困难。 外观可以提供子系统的简单默认视图,足以满足大多数客户端的需求。只有需要更多可定制性的客户才需要查看外观外的东西(原子系统提供的接口)。 +* 客户端与抽象的实现类之间存在许多依赖关系。 引入外观以使子系统与客户端和其他子系统分离,从而提高子系统的独立性和可移植性。 +* 您想对子系统进行分层。 使用外观来定义每个子系统级别的入口点。 如果子系统是相关的,则可以通过使子系统仅通过其外观相互通信来简化它们之间的依赖性。 + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/zh/facade/etc/facade.urm.png b/localization/zh/facade/etc/facade.urm.png new file mode 100644 index 000000000000..8e3ec7aca45e Binary files /dev/null and b/localization/zh/facade/etc/facade.urm.png differ diff --git a/localization/zh/factory-kit/README.md b/localization/zh/factory-kit/README.md new file mode 100644 index 000000000000..d23b081f1950 --- /dev/null +++ b/localization/zh/factory-kit/README.md @@ -0,0 +1,26 @@ +--- +title: Factory Kit +shortTitle: Factory Kit +category: Creational +language: zh +tag: + - Extensibility +--- + +## 含义 +使用分离的构建器和工厂接口来定义一个不可变内容的工厂。 + +## 类图 +![alt text](./etc/factory-kit.png "Factory Kit") + +## 适用场景 +工厂套件模式适用于与以下场景: + +* 一个类无法预知它需要创建的对象的类别 +- 你只是想要一个新的自定义构建器(builder)的实例,而非全局的构建器 +- 你明确地想要定义对象的类型,而且工厂可以创建这些对象 +- 你想要分离构建器(builder)和创建器(creator)接口 + +## 引用 + +* [Design Pattern Reloaded by Remi Forax: ](https://www.youtube.com/watch?v=-k2X7guaArU) \ No newline at end of file diff --git a/localization/zh/factory-kit/etc/factory-kit.png b/localization/zh/factory-kit/etc/factory-kit.png new file mode 100644 index 000000000000..7093193cb8d0 Binary files /dev/null and b/localization/zh/factory-kit/etc/factory-kit.png differ diff --git a/localization/zh/factory-method/README.md b/localization/zh/factory-method/README.md new file mode 100644 index 000000000000..f8c8b8db1109 --- /dev/null +++ b/localization/zh/factory-method/README.md @@ -0,0 +1,87 @@ +--- +title: Factory Method +shortTitle: Factory Method +category: Creational +language: zh +tag: + - Extensibility + - Gang Of Four +--- + +## Also known as +# 或称 + +虚拟构造器 + +## 目的 +为创建一个对象定义一个接口,但是让子类决定实例化哪个类。工厂方法允许类将实例化延迟到子类。 + +## 解释 +真实世界例子 + +> 铁匠生产武器。精灵需要精灵武器,而兽人需要兽人武器。根据客户来召唤正确类型的铁匠。 + +通俗的说 + +> 它为类提供了一种把实例化的逻辑委托给子类的方式。 + +维基百科上说 + +> 在基于类的编程中,工厂方法模式是一种创建型设计模式用来解决创建对象的问题,而不需要指定将要创建对象的确切类。这是通过调用工厂方法创建对象来完成的,而不是通过调用构造器。该工厂方法在接口中指定并由子类实现,或者在基类实现并可以选择由子类重写。 + + **程序示例** + +以上面的铁匠为例,首先我们有铁匠的接口和一些它的实现。 + +```java +public interface Blacksmith { + Weapon manufactureWeapon(WeaponType weaponType); +} + +public class ElfBlacksmith implements Blacksmith { + public Weapon manufactureWeapon(WeaponType weaponType) { + return ELFARSENAL.get(weaponType); + } +} + +public class OrcBlacksmith implements Blacksmith { + public Weapon manufactureWeapon(WeaponType weaponType) { + return ORCARSENAL.get(weaponType); + } +} +``` + +现在随着客户的到来,会召唤出正确类型的铁匠并制造出要求的武器。 + +```java +var blacksmith = new ElfBlacksmith(); +blacksmith.manufactureWeapon(WeaponType.SPEAR); +blacksmith.manufactureWeapon(WeaponType.AXE); +// Elvish weapons are created +``` + +## 类图 +![alt text](./etc/factory-method.urm.png "Factory Method pattern class diagram") + +## 适用性 +使用工厂方法模式当 + +* 一个类无法预料它所要必须创建的对象的类 +* 一个类想要它的子类来指定它要创建的对象 +* 类将责任委派给几个帮助子类中的一个,而你想定位了解是具体之中的哪一个 + +## Java中的例子 + +* [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +* [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +* [java.text.NumberFormat](http://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +* [java.nio.charset.Charset](http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +* [java.net.URLStreamHandlerFactory](http://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html#createURLStreamHandler-java.lang.String-) +* [java.util.EnumSet](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of-E-) +* [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/zh/factory-method/etc/factory-method.urm.png b/localization/zh/factory-method/etc/factory-method.urm.png new file mode 100644 index 000000000000..7c97aff91ee6 Binary files /dev/null and b/localization/zh/factory-method/etc/factory-method.urm.png differ diff --git a/localization/zh/factory/README.md b/localization/zh/factory/README.md new file mode 100644 index 000000000000..d399436f8443 --- /dev/null +++ b/localization/zh/factory/README.md @@ -0,0 +1,140 @@ +--- +title: Factory +shortTitle: Factory +category: Creational +language: zh +tag: + - Gang of Four +--- + +## 也被称为 + +* 简单工厂 +* 静态工厂方法 + +## 含义 + +在工厂类中提供一个封装的静态工厂方法,用于隐藏对象初始化细节,使客户端代码可以专注于使用,而不用关心类的初始化过程。 + +## 解释 + +现实例子 + +> +> 假设我们有一个需要连接到 SQL Server 的 Web 应用,但现在我们需要切换到连接 Oracle。为了不修改现有代码的情况下做到这一点,我们需要实现简单工厂模式。在这种模式下,可以通过调用一个静态方法来创建与给定数据库的连接。 + +维基百科 + +> 工厂类是一个用于创建其他对象的对象 -- 从形式上看,工厂方法是一个用于返回不同原型或类型的函数或方法。 + +**编程示例** + +我们有一个 `Car` 接口,以及实现类 `Ford`, `Ferrari`。 + +```java +public interface Car { + String getDescription(); +} + +public class Ford implements Car { + + static final String DESCRIPTION = "This is Ford."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +public class Ferrari implements Car { + + static final String DESCRIPTION = "This is Ferrari."; + + @Override + public String getDescription() { + return DESCRIPTION; + } +} +``` + +Enumeration above represents types of cars that we support (`Ford` and `Ferrari`). + +以下的枚举用于表示支持的 `Car` 类型(`Ford` 和 `Ferrari`) + +```java +public enum CarType { + + FORD(Ford::new), + FERRARI(Ferrari::new); + + private final Supplier constructor; + + CarType(Supplier constructor) { + this.constructor = constructor; + } + + public Supplier getConstructor() { + return this.constructor; + } +} +``` +接着我们实现了一个静态方法 `getCar` 用于封装工厂类 `CarsFactory` 创建 `Car` 具体对象实例的细节。 + +```java +public class CarsFactory { + + public static Car getCar(CarType type) { + return type.getConstructor().get(); + } +} +``` + +现在我们可以在客户端代码中通过工厂类创建不同类型的 `Car` 对象实例。 + +```java +var car1 = CarsFactory.getCar(CarType.FORD); +var car2 = CarsFactory.getCar(CarType.FERRARI); +LOGGER.info(car1.getDescription()); +LOGGER.info(car2.getDescription()); +``` + +程序输出: + +```java +This is Ford. +This is Ferrari. +``` + +## 类图 + +![alt text](./etc/factory.urm.png "Factory pattern class diagram") + +## 适用场景 + +在你只关心对象的创建,但不关心如何创建、管理它的时候,请使用简单工厂模式。 + +**优点** + +* 可以把对象创建代码集中在一个地方,避免在代码库存散布 "new" 关键字。 +* 可以让代码更加低耦合。它的一些主要优点包括更好的可测试性、更好的可读性、组件可替换性、可拓展性、更好的隔离性。 + +**缺点** + +* 会使代码变得比原来的更加复杂一些。 + +## 现实案例 + +* [java.util.Calendar#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) +* [java.util.ResourceBundle#getBundle()](https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) +* [java.text.NumberFormat#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) +* [java.nio.charset.Charset#forName()](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) +* [java.net.URLStreamHandlerFactory#createURLStreamHandler(String)](https://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html) (Returns different singleton objects, depending on a protocol) +* [java.util.EnumSet#of()](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of(E)) +* [javax.xml.bind.JAXBContext#createMarshaller()](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) and other similar methods. + +## 相关模式 + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) +* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/) + diff --git a/localization/zh/factory/etc/factory.urm.png b/localization/zh/factory/etc/factory.urm.png new file mode 100644 index 000000000000..4b3420792e06 Binary files /dev/null and b/localization/zh/factory/etc/factory.urm.png differ diff --git a/localization/zh/interpreter/README.md b/localization/zh/interpreter/README.md new file mode 100644 index 000000000000..a0dc580ae16c --- /dev/null +++ b/localization/zh/interpreter/README.md @@ -0,0 +1,34 @@ +--- +title: Interpreter +shortTitle: Interpreter +category: Behavioral +language: zh +tag: + - Gang of Four +--- + +## 目的 +给定一种语言,请定义其语法的表示形式,以及使用该表示形式来解释该语言中的句子的解释器。 + +## 类图 +![alt text](./etc/interpreter_1.png "Interpreter") + +## 适用性 +有一种要解释的语言时,请使用解释器模式,并且可以将语言中的语句表示为抽象语法树。解释器模式在以下情况下效果最佳 + +* 语法很简单。 对于复杂的语法,语法的类层次结构变得庞大且难以管理。 在这种情况下,解析器生成器之类的工具是更好的选择。 他们可以在不构建抽象语法树的情况下解释表达式,这可以节省空间并可能节省时间 +* 效率不是关键问题。 通常,最有效的解释器不是通过直接解释解析树来实现的,而是先将其转换为另一种形式。 例如,正则表达式通常会转换为状态机。 但是即使这样,翻译器也可以通过解释器模式实现,因此该模式仍然适用。 + +## 真实世界例子 + +* [java.util.Pattern](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) +* [java.text.Normalizer](http://docs.oracle.com/javase/8/docs/api/java/text/Normalizer.html) +* All subclasses of [java.text.Format](http://docs.oracle.com/javase/8/docs/api/java/text/Format.html) +* [javax.el.ELResolver](http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html) + + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/zh/interpreter/etc/interpreter_1.png b/localization/zh/interpreter/etc/interpreter_1.png new file mode 100644 index 000000000000..f10342a1df90 Binary files /dev/null and b/localization/zh/interpreter/etc/interpreter_1.png differ diff --git a/localization/zh/iterator/README.md b/localization/zh/iterator/README.md new file mode 100644 index 000000000000..14f8fb2d68a3 --- /dev/null +++ b/localization/zh/iterator/README.md @@ -0,0 +1,133 @@ +--- +title: Iterator +shortTitle: Iterator +category: Behavioral +language: zh +tag: + - Gang of Four +--- + +## 又被称为 +游标 + +## 目的 +提供一种在不暴露其基础表示的情况下顺序访问聚合对象的元素的方法。 + +## 解释 + +真实世界例子 + +> 百宝箱包含一组魔法物品。有多种物品,例如戒指,药水和武器。可以使用藏宝箱提供的迭代器按类型浏览商品。 + +通俗地说 + +> 容器可以提供与表示形式无关的迭代器接口,以提供对元素的访问。 + +维基百科说 + +> 在面向对象的编程中,迭代器模式是一种设计模式,其中迭代器用于遍历容器并访问容器的元素。 + +**程序示例** + +在我们的示例中包含物品的藏宝箱是主要类。 + +```java +public class TreasureChest { + + private final List items; + + public TreasureChest() { + items = List.of( + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); + } + + public Iterator iterator(ItemType itemType) { + return new TreasureChestItemIterator(this, itemType); + } + + public List getItems() { + return new ArrayList<>(items); + } +} + +public class Item { + + private ItemType type; + private final String name; + + public Item(ItemType type, String name) { + this.setType(type); + this.name = name; + } + + @Override + public String toString() { + return name; + } + + public ItemType getType() { + return type; + } + + public final void setType(ItemType type) { + this.type = type; + } +} + +public enum ItemType { + + ANY, WEAPON, RING, POTION + +} +``` + +迭代器接口极度简单。 + +```java +public interface Iterator { + + boolean hasNext(); + + T next(); +} +``` + +在以下示例中,我们遍历在宝箱中找到的戒指类型物品。 + +```java +var itemIterator = TREASURE_CHEST.iterator(ItemType.RING); +while (itemIterator.hasNext()) { + LOGGER.info(itemIterator.next().toString()); +} +// Ring of shadows +// Ring of armor +``` + +## 类图 +![alt text](./etc/iterator_1.png "Iterator") + +## 适用性 +以下情况使用迭代器模式 + +* 在不暴露其内部表示的情况下访问聚合对象的内容 +* 为了支持聚合对象的多种遍历方式 +* 提供一个遍历不同聚合结构的统一接口 + +## Java世界例子 + +* [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html) +* [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/zh/iterator/etc/iterator_1.png b/localization/zh/iterator/etc/iterator_1.png new file mode 100644 index 000000000000..d8313bc5881f Binary files /dev/null and b/localization/zh/iterator/etc/iterator_1.png differ diff --git a/localization/zh/monitor/README.md b/localization/zh/monitor/README.md new file mode 100644 index 000000000000..f6c6cd25443c --- /dev/null +++ b/localization/zh/monitor/README.md @@ -0,0 +1,96 @@ +--- +title: Monitor +shortTitle: Monitor +category: Concurrency +language: zh +tag: + - Performance +--- + +## 或称 + +监控对象模式 + +## 目的 + +主要目的是为多个线程或进程提供一种结构化和受控的方式来安全地访问和操作共享资源,例如变量、数据结构或代码的关键部分,而不会导致冲突或竞争条件。 + +## 解释 + +通俗的说 + +> 监视器模式用于强制对数据进行单线程访问。 一次只允许一个线程在监视器对象内执行代码。 + +维基百科说 + +> 在并发编程(也称为并行编程)中,监视器是一种同步构造,它允许线程具有互斥性和等待(阻止)特定条件变为假的能力。 监视器还具有向其他线程发出信号通知其条件已满足的机制。 + +**程序示例** + +考虑有一家银行通过转账方式将钱从一个帐户转移到另一个帐户。 它是`同步`意味着只有一个线程可以访问此方法,因为如果许多线程访问它并在同一时间将资金从一个帐户转移到另一个帐户,则余额会发生变化! + +``` +class Bank { + + private int[] accounts; + Logger logger; + + public Bank(int accountNum, int baseAmount, Logger logger) { + this.logger = logger; + accounts = new int[accountNum]; + Arrays.fill(accounts, baseAmount); + } + + public synchronized void transfer(int accountA, int accountB, int amount) { + if (accounts[accountA] >= amount) { + accounts[accountB] += amount; + accounts[accountA] -= amount; + logger.info("Transferred from account :" + accountA + " to account :" + accountB + " , amount :" + amount + " . balance :" + getBalance()); + } + } +``` + +getBalance 始终返回总金额,并且每次转账后总金额应相同 + +``` + private synchronized int getBalance() { + int balance = 0; + for (int account : accounts) { + balance += account; + } + return balance; + } + } +``` + +## 类图 +![alt text](./etc/monitor.urm.png "Monitor class diagram") + +## 适用性 + +监视器设计模式应该用于具有需要由多个线程或进程同时访问和操作的共享资源的情况。 此模式在需要同步以防止竞争条件、数据损坏和不一致状态的情况下特别有用。 以下是您应该考虑使用监视器模式的一些情况: + +1. **共享数据**:当您的应用程序涉及需要由多个线程访问和更新的共享数据结构、变量或资源时。 监视器确保一次只有一个线程可以访问共享资源,从而防止冲突并确保数据一致性。 + +2. **关键部分**:当您有代码的关键部分一次只需要由一个线程执行时。 关键部分是操作共享资源的代码部分,并发访问可能会导致问题。 监视器有助于确保在任何给定时间只有一个线程可以执行关键部分。 + +3. **线程安全**:当您需要确保线程安全而不是仅仅依赖锁和信号量等低级同步机制时。 监视器提供了封装同步和资源管理的更高级别的抽象。 + +4. **等待和发信号**:当您遇到线程需要等待满足某些条件才能继续操作时。 监视器通常包含线程等待特定条件以及其他线程在满足条件时通知它们的机制。 + +5. **死锁预防**:当您希望通过提供结构化方式来获取和释放共享资源上的锁来防止死锁时。 监视器通过确保资源访问得到良好管理来帮助避免常见的死锁情况。 + +6. **并发数据结构**:当您实现并发数据结构(例如队列、堆栈或哈希表)时,多个线程需要操作该结构,同时保持其完整性。 + +7. **资源共享**:当多个线程需要共享有限的资源时,例如连接数据库或访问网络套接字。 监视器可以帮助以受控方式管理这些资源的分配和释放。 + +8. **改进可维护性**:当您想要将同步逻辑和共享资源管理封装在单个对象中时,改进代码组织并使并发相关代码更容易推理。 + +但是,需要注意的是,监视器模式可能并不最适合所有并发场景。 在某些情况下,其他同步机制(例如锁、信号量或并发数据结构)可能更合适。 此外,现代编程语言和框架通常提供更高级别的并发结构,抽象出低级别同步的复杂性。 + +在应用监视器模式之前,建议彻底分析应用程序的并发需求,并选择最适合您需求的同步方法,同时考虑性能、复杂性和可用语言功能等因素。 + +## 相关模式 + +* Active object +* Double-checked locking diff --git a/localization/zh/monitor/etc/monitor.urm.png b/localization/zh/monitor/etc/monitor.urm.png new file mode 100644 index 000000000000..c00e70e3fd12 Binary files /dev/null and b/localization/zh/monitor/etc/monitor.urm.png differ diff --git a/localization/zh/observer/README.md b/localization/zh/observer/README.md new file mode 100644 index 000000000000..90b2583b7d60 --- /dev/null +++ b/localization/zh/observer/README.md @@ -0,0 +1,155 @@ +--- +title: Observer +shortTitle: Observer +category: Behavioral +language: zh +tag: + - Gang Of Four + - Reactive +--- + +## Also known as +## 又被称为 + +家属,发布订阅模式 + +## 目的 + +定义一种一对多的对象依赖关系这样当一个对象改变状态时,所有依赖它的对象都将自动通知或更新。 + +## 解释 + +真实世界例子 + +> 在遥远的土地上生活着霍比特人和兽人的种族。他们都是户外生活的人所以他们密切关注天气的变化。可以说他们不断地关注着天气。 + +通俗的说 + +> 注册成为一个观察者以接收对象状态的改变。 + +维基百科说 + +> 观察者模式是这样的一种软件设计模式:它有一个被称为主题的对象,维护着一个所有依赖于它的依赖者清单,也就是观察者清单,当主题的状态发生改变时,主题通常会调用观察者的方法来自动通知观察者们。 + +**编程示例** + +让我们先来介绍天气观察者的接口以及我们的种族,兽人和霍比特人。 + +```java +public interface WeatherObserver { + + void update(WeatherType currentWeather); +} + +@Slf4j +public class Orcs implements WeatherObserver { + + @Override + public void update(WeatherType currentWeather) { + LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now"); + } +} + +@Slf4j +public class Hobbits implements WeatherObserver { + + @Override + public void update(WeatherType currentWeather) { + switch (currentWeather) { + LOGGER.info("The hobbits are facing " + currentWeather.getDescription() + " weather now"); + } +} +``` + +然后这里是不断变化的天气。 + +```java +@Slf4j +public class Weather { + + private WeatherType currentWeather; + private final List observers; + + public Weather() { + observers = new ArrayList<>(); + currentWeather = WeatherType.SUNNY; + } + + public void addObserver(WeatherObserver obs) { + observers.add(obs); + } + + public void removeObserver(WeatherObserver obs) { + observers.remove(obs); + } + + /** + * Makes time pass for weather. + */ + public void timePasses() { + var enumValues = WeatherType.values(); + currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; + LOGGER.info("The weather changed to {}.", currentWeather); + notifyObservers(); + } + + private void notifyObservers() { + for (var obs : observers) { + obs.update(currentWeather); + } + } +} +``` + +这是完整的示例。 + +```java + var weather = new Weather(); + weather.addObserver(new Orcs()); + weather.addObserver(new Hobbits()); + + weather.timePasses(); + // The weather changed to rainy. + // The orcs are facing rainy weather now + // The hobbits are facing rainy weather now + weather.timePasses(); + // The weather changed to windy. + // The orcs are facing windy weather now + // The hobbits are facing windy weather now + weather.timePasses(); + // The weather changed to cold. + // The orcs are facing cold weather now + // The hobbits are facing cold weather now + weather.timePasses(); + // The weather changed to sunny. + // The orcs are facing sunny weather now + // The hobbits are facing sunny weather now +``` + +## Class diagram +![alt text](./etc/observer.png "Observer") + +## 应用 +在下面任何一种情况下都可以使用观察者模式 + +* 当抽象具有两个方面时,一个方面依赖于另一个方面。将这些方面封装在单独的对象中,可以使你分别进行更改和重用 +* 当一个对象的改变的同时需要改变其他对象,同时你又不知道有多少对象需要改变时 +* 当一个对象可以通知其他对象而无需假设这些对象是谁时。换句话说,你不想让这些对象紧耦合。 + +## 典型用例 + +* 一个对象的改变导致其他对象的改变 + +## Java中的例子 + +* [java.util.Observer](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html) +* [java.util.EventListener](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html) +* [javax.servlet.http.HttpSessionBindingListener](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html) +* [RxJava](https://github.com/ReactiveX/RxJava) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Java Generics and Collections](https://www.amazon.com/gp/product/0596527756/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596527756&linkCode=as2&tag=javadesignpat-20&linkId=246e5e2c26fe1c3ada6a70b15afcb195) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/zh/observer/etc/observer.png b/localization/zh/observer/etc/observer.png new file mode 100644 index 000000000000..f2ab0edfeb21 Binary files /dev/null and b/localization/zh/observer/etc/observer.png differ diff --git a/localization/zh/private-class-data/README.md b/localization/zh/private-class-data/README.md new file mode 100644 index 000000000000..25fe2b880a1c --- /dev/null +++ b/localization/zh/private-class-data/README.md @@ -0,0 +1,127 @@ +--- +title: Private Class Data +shortTitle: Private Class Data +category: Idiom +language: zh +tag: + - Data access +--- + +## 目的 + +私有类数据设计模式试图通过限制属性的可见性来减少属性的暴露。 通过将它们封装在单个Data对象中,可以减少类属性的数量。 + +## 解释 + +真实世界例子 + +> 想象一下你在为家人做晚餐炖汤。你想阻止家庭成员在你烹饪时偷偷品尝菜品,否则后面可能东西不够吃了。 + +通俗的说 + +> 私有类数据模式通过将数据与使用它的方法分离到维护数据状态的类中,从而防止了对不可变数据的操纵。 + +维基百科说 + +> 私有类数据是计算机编程中的一种设计模式,用于封装类属性及其操作。 + +**程序示例** + +使用上面炖汤的例子。 首先我们有 `炖汤`类 ,它的属性没有被私有类数据保护,从而使炖菜的成分对类方法易变。 + +```java +public class Stew { + private static final Logger LOGGER = LoggerFactory.getLogger(Stew.class); + private int numPotatoes; + private int numCarrots; + private int numMeat; + private int numPeppers; + public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { + this.numPotatoes = numPotatoes; + this.numCarrots = numCarrots; + this.numMeat = numMeat; + this.numPeppers = numPeppers; + } + public void mix() { + LOGGER.info("Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers", + numPotatoes, numCarrots, numMeat, numPeppers); + } + public void taste() { + LOGGER.info("Tasting the stew"); + if (numPotatoes > 0) { + numPotatoes--; + } + if (numCarrots > 0) { + numCarrots--; + } + if (numMeat > 0) { + numMeat--; + } + if (numPeppers > 0) { + numPeppers--; + } + } +} +``` + +现在,我们有了` ImmutableStew`类,其中的数据受`StewData`类保护。 现在,其中的方法无法处理`ImmutableStew`类的数据。 + +```java +public class StewData { + private final int numPotatoes; + private final int numCarrots; + private final int numMeat; + private final int numPeppers; + public StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { + this.numPotatoes = numPotatoes; + this.numCarrots = numCarrots; + this.numMeat = numMeat; + this.numPeppers = numPeppers; + } + public int getNumPotatoes() { + return numPotatoes; + } + public int getNumCarrots() { + return numCarrots; + } + public int getNumMeat() { + return numMeat; + } + public int getNumPeppers() { + return numPeppers; + } +} +public class ImmutableStew { + private static final Logger LOGGER = LoggerFactory.getLogger(ImmutableStew.class); + private final StewData data; + public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { + data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers); + } + public void mix() { + LOGGER + .info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers", + data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers()); + } +} +``` + +让我们尝试创建每个类的实例并调用其方法: + +```java +var stew = new Stew(1, 2, 3, 4); +stew.mix(); // Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers +stew.taste(); // Tasting the stew +stew.mix(); // Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers +var immutableStew = new ImmutableStew(2, 4, 3, 6); +immutableStew.mix(); // Mixing the immutable stew we find: 2 potatoes, 4 carrots, 3 meat and 6 peppers +``` + +## 类图 + +![alt text](./etc/private-class-data.png "Private Class Data") + +## 适用性 + +在以下情况下使用私有类数据模式 + +* 您要阻止对类数据成员的写访问。 diff --git a/localization/zh/private-class-data/etc/private-class-data.png b/localization/zh/private-class-data/etc/private-class-data.png new file mode 100644 index 000000000000..65c343a5faf9 Binary files /dev/null and b/localization/zh/private-class-data/etc/private-class-data.png differ diff --git a/localization/zh/producer-consumer/README.md b/localization/zh/producer-consumer/README.md new file mode 100644 index 000000000000..cf7f894c4a95 --- /dev/null +++ b/localization/zh/producer-consumer/README.md @@ -0,0 +1,20 @@ +--- +title: Producer Consumer +shortTitle: Producer Consumer +category: Concurrency +language: zh +tag: + - Reactive +--- + +## 目的 +生产者消费者设计模式是一种经典的并发模式,通过将工作与执行工作任务分开来减少生产者与消费者之间的耦合。 + +## 类图 +![alt text](./etc/producer-consumer.png "Producer Consumer") + +## 适用性 +在以下情况下使用生产者消费者 + +* 通过将工作分成生产和消费两个工作进程来解耦系统 +* 解决生产工作和消费工作需要不同时间的问题 diff --git a/localization/zh/producer-consumer/etc/producer-consumer.png b/localization/zh/producer-consumer/etc/producer-consumer.png new file mode 100644 index 000000000000..e8bc573b388f Binary files /dev/null and b/localization/zh/producer-consumer/etc/producer-consumer.png differ diff --git a/localization/zh/proxy/README.md b/localization/zh/proxy/README.md new file mode 100644 index 000000000000..f0ed1d5b61dd --- /dev/null +++ b/localization/zh/proxy/README.md @@ -0,0 +1,160 @@ +--- +title: Proxy +shortTitle: Proxy +category: Structural +language: zh +tag: + - Gang Of Four + - Decoupling +--- + +## 又被称为 + +替代(代孕)模式 + +## 目的 + +为另一个对象提供代理或占位符以控制对其的访问。 + +## 解释 + +真实世界例子 + +> 想象有一个塔,当地的巫师去那里学习他们的法术。象牙塔只能够通过代理来进入以此来保证只有首先3个巫师才能进入。这里的代理就代表的塔的功能并添加访问控制。 + +通俗的说 + +> 使用代理模式,一个类代表另一个类的功能。 + +维基百科说 + +> 在最一般的形式上,代理是一个类,它充当与其他对象的接口。代理是客户端调用的包装器或代理对象,以访问后台的实际服务对象。代理本身可以简单地转发到真实对象,也可以提供其他逻辑。在代理中,可以提供额外的功能,例如在对实对象的操作占用大量资源时进行缓存,或者在对实对象的操作被调用之前检查前提条件。 + +**程序示例** + +使用上面的巫师塔为例。首先我们有**巫师塔**接口和**象牙塔**类 。 + +```java +public interface WizardTower { + + void enter(Wizard wizard); +} + +public class IvoryTower implements WizardTower { + + private static final Logger LOGGER = LoggerFactory.getLogger(IvoryTower.class); + + public void enter(Wizard wizard) { + LOGGER.info("{} enters the tower.", wizard); + } + +} +``` + +然后有个简单的巫师类。 + +```java +public class Wizard { + + private final String name; + + public Wizard(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} +``` + +然后我们有巫师塔代理类为巫师塔添加访问控制。 + +```java +public class WizardTowerProxy implements WizardTower { + + private static final Logger LOGGER = LoggerFactory.getLogger(WizardTowerProxy.class); + + private static final int NUM_WIZARDS_ALLOWED = 3; + + private int numWizards; + + private final WizardTower tower; + + public WizardTowerProxy(WizardTower tower) { + this.tower = tower; + } + + @Override + public void enter(Wizard wizard) { + if (numWizards < NUM_WIZARDS_ALLOWED) { + tower.enter(wizard); + numWizards++; + } else { + LOGGER.info("{} is not allowed to enter!", wizard); + } + } +} +``` + +然后这是进入塔的场景。 + +```java +var proxy = new WizardTowerProxy(new IvoryTower()); +proxy.enter(new Wizard("Red wizard")); +proxy.enter(new Wizard("White wizard")); +proxy.enter(new Wizard("Black wizard")); +proxy.enter(new Wizard("Green wizard")); +proxy.enter(new Wizard("Brown wizard")); +``` + +程序输出: + +``` +Red wizard enters the tower. +White wizard enters the tower. +Black wizard enters the tower. +Green wizard is not allowed to enter! +Brown wizard is not allowed to enter! +``` + +## 类图 + +![alt text](./etc/proxy.urm.png "Proxy pattern class diagram") + +## 适用性 + +代理适用于需要比简单指针更广泛或更复杂的对象引用的情况。这是代理模式适用的几种常见情况。 + +* 远程代理为不同地址空间中的对象提供了本地代表。 +* 虚拟代理根据需要创建昂贵的对象。 +* 保护代理控制对原始对象的访问。当对象有不同的接入权限时保护代理很有用。 + +## 典型用例 + +* 对象的访问控制 +* 懒加载 +* 实现日志记录 +* 简化网络连接 +* 对象的访问计数 + +## 教程 + +* [Controlling Access With Proxy Pattern](http://java-design-patterns.com/blog/controlling-access-with-proxy-pattern/) + +## 已知使用 + +* [java.lang.reflect.Proxy](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html) +* [Apache Commons Proxy](https://commons.apache.org/proper/commons-proxy/) +* Mocking frameworks [Mockito](https://site.mockito.org/), +[Powermock](https://powermock.github.io/), [EasyMock](https://easymock.org/) + +## 相关设计模式 + +* [Ambassador](https://java-design-patterns.com/patterns/ambassador/) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/localization/zh/proxy/etc/proxy.urm.png b/localization/zh/proxy/etc/proxy.urm.png new file mode 100644 index 000000000000..a0c94fc7c717 Binary files /dev/null and b/localization/zh/proxy/etc/proxy.urm.png differ diff --git a/localization/zh/servant/README.md b/localization/zh/servant/README.md new file mode 100644 index 000000000000..467785b619fd --- /dev/null +++ b/localization/zh/servant/README.md @@ -0,0 +1,231 @@ +--- +title: Servant +shortTitle: Servant +category: Behavioral +language: zh +tag: +- Decoupling +--- + +## 含义 +仆人类被用于向一组类提供一些行为,区别于在每个类定义行为-或者当我们无法排除 +公共父类中的这种行为,这些行为在仆人类被定义一次 + +## 解释 + +现实例子 + +> 国王、王后和其他宫廷皇室成员需要仆人为他们提供饮食、准备饮料等服务 + +简单地说 + +> 确保一个仆人对象为一组被服务的对象提供一些特定的服务 + +维基百科 + +> 在软件工程中,仆人模式定义了一个对象,用于向一组类提供某些功能,而无需在每个类中定义该功能。 仆人是一个类,其实例(甚至只是类)提供了处理所需服务的方法,而仆人为其(或与谁)做某事的对象被视为参数。 + +**编程示例** + +那些能够为其他宫廷皇室成员提供服务的仆人类 + +```java +/** + * Servant. + */ +public class Servant { + + public String name; + + /** + * Constructor. + */ + public Servant(String name) { + this.name = name; + } + + public void feed(Royalty r) { + r.getFed(); + } + + public void giveWine(Royalty r) { + r.getDrink(); + } + + public void giveCompliments(Royalty r) { + r.receiveCompliments(); + } + + /** + * Check if we will be hanged. + */ + public boolean checkIfYouWillBeHanged(List tableGuests) { + return tableGuests.stream().allMatch(Royalty::getMood); + } +} +``` + +皇家是一个接口,它被国王和女王类实现,以获取仆人的服务 + +```java +interface Royalty { + + void getFed(); + + void getDrink(); + + void changeMood(); + + void receiveCompliments(); + + boolean getMood(); +} +``` +国王类正在实现皇家接口 +```java +public class King implements Royalty { + + private boolean isDrunk; + private boolean isHungry = true; + private boolean isHappy; + private boolean complimentReceived; + + @Override + public void getFed() { + isHungry = false; + } + + @Override + public void getDrink() { + isDrunk = true; + } + + public void receiveCompliments() { + complimentReceived = true; + } + + @Override + public void changeMood() { + if (!isHungry && isDrunk) { + isHappy = true; + } + if (complimentReceived) { + isHappy = false; + } + } + + @Override + public boolean getMood() { + return isHappy; + } +} +``` +女王类正在实现皇家接口 +```java +public class Queen implements Royalty { + + private boolean isDrunk = true; + private boolean isHungry; + private boolean isHappy; + private boolean isFlirty = true; + private boolean complimentReceived; + + @Override + public void getFed() { + isHungry = false; + } + + @Override + public void getDrink() { + isDrunk = true; + } + + public void receiveCompliments() { + complimentReceived = true; + } + + @Override + public void changeMood() { + if (complimentReceived && isFlirty && isDrunk && !isHungry) { + isHappy = true; + } + } + + @Override + public boolean getMood() { + return isHappy; + } + + public void setFlirtiness(boolean f) { + this.isFlirty = f; + } + +} +``` + +然后,为了使用: + +```java +public class App { + + private static final Servant jenkins = new Servant("Jenkins"); + private static final Servant travis = new Servant("Travis"); + + /** + * Program entry point. + */ + public static void main(String[] args) { + scenario(jenkins, 1); + scenario(travis, 0); + } + + /** + * Can add a List with enum Actions for variable scenarios. + */ + public static void scenario(Servant servant, int compliment) { + var k = new King(); + var q = new Queen(); + + var guests = List.of(k, q); + + // feed + servant.feed(k); + servant.feed(q); + // serve drinks + servant.giveWine(k); + servant.giveWine(q); + // compliment + servant.giveCompliments(guests.get(compliment)); + + // outcome of the night + guests.forEach(Royalty::changeMood); + + // check your luck + if (servant.checkIfYouWillBeHanged(guests)) { + LOGGER.info("{} will live another day", servant.name); + } else { + LOGGER.info("Poor {}. His days are numbered", servant.name); + } + } +} +``` + +程序输出 + +``` +Jenkins will live another day +Poor Travis. His days are numbered +``` + + +## 类图 +![alt text](./etc/servant-pattern.png "Servant") + +## 适用场景 +在什么时候使用仆人模式 + +* 当我们希望某些对象执行一个公共操作并且不想将该操作定义为每个类中的方法时 + +## 鸣谢 + +* [Let's Modify the Objects-First Approach into Design-Patterns-First](http://edu.pecinovsky.cz/papers/2006_ITiCSE_Design_Patterns_First.pdf) diff --git a/localization/zh/servant/etc/servant-pattern.png b/localization/zh/servant/etc/servant-pattern.png new file mode 100644 index 000000000000..a8237775e332 Binary files /dev/null and b/localization/zh/servant/etc/servant-pattern.png differ diff --git a/localization/zh/sharding/README.md b/localization/zh/sharding/README.md new file mode 100644 index 000000000000..5db42563d5c0 --- /dev/null +++ b/localization/zh/sharding/README.md @@ -0,0 +1,29 @@ +--- +title: Sharding +shortTitle: Sharding +category: Behavioral +language: zh +tag: + - Performance + - Cloud distributed +--- + +## 含义 +分片模式是指将数据存储划分为水平分区或分片。每个分片都有相同的模式,但持有自己独特的数据子集。 + +一个分片本身就是一个数据存储(它可以包含许多不同类型的实体的数据),运行在作为存储节点的服务器上。 + +## 类图 +![alt text](./etc/sharding.urm.png "Sharding pattern class diagram") + +## 适用场景 +这种设计模式提供了一下的好处: + +- 你可以通过增加在额外的存储节点上,运行的更多分片来实现系统扩容。 +- 系统可以使用现成的廉价硬件,而不是为每个存储节点使用专门(或者昂贵)的服务器硬件。 +- 你可以通过平衡各分片之间的工作负载来减少竞争,以提高性能。 +- 在云环境中,分片可以在物理上靠近访问该节点数据的用户。 + +## 引用 + +* [Sharding pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/sharding) \ No newline at end of file diff --git a/localization/zh/sharding/etc/sharding.urm.png b/localization/zh/sharding/etc/sharding.urm.png new file mode 100644 index 000000000000..e7f412af3f01 Binary files /dev/null and b/localization/zh/sharding/etc/sharding.urm.png differ diff --git a/localization/zh/singleton/README.md b/localization/zh/singleton/README.md new file mode 100644 index 000000000000..4f9ddc2f54ae --- /dev/null +++ b/localization/zh/singleton/README.md @@ -0,0 +1,94 @@ +--- +title: Singleton +shortTitle: Singleton +category: Creational +language: zh +tag: + - Gang of Four +--- + +## 目的 + +确保一个类只有一个实例,并为其提供一个全局访问点。 + +## 解释 + +情境示例 + +> 巫师们之在一个象牙塔中学习他们的魔法,并且始终使用同一座附魔的象牙塔。 +> +> 这里的象牙塔是一个单例对象。 + +通俗来说 + +> 对于一个特定的类,确保只会创建一个对象。 + +维基百科说 + +> 在软件工程中,单例模式是一种软件设计模式,它将类的实例化限制为一个对象。当系统中只需要一个对象来协调各种操作时,这种模式非常有用。 + +**程序示例** + +详见 Joshua Bloch, Effective Java 2nd Edition p.18。 + +> 一个只有一个元素的枚举类型是实现单例模式的最佳方式。 + +```java +public enum EnumIvoryTower { + INSTANCE +} +``` + +使用: + +```java + var enumIvoryTower1 = EnumIvoryTower.INSTANCE; + var enumIvoryTower2 = EnumIvoryTower.INSTANCE; + LOGGER.info("enumIvoryTower1={}", enumIvoryTower1); + LOGGER.info("enumIvoryTower2={}", enumIvoryTower2); +``` + +控制台输出: + +``` +enumIvoryTower1=com.iluwatar.singleton.EnumIvoryTower@1221555852 +enumIvoryTower2=com.iluwatar.singleton.EnumIvoryTower@1221555852 +``` + +## 类图 + +![alt text](./etc/singleton.urm.png "Singleton pattern class diagram") + +## 适用性 + +当满足以下情况时,使用单例模式: + +* 确保一个类只有一个实例,并且客户端能够通过一个众所周知的访问点访问该实例。 +* 唯一的实例能够被子类扩展, 同时客户端不需要修改代码就能使用扩展后的实例。 + +一些典型的单例模式用例包括: + +* logging类 +* 管理与数据库的链接 +* 文件管理器(File manager) + +## 已知使用 + +* [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29) +* [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--) +* [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--) + + +## 影响 + +* 通过控制实例的创建和生命周期,违反了单一职责原则(SRP)。 +* 鼓励使用全局共享实例,组织了对象及其使用的资源被释放。 +* 代码变得耦合,给客户端的测试带来难度。 +* 单例模式的设计可能会使得子类化(继承)单例变得几乎不可能 + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/zh/singleton/etc/singleton.urm.png b/localization/zh/singleton/etc/singleton.urm.png new file mode 100644 index 000000000000..46584af40039 Binary files /dev/null and b/localization/zh/singleton/etc/singleton.urm.png differ diff --git a/localization/zh/state/README.md b/localization/zh/state/README.md new file mode 100644 index 000000000000..b717ba0e40fd --- /dev/null +++ b/localization/zh/state/README.md @@ -0,0 +1,154 @@ +--- +title: State +shortTitle: State +category: Behavioral +language: zh +tag: + - Gang of Four +--- + +## 又被称为 +对象状态 + +## 目的 +允许对象在内部状态改变时改变它的行为。对象看起来好像修改了它的类。 + +## 解释 +真实世界例子 + +> 当在长毛象的自然栖息地观察长毛象时,似乎它会根据情况来改变自己的行为。它开始可能很平静但是随着时间推移当它检测到威胁时它会对周围的环境感到愤怒和危险。 + +通俗的说 + +> 状态模式允许对象改变它的行为。 + +维基百科说 + +> 状态模式是一种允许对象在内部状态改变时改变它的行为的行为型设计模式。这种模式接近于有限状态机的概念。状态模式可以被理解为策略模式,它能够通过调用在模式接口中定义的方法来切换策略。 + +**编程示例** + +这里是模式接口和它具体的实现。 + +```java +public interface State { + + void onEnterState(); + + void observe(); +} + +public class PeacefulState implements State { + + private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class); + + private final Mammoth mammoth; + + public PeacefulState(Mammoth mammoth) { + this.mammoth = mammoth; + } + + @Override + public void observe() { + LOGGER.info("{} is calm and peaceful.", mammoth); + } + + @Override + public void onEnterState() { + LOGGER.info("{} calms down.", mammoth); + } +} + +public class AngryState implements State { + + private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class); + + private final Mammoth mammoth; + + public AngryState(Mammoth mammoth) { + this.mammoth = mammoth; + } + + @Override + public void observe() { + LOGGER.info("{} is furious!", mammoth); + } + + @Override + public void onEnterState() { + LOGGER.info("{} gets angry!", mammoth); + } +} +``` + +然后这里是包含状态的长毛象。 + +```java +public class Mammoth { + + private State state; + + public Mammoth() { + state = new PeacefulState(this); + } + + public void timePasses() { + if (state.getClass().equals(PeacefulState.class)) { + changeStateTo(new AngryState(this)); + } else { + changeStateTo(new PeacefulState(this)); + } + } + + private void changeStateTo(State newState) { + this.state = newState; + this.state.onEnterState(); + } + + @Override + public String toString() { + return "The mammoth"; + } + + public void observe() { + this.state.observe(); + } +} +``` + +然后这里是长毛象随着时间的推移后的整个行为示例。 + +```java + var mammoth = new Mammoth(); + mammoth.observe(); + mammoth.timePasses(); + mammoth.observe(); + mammoth.timePasses(); + mammoth.observe(); + + // The mammoth gets angry! + // The mammoth is furious! + // The mammoth calms down. + // The mammoth is calm and peaceful. +``` + +## 类图 +![alt text](./etc/state_urm.png "State") + +## 适用性 + +在以下两种情况下,请使用State模式 + +* 对象的行为取决于它的状态,并且它必须在运行时根据状态更改其行为。 +* 根据对象状态的不同,操作有大量的条件语句。此状态通常由一个或多个枚举常量表示。通常,几个操作将包含此相同的条件结构。状态模式把条件语句的分支分别放入单独的类中。这样一来,你就可以将对象的状态视为独立的对象,该对象可以独立于其他对象而变化。 + +## Java中例子 + +* [javax.faces.lifecycle.Lifecycle#execute()](http://docs.oracle.com/javaee/7/api/javax/faces/lifecycle/Lifecycle.html#execute-javax.faces.context.FacesContext-) controlled by [FacesServlet](http://docs.oracle.com/javaee/7/api/javax/faces/webapp/FacesServlet.html), the behavior is dependent on current phase of lifecycle. +* [JDiameter - Diameter State Machine](https://github.com/npathai/jdiameter/blob/master/core/jdiameter/api/src/main/java/org/jdiameter/api/app/State.java) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/zh/state/etc/state_urm.png b/localization/zh/state/etc/state_urm.png new file mode 100644 index 000000000000..c2cf9f562943 Binary files /dev/null and b/localization/zh/state/etc/state_urm.png differ diff --git a/localization/zh/step-builder/README.md b/localization/zh/step-builder/README.md new file mode 100644 index 000000000000..36dd0308a163 --- /dev/null +++ b/localization/zh/step-builder/README.md @@ -0,0 +1,25 @@ +--- +title: Step Builder +shortTitle: Step Builder +category: Creational +language: zn +tag: + - Instantiation +--- + +## 又被称为 +分步构建 + +## 目的 +这是构建者模式的一个扩展,完全指导用户创建对象,没有混淆的机会。 +用户体验会大大提升,因为他只能看到下一个步骤的方法,直到适当的时机才会出现构建对象的“build”方法。 + +## 类图 +![alt text](./etc/step-builder.png "Step Builder") + +## 应用 +使用分布构建模式当创建复杂对象的算法需要独立于组成对象的部分以及它们的组装方式,且构造过程必须允许对象有不同的表示形式,并且在此过程中顺序很重要时。 + +## 鸣谢 + +* [Marco Castigliego - Step Builder](http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html) diff --git a/localization/zh/step-builder/etc/step-builder.png b/localization/zh/step-builder/etc/step-builder.png new file mode 100644 index 000000000000..b7b623657c58 Binary files /dev/null and b/localization/zh/step-builder/etc/step-builder.png differ diff --git a/localization/zh/strategy/README.md b/localization/zh/strategy/README.md new file mode 100644 index 000000000000..8e6a1f3930df --- /dev/null +++ b/localization/zh/strategy/README.md @@ -0,0 +1,132 @@ +--- +title: Strategy +shortTitle: Strategy +category: Behavioral +language: zh +tag: + - Gang of Four +--- + +## 又被称为 +政策(方针)模式 + +## 目的 + +定义一个家族算法,并封装好其中每一个,使它们可以互相替换。策略模式使算法的变化独立于使用它的客户。 + +## 解释 + +现实世界例子 + +> 屠龙是一项危险的职业。有经验将会使它变得简单。经验丰富的屠龙者对不同类型的龙有不同的战斗策略。 + +直白点说 + +> 策略模式允许在运行时选择最匹配的算法。 + +维基百科上说 + +> 在程序编程领域,策略模式(又叫政策模式)是一种启用在运行时选择算法的行为型软件设计模式。 + +**编程实例** + +让我们先介绍屠龙的策略模式接口和它的实现。 + +```java +@FunctionalInterface +public interface DragonSlayingStrategy { + + void execute(); +} + +@Slf4j +public class MeleeStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("With your Excalibur you sever the dragon's head!"); + } +} + +@Slf4j +public class ProjectileStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!"); + } +} + +@Slf4j +public class SpellStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"); + } +} +``` + +现在有一个强力的屠龙者要基于上面的组件来选择他的战斗策略。 + +```java +public class DragonSlayer { + + private DragonSlayingStrategy strategy; + + public DragonSlayer(DragonSlayingStrategy strategy) { + this.strategy = strategy; + } + + public void changeStrategy(DragonSlayingStrategy strategy) { + this.strategy = strategy; + } + + public void goToBattle() { + strategy.execute(); + } +} +``` + +最后是屠龙者的行动。 + +```java + LOGGER.info("Green dragon spotted ahead!"); + var dragonSlayer = new DragonSlayer(new MeleeStrategy()); + dragonSlayer.goToBattle(); + LOGGER.info("Red dragon emerges."); + dragonSlayer.changeStrategy(new ProjectileStrategy()); + dragonSlayer.goToBattle(); + LOGGER.info("Black dragon lands before you."); + dragonSlayer.changeStrategy(new SpellStrategy()); + dragonSlayer.goToBattle(); + + // Green dragon spotted ahead! + // With your Excalibur you sever the dragon's head! + // Red dragon emerges. + // You shoot the dragon with the magical crossbow and it falls dead on the ground! + // Black dragon lands before you. + // You cast the spell of disintegration and the dragon vaporizes in a pile of dust! +``` + +## 类图 +![alt text](./etc/strategy_urm.png "Strategy") + +## 应用 +使用策略模式当 + +* 许多相关的类只是行为不同。策略模式提供了一种为一种类配置多种行为的能力。 +* 你需要一种算法的不同变体。比如,你可能定义反应不用时间空间权衡的算法。当这些算法的变体使用类的层次结构来实现时就可以使用策略模式。 +* 一个算法使用的数据客户不应该对其知晓。使用策略模式来避免暴露复杂的,特定于算法的数据结构。 +* 一个类定义了许多行为,这些行为在其操作中展现为多个条件语句。移动相关的条件分支到它们分别的策略类中来代替这些条件语句。 + +## 教学 + +* [Strategy Pattern Tutorial](https://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorial) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/zh/strategy/etc/strategy_urm.png b/localization/zh/strategy/etc/strategy_urm.png new file mode 100644 index 000000000000..67d19acae62d Binary files /dev/null and b/localization/zh/strategy/etc/strategy_urm.png differ diff --git a/localization/zh/table-module/README.md b/localization/zh/table-module/README.md new file mode 100644 index 000000000000..9a9dfed1eb7c --- /dev/null +++ b/localization/zh/table-module/README.md @@ -0,0 +1,136 @@ +--- +title: Table Module +shortTitle: Table Module +category: Structural +language: zh +tag: + - Data access +--- + +## 又被称为 +表模块 + +## Intent +表模块模式将域逻辑按数据库中的每个表组织为一个类,并且一个类的单个实例包含将对数据执行的各种过程。 + +## Explanation + +现实世界例子 + +> 当处理一个用户系统时,我们需要在用户表上进行一些操作。在这种情况下,我们可以使用表模块模式。我们可以创建一个名为 UserTableModule 的类,并初始化该类的一个实例,来处理用户表中所有行的业务逻辑。 + +直白点说 + +> 一个单独的实例,处理数据库表或视图中所有行的业务逻辑。 + +**编程实例** + +在用户系统的示例中,我们需要处理用户登录和用户注册的域逻辑。我们可以使用表模块模式,并创建UserTableModule类的一个实例来处理用户表中所有行的业务逻辑。 + +以下是基本的User实体。 + +```java +@Setter +@Getter +@ToString +@EqualsAndHashCode +@AllArgsConstructor +public class User { + private int id; + private String username; + private String password; +} +``` + +下面的是 `UserTableModule` 类. + +```java +public class UserTableModule { + private final DataSource dataSource; + private Connection connection = null; + private ResultSet resultSet = null; + private PreparedStatement preparedStatement = null; + + public UserTableModule(final DataSource userDataSource) { + this.dataSource = userDataSource; + } + + /** + * Login using username and password. + * + * @param username the username of a user + * @param password the password of a user + * @return the execution result of the method + * @throws SQLException if any error + */ + public int login(final String username, final String password) throws SQLException { + // Method implementation. + + } + + /** + * Register a new user. + * + * @param user a user instance + * @return the execution result of the method + * @throws SQLException if any error + */ + public int registerUser(final User user) throws SQLException { + // Method implementation. + } +} +``` + +在App类中,我们使用UserTableModule的一个实例来处理用户登录和注册。 + +```java +// Create data source and create the user table. +final var dataSource = createDataSource(); +createSchema(dataSource); +userTableModule = new UserTableModule(dataSource); + +//Initialize two users. +var user1 = new User(1, "123456", "123456"); +var user2 = new User(2, "test", "password"); + +//Login and register using the instance of userTableModule. +userTableModule.registerUser(user1); +userTableModule.login(user1.getUsername(), user1.getPassword()); +userTableModule.login(user2.getUsername(), user2.getPassword()); +userTableModule.registerUser(user2); +userTableModule.login(user2.getUsername(), user2.getPassword()); + +deleteSchema(dataSource); +``` + +程序输出: + +```java +12:22:13.095 [main] INFO com.iluwatar.tablemodule.UserTableModule - Register successfully! +12:22:13.117 [main] INFO com.iluwatar.tablemodule.UserTableModule - Login successfully! +12:22:13.128 [main] INFO com.iluwatar.tablemodule.UserTableModule - Fail to login! +12:22:13.136 [main] INFO com.iluwatar.tablemodule.UserTableModule - Register successfully! +12:22:13.144 [main] INFO com.iluwatar.tablemodule.UserTableModule - Login successfully! +``` + +## 类图 + +![](etc/table-module.urm.png "table module") + +## 应用 +使用表模块模式当: + +- 域逻辑简单且数据呈表格形式。 +- 应用程序仅使用少量共享的常见的面向表格的数据结构。 + +## 教学 + +- [Transaction Script](https://java-design-patterns.com/patterns/transaction-script/) + +- [Domain Model](https://java-design-patterns.com/patterns/domain-model/) + +## 鸣谢 + +* [Table Module Pattern](http://wiki3.cosc.canterbury.ac.nz/index.php/Table_module_pattern) +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321127420&linkId=18acc13ba60d66690009505577c45c04) +* [Architecture patterns: domain model and friends](https://inviqa.com/blog/architecture-patterns-domain-model-and-friends) \ No newline at end of file diff --git a/localization/zh/table-module/etc/table-module.urm.png b/localization/zh/table-module/etc/table-module.urm.png new file mode 100644 index 000000000000..9c4bc0b189db Binary files /dev/null and b/localization/zh/table-module/etc/table-module.urm.png differ diff --git a/localization/zh/template-method/README.md b/localization/zh/template-method/README.md new file mode 100644 index 000000000000..57b4f0a9de2a --- /dev/null +++ b/localization/zh/template-method/README.md @@ -0,0 +1,144 @@ +--- +title: Template method +shortTitle: Template method +category: Behavioral +language: zh +tag: + - Gang of Four +--- + +## 目的 +在一个操作中定义算法的骨架,将某些步骤推迟到子类。模板方法允许子类重新定义算法的某些步骤,而无需更改算法的结构。 + +## 解释 +真实世界例子 + +> 偷东西的一般步骤是相同的。 首先,选择目标,然后以某种方式使其迷惑,最后,你偷走了该物品。然而这些步骤有很多实现方式。 + +通俗的说 + +> 模板方法模式在父类中列出一般的步骤然后让具体的子类定义实现细节。 + +维基百科说 + +> 在面向对象的编程中,模板方法是Gamma等人确定的行为设计模式之一。在《设计模式》一书中。模板方法是父类中一个方法,通常是一个抽象父类,根据许多高级步骤定义了操作的骨架。这些步骤本身由与模板方法在同一类中的其他帮助程序方法实现。 + +**编程示例** + +让我们首先介绍模板方法类及其具体实现。 + +```java +public abstract class StealingMethod { + + private static final Logger LOGGER = LoggerFactory.getLogger(StealingMethod.class); + + protected abstract String pickTarget(); + + protected abstract void confuseTarget(String target); + + protected abstract void stealTheItem(String target); + + public void steal() { + var target = pickTarget(); + LOGGER.info("The target has been chosen as {}.", target); + confuseTarget(target); + stealTheItem(target); + } +} + +public class SubtleMethod extends StealingMethod { + + private static final Logger LOGGER = LoggerFactory.getLogger(SubtleMethod.class); + + @Override + protected String pickTarget() { + return "shop keeper"; + } + + @Override + protected void confuseTarget(String target) { + LOGGER.info("Approach the {} with tears running and hug him!", target); + } + + @Override + protected void stealTheItem(String target) { + LOGGER.info("While in close contact grab the {}'s wallet.", target); + } +} + +public class HitAndRunMethod extends StealingMethod { + + private static final Logger LOGGER = LoggerFactory.getLogger(HitAndRunMethod.class); + + @Override + protected String pickTarget() { + return "old goblin woman"; + } + + @Override + protected void confuseTarget(String target) { + LOGGER.info("Approach the {} from behind.", target); + } + + @Override + protected void stealTheItem(String target) { + LOGGER.info("Grab the handbag and run away fast!"); + } +} +``` + +这是包含模板方法的半身贼类。 + +```java +public class HalflingThief { + + private StealingMethod method; + + public HalflingThief(StealingMethod method) { + this.method = method; + } + + public void steal() { + method.steal(); + } + + public void changeMethod(StealingMethod method) { + this.method = method; + } +} +``` +最后,我们展示半身人贼如何利用不同的偷窃方法。 + +```java + var thief = new HalflingThief(new HitAndRunMethod()); + thief.steal(); + thief.changeMethod(new SubtleMethod()); + thief.steal(); +``` + +## 类图 +![alt text](./etc/template_method_urm.png "Template Method") + +## 适用性 + +使用模板方法模式可以 + +* 一次性实现一个算法中不变的部分并将其留给子类来实现可能变化的行为。 +* 子类之间的共同行为应分解并集中在一个共同类中,以避免代码重复。如Opdyke和Johnson所描述的,这是“重构概括”的一个很好的例子。你首先要确定现有代码中的差异,然后将差异拆分为新的操作。最后,将不同的代码替换为调用这些新操作之一的模板方法。 +* 控制子类扩展。您可以定义一个模板方法,该方法在特定点调用“ 钩子”操作,从而仅允许在这些点进行扩展 + +## 教程 + +* [Template-method Pattern Tutorial](https://www.journaldev.com/1763/template-method-design-pattern-in-java) + +## Java例子 + +* [javax.servlet.GenericServlet.init](https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/GenericServlet.html#init--): +Method `GenericServlet.init(ServletConfig config)` calls the parameterless method `GenericServlet.init()` which is intended to be overridden in subclasses. +Method `GenericServlet.init(ServletConfig config)` is the template method in this example. + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/zh/template-method/etc/template_method_urm.png b/localization/zh/template-method/etc/template_method_urm.png new file mode 100644 index 000000000000..b7babccff96d Binary files /dev/null and b/localization/zh/template-method/etc/template_method_urm.png differ diff --git a/localization/zh/trampoline/README.md b/localization/zh/trampoline/README.md new file mode 100644 index 000000000000..438d75905170 --- /dev/null +++ b/localization/zh/trampoline/README.md @@ -0,0 +1,136 @@ +--- +title: Trampoline +shortTitle: Trampoline +category: Behavioral +language: zh +tag: +- Performance +--- + +## 目的 + +蹦床模式是用于在 Java 中递归地实现算法,而不会破坏堆栈,并且可以交错地执行函数,而无需将它们编码在一起。 + +## 解释 + +递归是一种常用的技术,用于以分而治之的方式解决算法问题。例如,计算斐波那契累加和与阶乘。在这类问题中,递归比循环更简单直接。此外,递归可能需要更少的代 +码并且看起来更简明。有一种说法是,每个递归问题都可以使用循环来解决,但代价是编写更难以理解的代码。然而,递归型解决方案有一个很大的警告。对于每个 +递归调用,通常需要存储一个中间值,并且可用的栈内存有限。栈内存不足会导致栈溢出错误并停止程序执行。蹦床模式是一种允许在 Java 中定义递归算法而无需破坏 +堆栈的技巧。 + +现实世界例子 + +> 使用蹦床模式进行递归斐波那契计算,不存在堆栈溢出问题。 + +通俗地说 + +> 蹦床模式允许递归而不会耗尽栈内存。 + +维基百科上说 + +> 在 Java 中,蹦床是指使用反射来避免使用内部类,例如在事件侦听器中。反射调用的整理操作时间换成了内部类的整理操作空间。 Java 中的蹦床通常涉及创建 GenericListener 以将事件传递到外部类。 + +**编程实例** + +这是 Java 中的蹦床实现。 + +当在返回的蹦床上调用 `get` 时,只要返回的具体实例是蹦床,内部就会在返回的蹦床上迭代调用跳转,并在返回的实例完成后停止。 + +```java +public interface Trampoline { + + T get(); + + default Trampoline jump() { + return this; + } + + default T result() { + return get(); + } + + default boolean complete() { + return true; + } + + static Trampoline done(final T result) { + return () -> result; + } + + static Trampoline more(final Trampoline> trampoline) { + return new Trampoline() { + @Override + public boolean complete() { + return false; + } + + @Override + public Trampoline jump() { + return trampoline.result(); + } + + @Override + public T get() { + return trampoline(this); + } + + T trampoline(final Trampoline trampoline) { + return Stream.iterate(trampoline, Trampoline::jump) + .filter(Trampoline::complete) + .findFirst() + .map(Trampoline::result) + .orElseThrow(); + } + }; + } +} +``` + +使用蹦床获取斐波那契值。 + +```java +public static void main(String[] args) { + LOGGER.info("Start calculating war casualties"); + var result = loop(10, 1).result(); + LOGGER.info("The number of orcs perished in the war: {}", result); +} + +public static Trampoline loop(int times, int prod) { + if (times == 0) { + return Trampoline.done(prod); + } else { + return Trampoline.more(() -> loop(times - 1, prod * times)); + } +} +``` + +程序输出: + +```java +19:22:24.462 [main] INFO com.iluwatar.trampoline.TrampolineApp - Start calculating war casualties +19:22:24.472 [main] INFO com.iluwatar.trampoline.TrampolineApp - The number of orcs perished in the war: 3628800 +``` + +## 类图 + +![alt text](./etc/trampoline_urm.png "Trampoline pattern class diagram") + +## 适用场景 + +使用蹦床模式时 +* 用于实现尾递归函数。该模式允许切换无堆栈操作。 +* 用于在同一线程上交错执行两个或多个函数。 + +## 现实案例 + +* [cyclops-react](https://github.com/aol/cyclops-react) + +## 鸣谢 + +* [Trampolining: a practical guide for awesome Java Developers](https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076) +* [Trampoline in java ](http://mindprod.com/jgloss/trampoline.html) +* [Laziness, trampolines, monoids and other functional amenities: this is not your father's Java](https://www.slideshare.net/mariofusco/lazine) +* [Trampoline implementation](https://github.com/bodar/totallylazy/blob/master/src/com/googlecode/totallylazy/Trampoline.java) +* [What is a trampoline function?](https://stackoverflow.com/questions/189725/what-is-a-trampoline-function) +* [Modern Java in Action: Lambdas, streams, functional and reactive programming](https://www.amazon.com/gp/product/1617293563/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617293563&linkId=ad53ae6f9f7c0982e759c3527bd2595c) +* [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://www.amazon.com/gp/product/1617291994/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617291994&linkId=e3e5665b0732c59c9d884896ffe54f4f) diff --git a/localization/zh/trampoline/etc/trampoline_urm.png b/localization/zh/trampoline/etc/trampoline_urm.png new file mode 100644 index 000000000000..f2e9c7439a32 Binary files /dev/null and b/localization/zh/trampoline/etc/trampoline_urm.png differ diff --git a/localization/zh/unit-of-work/README.md b/localization/zh/unit-of-work/README.md new file mode 100644 index 000000000000..5623b42ed1f4 --- /dev/null +++ b/localization/zh/unit-of-work/README.md @@ -0,0 +1,204 @@ +--- +title: Unit Of Work +shortTitle: Unit Of Work +category: Architectural +language: zn +tag: + - Data access + - Performance +--- + +## 又被称为 +工作单元 + +## 目的 + +当一个业务事务完成时,所有的更新都作为一个大的工作单元一次性发送,以最小化数据库的往返次数进行持久化。 + +## 解释 + +现实世界例子 + +> 武器商人拥有一个包含武器信息的数据库。 +> 全城的商贩们都在不断地更新这些信息,这导致数据库服务器的负载很高。 +> 为了使负载更易于管理,我们应用了工作单元模式,将许多小的更新批量发送。 + +用直白的话来说 + +> 工作单元将许多小的数据库更新合并成一个批次。 +> 以优化往返次数。 + +[MartinFowler.com](https://martinfowler.com/eaaCatalog/unitOfWork.html) 中说 + +> 维护一个受业务事务影响的对象列表。 +> 并协调写出更改和解决并发问题。 + +**编程样例** + +以下是要持久化到数据库中的 `Weapon` 的实体。 + +```java +@Getter +@RequiredArgsConstructor +public class Weapon { + private final Integer id; + private final String name; +} +``` + +实现的核心是 `ArmsDealer` 实现了工作单元模式。 +它维护了一个需要完成的数据库操作映射 (`context`) 当调用 `commit` 时 +它会一次性批量应用这些操作。 + +```java +public interface IUnitOfWork { + + String INSERT = "INSERT"; + String DELETE = "DELETE"; + String MODIFY = "MODIFY"; + + void registerNew(T entity); + + void registerModified(T entity); + + void registerDeleted(T entity); + + void commit(); +} + +@Slf4j +@RequiredArgsConstructor +public class ArmsDealer implements IUnitOfWork { + + private final Map> context; + private final WeaponDatabase weaponDatabase; + + @Override + public void registerNew(Weapon weapon) { + LOGGER.info("Registering {} for insert in context.", weapon.getName()); + register(weapon, UnitActions.INSERT.getActionValue()); + } + + @Override + public void registerModified(Weapon weapon) { + LOGGER.info("Registering {} for modify in context.", weapon.getName()); + register(weapon, UnitActions.MODIFY.getActionValue()); + + } + + @Override + public void registerDeleted(Weapon weapon) { + LOGGER.info("Registering {} for delete in context.", weapon.getName()); + register(weapon, UnitActions.DELETE.getActionValue()); + } + + private void register(Weapon weapon, String operation) { + var weaponsToOperate = context.get(operation); + if (weaponsToOperate == null) { + weaponsToOperate = new ArrayList<>(); + } + weaponsToOperate.add(weapon); + context.put(operation, weaponsToOperate); + } + + /** + * All UnitOfWork operations are batched and executed together on commit only. + */ + @Override + public void commit() { + if (context == null || context.size() == 0) { + return; + } + LOGGER.info("Commit started"); + if (context.containsKey(UnitActions.INSERT.getActionValue())) { + commitInsert(); + } + + if (context.containsKey(UnitActions.MODIFY.getActionValue())) { + commitModify(); + } + if (context.containsKey(UnitActions.DELETE.getActionValue())) { + commitDelete(); + } + LOGGER.info("Commit finished."); + } + + private void commitInsert() { + var weaponsToBeInserted = context.get(UnitActions.INSERT.getActionValue()); + for (var weapon : weaponsToBeInserted) { + LOGGER.info("Inserting a new weapon {} to sales rack.", weapon.getName()); + weaponDatabase.insert(weapon); + } + } + + private void commitModify() { + var modifiedWeapons = context.get(UnitActions.MODIFY.getActionValue()); + for (var weapon : modifiedWeapons) { + LOGGER.info("Scheduling {} for modification work.", weapon.getName()); + weaponDatabase.modify(weapon); + } + } + + private void commitDelete() { + var deletedWeapons = context.get(UnitActions.DELETE.getActionValue()); + for (var weapon : deletedWeapons) { + LOGGER.info("Scrapping {}.", weapon.getName()); + weaponDatabase.delete(weapon); + } + } +} +``` + +以下描述了整个应用是如何组装起来的。 + +```java +// create some weapons +var enchantedHammer = new Weapon(1, "enchanted hammer"); +var brokenGreatSword = new Weapon(2, "broken great sword"); +var silverTrident = new Weapon(3, "silver trident"); + +// create repository +var weaponRepository = new ArmsDealer(new HashMap>(), new WeaponDatabase()); + +// perform operations on the weapons +weaponRepository.registerNew(enchantedHammer); +weaponRepository.registerModified(silverTrident); +weaponRepository.registerDeleted(brokenGreatSword); +weaponRepository.commit(); +``` + +以下是控制台输出。 + +``` +21:39:21.984 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering enchanted hammer for insert in context. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering silver trident for modify in context. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering broken great sword for delete in context. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Commit started +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Inserting a new weapon enchanted hammer to sales rack. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Scheduling silver trident for modification work. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Scrapping broken great sword. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Commit finished. +``` + +## 类图 + +![alt text](./etc/unit-of-work.urm.png "unit-of-work") + +## 应用 + +在以下情况时使用单元模式 + +* 为了优化数据库事务所需的时间。 +* 作为工作单元将更改发送到数据库,确保事务的原子性。 +* 为了减少数据库调用的次数。 + +## 教程 + +* [Repository and Unit of Work Pattern](https://www.programmingwithwolfgang.com/repository-and-unit-of-work-pattern/) +* [Unit of Work - a Design Pattern](https://mono.software/2017/01/13/unit-of-work-a-design-pattern/) + +## 鸣谢 + +* [Design Pattern - Unit Of Work Pattern](https://www.codeproject.com/Articles/581487/Unit-of-Work-Design-Pattern) +* [Unit Of Work](https://martinfowler.com/eaaCatalog/unitOfWork.html) +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321127420&linkCode=as2&tag=javadesignpat-20&linkId=d9f7d37b032ca6e96253562d075fcc4a) diff --git a/localization/zh/unit-of-work/etc/unit-of-work.urm.png b/localization/zh/unit-of-work/etc/unit-of-work.urm.png new file mode 100644 index 000000000000..bb192af54477 Binary files /dev/null and b/localization/zh/unit-of-work/etc/unit-of-work.urm.png differ diff --git a/localization/zh/update-method/README.md b/localization/zh/update-method/README.md new file mode 100644 index 000000000000..01bb51587876 --- /dev/null +++ b/localization/zh/update-method/README.md @@ -0,0 +1,37 @@ +--- +title: Update Method +shortTitle: Update Method +category: Behavioral +language: zn +tag: + - Game programming +--- + +## 又被称为 +更新方法 + +## 目的 +更新方法模式通过告诉每个对象一次处理一个行为帧来模拟一组独立的对象。 + +## 解释 +游戏世界维护了一个对象的集合。每个对象都实现了一个更新方法,用来模拟该对象行为的一帧。在每一帧中,游戏会更新集合中的每一个对象。 + +要了解更多关于游戏循环是如何运行的,以及何时调用更新方法,请参考“游戏循环模式”。 + +## 类图 +![alt text](./etc/update-method.urm.png "Update Method pattern class diagram") + +## 应用 +如果说游戏循环模式是自切面包以来最好的东西,那么更新方法模式就是它的黄油。有很多玩家与动态实体互动的游戏都以某种形式使用这个模式。如果游戏里有宇航兵、龙、火星人、幽灵或运动员,那么它很可能使用了这种模式。 + +然而,如果游戏更为抽象,且移动的部分不像是生动的角色,而更像是棋盘上的棋子,那么这种模式往往并不合适。在像国际象棋这样的游戏中,你不需要同时模拟所有的棋子,也可能不需要告诉每一个兵卒在每一帧都更新自己。 + +当以下情况发生时,更新方法工作得很好: + +- 你的游戏中有许多对象或系统需要同时运行。 +- 每个对象的行为大部分都独立于其他对象。 +- 这些对象需要随时间进行模拟。 + +## 鸣谢 + +* [Game Programming Patterns - Update Method](http://gameprogrammingpatterns.com/update-method.html) diff --git a/localization/zh/update-method/etc/update-method.urm.png b/localization/zh/update-method/etc/update-method.urm.png new file mode 100644 index 000000000000..ddc47b5fe145 Binary files /dev/null and b/localization/zh/update-method/etc/update-method.urm.png differ diff --git a/localization/zh/value-object/README.md b/localization/zh/value-object/README.md new file mode 100644 index 000000000000..7ce457e690dd --- /dev/null +++ b/localization/zh/value-object/README.md @@ -0,0 +1,97 @@ +--- +title: Value Object +shortTitle: Value Object +category: Creational +language: zn +tag: + - Instantiation +--- + +## 又被称为 +值对象 + +## 目的 + +提供的对象应遵循值语义而不是引用语义。这意味着两个值对象的相等性不是基于它们的身份。只要两个值对象的值相同,即使它们不是同一个对象,它们也被认为是相等的。 + +## 解释 + +现实世界例子 + +> 在一个角色扮演游戏中,有一个用于英雄属性统计的类。 +> 这些统计属性包括力量、智慧和运气等特征。 +> 当所有的属性都相同时,不同英雄的统计数据应被认为是相等的。 + +用直白的话来说 + +> 当值对象的属性有相同的值时,它们是相等的。 + +维基百科中说 + +> 在计算机科学中,值对象是一个代表简单实体的小对象。 +> 其相等性不是基于身份的:即当两个值对象有相同的值的时候。 +> 它们是相等的,而不必要是同一个对象。 + +**编程样例** + +这里是作为值对象的 `HeroStat` 类。 请注意使用了 +[Lombok's `@Value`](https://projectlombok.org/features/Value) 注解。 + +```java +@Value(staticConstructor = "valueOf") +class HeroStat { + + int strength; + int intelligence; + int luck; +} +``` + +这个示例创建了三个不同的 `HeroStat`s 并比较了它们的相等性。 + +```java +var statA = HeroStat.valueOf(10, 5, 0); +var statB = HeroStat.valueOf(10, 5, 0); +var statC = HeroStat.valueOf(5, 1, 8); + +LOGGER.info(statA.toString()); +LOGGER.info(statB.toString()); +LOGGER.info(statC.toString()); + +LOGGER.info("Is statA and statB equal : {}", statA.equals(statB)); +LOGGER.info("Is statA and statC equal : {}", statA.equals(statC)); +``` + +以下是控制台的输出。 + +``` +20:11:12.199 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=10, intelligence=5, luck=0) +20:11:12.202 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=10, intelligence=5, luck=0) +20:11:12.202 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=5, intelligence=1, luck=8) +20:11:12.202 [main] INFO com.iluwatar.value.object.App - Is statA and statB equal : true +20:11:12.203 [main] INFO com.iluwatar.value.object.App - Is statA and statC equal : false +``` + +## 类图 + +![alt text](./etc/value-object.png "Value Object") + +## 应用 + +当满足以下情况时,使用值对象: + +* 对象的相等性需要基于对象的值 + +## 现实世界的案例 + +* [java.util.Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html) +* [java.time.LocalDate](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) +* [joda-time, money, beans](http://www.joda.org/) + +## 鸣谢 + +* [Patterns of Enterprise Application Architecture](http://www.martinfowler.com/books/eaa.html) +* [ValueObject](https://martinfowler.com/bliki/ValueObject.html) +* [VALJOs - Value Java Objects : Stephen Colebourne's blog](http://blog.joda.org/2014/03/valjos-value-java-objects.html) +* [Value Object : Wikipedia](https://en.wikipedia.org/wiki/Value_object) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/localization/zh/value-object/etc/value-object.png b/localization/zh/value-object/etc/value-object.png new file mode 100644 index 000000000000..69a244c80691 Binary files /dev/null and b/localization/zh/value-object/etc/value-object.png differ diff --git a/localization/zh/version-number/README.md b/localization/zh/version-number/README.md new file mode 100644 index 000000000000..aa0966556fe8 --- /dev/null +++ b/localization/zh/version-number/README.md @@ -0,0 +1,158 @@ +--- +title: Version Number +shortTitle: Version Number +category: Concurrency +language: zh +tag: + - Data access + - Microservices +--- + +## 名字 / 分类 + +版本号 + +## 或称 + +实体版本控制,乐观锁。 + +## 目的 + +解决多个客户端尝试同时更新同一实体时的并发冲突。 + +## 解释 + +现实世界的例子 + +> 爱丽丝(Alice)和鲍勃(Bob)正在管理书,该书存储在数据库中。 我们的英雄们正在同时进行更改,我们需要某种机制来防止他们相互覆盖。 + +通俗地说 + +> 版本号模式可防止对同一实体进行并发更新。 + +维基百科说 + +> 乐观并发控制假设多个事务可以频繁完成而不会互相干扰。 在运行时,事务使用数据资源而不获取这些资源的锁。 在提交之前,每个事务都将验证没有其他事务修改了已读取的数据。如果检查发现有冲突的修改,则提交的事务将回滚并可以重新启动。 + +**程序示例** + +我们有`Book` 已版本化的实体,它有一个复制构造函数。 + +```java +public class Book { + private long id; + private String title = ""; + private String author = ""; + + private long version = 0; // version number + + public Book(Book book) { + this.id = book.id; + this.title = book.title; + this.author = book.author; + this.version = book.version; + } + + // getters and setters are omitted here +} +``` + +我们还有一个 `BookRepository`, 它实现了并发控制。 + +```java +public class BookRepository { + private final Map collection = new HashMap<>(); + + public void update(Book book) throws BookNotFoundException, VersionMismatchException { + if (!collection.containsKey(book.getId())) { + throw new BookNotFoundException("Not found book with id: " + book.getId()); + } + + var latestBook = collection.get(book.getId()); + if (book.getVersion() != latestBook.getVersion()) { + throw new VersionMismatchException( + "Tried to update stale version " + book.getVersion() + + " while actual version is " + latestBook.getVersion() + ); + } + + // update version, including client representation - modify by reference here + book.setVersion(book.getVersion() + 1); + + // save book copy to repository + collection.put(book.getId(), new Book(book)); + } + + public Book get(long bookId) throws BookNotFoundException { + if (!collection.containsKey(bookId)) { + throw new BookNotFoundException("Not found book with id: " + bookId); + } + + // return copy of the book + return new Book(collection.get(bookId)); + } +} +``` + +这是实践中的并发控制: + +```java +var bookId = 1; +// Alice and Bob took the book concurrently +final var aliceBook = bookRepository.get(bookId); +final var bobBook = bookRepository.get(bookId); + +aliceBook.setTitle("Kama Sutra"); // Alice has updated book title +bookRepository.update(aliceBook); // and successfully saved book in database +LOGGER.info("Alice updates the book with new version {}", aliceBook.getVersion()); + +// now Bob has the stale version of the book with empty title and version = 0 +// while actual book in database has filled title and version = 1 +bobBook.setAuthor("Vatsyayana Mallanaga"); // Bob updates the author +try { + LOGGER.info("Bob tries to update the book with his version {}", bobBook.getVersion()); + bookRepository.update(bobBook); // Bob tries to save his book to database +} catch (VersionMismatchException e) { + // Bob update fails, and book in repository remained untouchable + LOGGER.info("Exception: {}", e.getMessage()); + // Now Bob should reread actual book from repository, do his changes again and save again +} +``` + +程序输出: + +```java +Alice updates the book with new version 1 +Bob tries to update the book with his version 0 +Exception: Tried to update stale version 0 while actual version is 1 +``` + +## 类图 + +![alt text](./etc/version-number.urm.png "Version Number pattern class diagram") + +## 适用性 + +将版本号用于: + +* 解决对数据的并发写访问 +* 强的数据一致性 + +## 教程 +* [Version Number Pattern Tutorial](http://www.java2s.com/Tutorial/Java/0355__JPA/VersioningEntity.htm) + +## 已知用途 + * [Hibernate](https://vladmihalcea.com/jpa-entity-version-property-hibernate/) + * [Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-versioning) + * [Apache Solr](https://lucene.apache.org/solr/guide/6_6/updating-parts-of-documents.html) + +## 意义 +版本号模式允许实现并发控制,通常通过乐观离线锁模式来完成。 + +## 相关模式 +* [Optimistic Offline Lock](https://martinfowler.com/eaaCatalog/optimisticOfflineLock.html) + +## 鸣谢 +* [Optimistic Locking in JPA](https://www.baeldung.com/jpa-optimistic-locking) +* [JPA entity versioning](https://www.byteslounge.com/tutorials/jpa-entity-versioning-version-and-optimistic-locking) +* [J2EE Design Patterns](http://ommolketab.ir/aaf-lib/axkwht7wxrhvgs2aqkxse8hihyu9zv.pdf) diff --git a/localization/zh/version-number/etc/version-number.urm.png b/localization/zh/version-number/etc/version-number.urm.png new file mode 100644 index 000000000000..95a5819b4b6e Binary files /dev/null and b/localization/zh/version-number/etc/version-number.urm.png differ diff --git a/localization/zh/visitor/README.md b/localization/zh/visitor/README.md new file mode 100644 index 000000000000..58c4475696e5 --- /dev/null +++ b/localization/zh/visitor/README.md @@ -0,0 +1,223 @@ +--- +title: Visitor +shortTitle: Visitor +category: Behavioral +language: zh +tag: + - Gang of Four +--- + +## 目的 + +表示要在对象结构的元素上执行的操作。访问者可让你定义新操作,而无需更改其所操作元素的类。 + +## 解释 + +真实世界例子 + +> 考虑有一个带有军队单位的树形结构。指挥官下有两名中士,每名中士下有三名士兵。基于这个层级结构实现访问者模式,我们可以轻松创建与指挥官,中士,士兵或所有人员互动的新对象 + +通俗的说 + +> 访问者模式定义可以在数据结构的节点上执行的操作。 + +维基百科说 + +> 在面向对象的程序设计和软件工程中,访问者设计模式是一种将算法与操作对象的结构分离的方法。这种分离的实际结果是能够在不修改结构的情况下向现有对象结构添加新操作。 + +**程序示例** + +使用上面的军队单元的例子,我们首先由单位和单位访问器类型。 + +```java +public abstract class Unit { + + private final Unit[] children; + + public Unit(Unit... children) { + this.children = children; + } + + public void accept(UnitVisitor visitor) { + Arrays.stream(children).forEach(child -> child.accept(visitor)); + } +} + +public interface UnitVisitor { + + void visitSoldier(Soldier soldier); + + void visitSergeant(Sergeant sergeant); + + void visitCommander(Commander commander); +} +``` + +然后我们有具体的单元。 + +```java +public class Commander extends Unit { + + public Commander(Unit... children) { + super(children); + } + + @Override + public void accept(UnitVisitor visitor) { + visitor.visitCommander(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "commander"; + } +} + +public class Sergeant extends Unit { + + public Sergeant(Unit... children) { + super(children); + } + + @Override + public void accept(UnitVisitor visitor) { + visitor.visitSergeant(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "sergeant"; + } +} + +public class Soldier extends Unit { + + public Soldier(Unit... children) { + super(children); + } + + @Override + public void accept(UnitVisitor visitor) { + visitor.visitSoldier(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "soldier"; + } +} +``` + +然后有一些具体的访问者。 + +```java +public class CommanderVisitor implements UnitVisitor { + + private static final Logger LOGGER = LoggerFactory.getLogger(CommanderVisitor.class); + + @Override + public void visitSoldier(Soldier soldier) { + // Do nothing + } + + @Override + public void visitSergeant(Sergeant sergeant) { + // Do nothing + } + + @Override + public void visitCommander(Commander commander) { + LOGGER.info("Good to see you {}", commander); + } +} + +public class SergeantVisitor implements UnitVisitor { + + private static final Logger LOGGER = LoggerFactory.getLogger(SergeantVisitor.class); + + @Override + public void visitSoldier(Soldier soldier) { + // Do nothing + } + + @Override + public void visitSergeant(Sergeant sergeant) { + LOGGER.info("Hello {}", sergeant); + } + + @Override + public void visitCommander(Commander commander) { + // Do nothing + } +} + +public class SoldierVisitor implements UnitVisitor { + + private static final Logger LOGGER = LoggerFactory.getLogger(SoldierVisitor.class); + + @Override + public void visitSoldier(Soldier soldier) { + LOGGER.info("Greetings {}", soldier); + } + + @Override + public void visitSergeant(Sergeant sergeant) { + // Do nothing + } + + @Override + public void visitCommander(Commander commander) { + // Do nothing + } +} +``` + +最后,来看看实践中访问者模式的力量。 + +```java +commander.accept(new SoldierVisitor()); +commander.accept(new SergeantVisitor()); +commander.accept(new CommanderVisitor()); +``` + +程序输出: + +``` +Greetings soldier +Greetings soldier +Greetings soldier +Greetings soldier +Greetings soldier +Greetings soldier +Hello sergeant +Hello sergeant +Good to see you commander +``` + +## Class diagram + +![alt text](./etc/visitor_1.png "Visitor") + +## 适用性 + +使用访问者模式当 + +* 对象结构包含许多具有不同接口的对象类,并且你希望根据这些对象的具体类对这些对象执行操作。 +* 需要对对象结构中的对象执行许多不同且不相关的操作,并且你想避免使用这些操作“污染”它们的类。 访问者可以通过在一个类中定义相关操作来将它们保持在一起。当许多应用程序共享对象结构时,请使用访问者模式将操作仅放在需要它们的那些应用程序中 +* 定义对象结构的类很少变化,但是你经常想在结构上定义新的操作。更改对象结构类需要重新定义所有访问者的接口,这可能会导致成本高昂。如果对象结构类经常更改,则最好在这些类中定义操作。 + +## 真实例子 + +* [Apache Wicket](https://github.com/apache/wicket) component tree, see [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java) +* [javax.lang.model.element.AnnotationValue](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/AnnotationValue.html) and [AnnotationValueVisitor](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/AnnotationValueVisitor.html) +* [javax.lang.model.element.Element](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/Element.html) and [Element Visitor](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/ElementVisitor.html) +* [java.nio.file.FileVisitor](http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileVisitor.html) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/localization/zh/visitor/etc/visitor_1.png b/localization/zh/visitor/etc/visitor_1.png new file mode 100644 index 000000000000..de5285d7fdc3 Binary files /dev/null and b/localization/zh/visitor/etc/visitor_1.png differ diff --git a/lockable-object/README.md b/lockable-object/README.md new file mode 100644 index 000000000000..108d27c5e337 --- /dev/null +++ b/lockable-object/README.md @@ -0,0 +1,163 @@ +--- +title: "Lockable Object Pattern in Java: Implementing Robust Synchronization Mechanisms" +shortTitle: Lockable Object +description: "Learn about the Lockable Object design pattern in Java. Explore its usage, real-world examples, benefits, and how it ensures thread safety and resource management in multithreaded environments." +category: Concurrency +language: en +tag: + - Decoupling + - Encapsulation + - Security + - Synchronization + - Thread management +--- + +## Also known as + +* Resource Lock +* Mutual Exclusion Object + +## Intent of Lockable Object Design Pattern + +The Lockable Object pattern in Java aims to control access to a shared resource in a multithreaded environment, ensuring thread safety by providing a mechanism for resource locking, ensuring that only one thread can access the resource at a time. + +## Detailed Explanation of Lockable Object Pattern with Real-World Examples + +Real-world example + +> Imagine a shared printer in a busy office as an analogous real-world example of the Lockable Object design pattern in Java. This pattern ensures that only one thread can access the resource at a time, thus maintaining concurrency control and synchronization. Multiple employees need to print documents throughout the day, but the printer can only handle one print job at a time. To manage this, there's a locking system in place—much like a lockable object in programming—that ensures when one person is printing, others must wait their turn. This prevents print jobs from overlapping or interfering with each other, ensuring that each document is printed correctly and in the order it was sent, mirroring the concept of thread synchronization and resource locking in software development. + +In plain words + +> The Lockable Object design pattern ensures safe access to a shared resource in a multithreaded environment by allowing only one thread to access the resource at a time through locking mechanisms. + +Wikipedia says + +> In computer science, a lock or mutex (from mutual exclusion) is a synchronization primitive that prevents state from being modified or accessed by multiple threads of execution at once. Locks enforce mutual exclusion concurrency control policies, and with a variety of possible methods there exist multiple unique implementations for different applications. + +Sequence diagram + +![Lockable Object Sequence Diagram](./etc/lockable-object-sequence-diagram.png) + +## Programmatic Example of Lockable Object Pattern in Java + +The Lockable Object pattern is a concurrency control design pattern in Java that allows only one thread to access a shared resource at a time, ensuring mutual exclusion and preventing data corruption. Instead of using the `synchronized` keyword on the methods to be synchronized, the object which implements the Lockable interface handles the request. + +In this example, we have a `SwordOfAragorn` object that implements the `Lockable` interface. Multiple `Creature` objects, represented by `Elf`, `Orc`, and `Human` classes, are trying to acquire the sword. Each `Creature` is wrapped in a `Feind` object that implements `Runnable`, allowing each creature to attempt to acquire the sword in a separate thread. + +Here's the `Lockable` interface: + +```java +public interface Lockable { + boolean isLocked(); + Creature getLocker(); + boolean acquire(Creature creature); + void release(Creature creature); +} +``` + +The `SwordOfAragorn` class implements this interface: + +```java +public class SwordOfAragorn implements Lockable { + // Implementation details... +} +``` + +The `Creature` class and its subclasses (`Elf`, `Orc`, `Human`) represent different creatures that can try to acquire the sword: + +```java +public abstract class Creature { + // Implementation details... +} + +public class Elf extends Creature { + // Implementation details... +} + +public class Orc extends Creature { + // Implementation details... +} + +public class Human extends Creature { + // Implementation details... +} +``` + +The `Feind` class wraps a `Creature` and a `Lockable` object, and implements `Runnable`: + +```java +public class Feind implements Runnable { + private final Creature creature; + private final Lockable target; + + public Feind(@NonNull Creature feind, @NonNull Lockable target) { + this.creature = feind; + this.target = target; + } + + @Override + public void run() { + if (!creature.acquire(target)) { + fightForTheSword(creature, target.getLocker(), target); + } else { + LOGGER.info("{} has acquired the sword!", target.getLocker().getName()); + } + } + + // Additional methods... +} +``` + +In the `App` class, multiple `Feind` objects are created and submitted to an `ExecutorService`, each in a separate thread: + +```java +public class App implements Runnable { + @Override + public void run() { + var sword = new SwordOfAragorn(); + List creatures = new ArrayList<>(); + // Creation of creatures... + ExecutorService service = Executors.newFixedThreadPool(totalFiends); + for (var i = 0; i < totalFiends; i = i + MULTIPLICATION_FACTOR) { + service.submit(new Feind(creatures.get(i), sword)); + service.submit(new Feind(creatures.get(i + 1), sword)); + service.submit(new Feind(creatures.get(i + 2), sword)); + } + // Additional code... + } +} +``` + +This example demonstrates the Lockable Object pattern by showing how multiple threads can attempt to acquire a lock on a shared resource, with only one thread being able to acquire the lock at a time. + +## When to Use the Lockable Object Pattern in Java + +* Use the Lockable Object pattern in Java when you need to prevent data corruption by multiple threads accessing a shared resource concurrently, ensuring thread safety and robust shared resource management. +* Suitable for systems where thread safety is critical and data integrity must be maintained across various operations. + +## Real-World Applications of Lockable Object Pattern in Java + +* Java’s synchronized keyword and the Lock interfaces in the java.util.concurrent.locks package implement lockable objects to manage synchronization. + +## Benefits and Trade-offs of Lockable Object Pattern + +Benefits: + +* Ensures data consistency and prevents race conditions. +* Provides clear structure for managing access to shared resources. + +Trade-offs: + +* Can lead to decreased performance due to overhead of acquiring and releasing locks. +* Potential for deadlocks if not implemented and managed carefully. + +## Related Java Design Patterns + +* [Monitor Object](https://java-design-patterns.com/patterns/monitor/): Both patterns manage access to shared resources; Monitor Object combines synchronization and encapsulation of the condition variable. +* [Read/Write Lock](https://java-design-patterns.com/patterns/reader-writer-lock/): Specialization of Lockable Object for scenarios where read operations outnumber write operations. + +## References and Credits + +* [Java Concurrency in Practice](https://amzn.to/4aRMruW) +* [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) diff --git a/lockable-object/etc/lockable-object-sequence-diagram.png b/lockable-object/etc/lockable-object-sequence-diagram.png new file mode 100644 index 000000000000..10b08a5f15f1 Binary files /dev/null and b/lockable-object/etc/lockable-object-sequence-diagram.png differ diff --git a/lockable-object/etc/lockable-object.urm.png b/lockable-object/etc/lockable-object.urm.png new file mode 100644 index 000000000000..431244f2b314 Binary files /dev/null and b/lockable-object/etc/lockable-object.urm.png differ diff --git a/lockable-object/etc/lockable-object.urm.puml b/lockable-object/etc/lockable-object.urm.puml new file mode 100644 index 000000000000..646cc3bc5a06 --- /dev/null +++ b/lockable-object/etc/lockable-object.urm.puml @@ -0,0 +1,94 @@ +@startuml +package com.iluwatar.lockableobject.domain { + abstract class Creature { + - LOGGER : Logger {static} + - damage : int + - health : int + ~ instruments : Set + - name : String + - type : CreatureType + + Creature(name : String) + + acquire(lockable : Lockable) : boolean + + attack(creature : Creature) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getDamage() : int + + getHealth() : int + + getInstruments() : Set + + getName() : String + + getType() : CreatureType + + hashCode() : int + + hit(damage : int) + + isAlive() : boolean + + kill() + + setDamage(damage : int) + + setHealth(health : int) + + setInstruments(instruments : Set) + + setName(name : String) + + setType(type : CreatureType) + + toString() : String + } + enum CreatureType { + + ELF {static} + + HUMAN {static} + + ORC {static} + + valueOf(name : String) : CreatureType {static} + + values() : CreatureType[] {static} + } + class Elf { + + Elf(name : String) + } + class Feind { + - LOGGER : Logger {static} + - feind : Creature + - target : Lockable + + Feind(feind : Creature, target : Lockable) + - fightForTheSword(reacher : Creature, holder : Creature, sword : Lockable) + + run() + } + class Human { + + Human(name : String) + } + class Orc { + + Orc(name : String) + } +} +package com.iluwatar.lockableobject { + class App { + - LOGGER : Logger {static} + - MULTIPLICATION_FACTOR : int {static} + - WAIT_TIME : int {static} + - WORKERS : int {static} + + App() + + main(args : String[]) {static} + } + interface Lockable { + + getLocker() : Creature {abstract} + + getName() : String {abstract} + + isLocked() : boolean {abstract} + + lock(Creature) : boolean {abstract} + + unlock(Creature) {abstract} + } + class SwordOfAragorn { + - LOGGER : Logger {static} + - NAME : String {static} + - locker : Creature + - synchronizer : Object + + SwordOfAragorn() + + getLocker() : Creature + + getName() : String + + isLocked() : boolean + + lock(creature : Creature) : boolean + + unlock(creature : Creature) + } +} +Creature --> "-type" CreatureType +Creature --> "-instruments" Lockable +Feind --> "-feind" Creature +Feind --> "-target" Lockable +SwordOfAragorn --> "-locker" Creature +SwordOfAragorn ..|> Lockable +Elf --|> Creature +Human --|> Creature +Orc --|> Creature +@enduml \ No newline at end of file diff --git a/lockable-object/pom.xml b/lockable-object/pom.xml new file mode 100644 index 000000000000..a96ec972e726 --- /dev/null +++ b/lockable-object/pom.xml @@ -0,0 +1,72 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + lockable-object + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.lockableobject.App + + + + + + + + + diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java new file mode 100644 index 000000000000..1c05f7d33428 --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java @@ -0,0 +1,99 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject; + +import com.iluwatar.lockableobject.domain.Creature; +import com.iluwatar.lockableobject.domain.Elf; +import com.iluwatar.lockableobject.domain.Feind; +import com.iluwatar.lockableobject.domain.Human; +import com.iluwatar.lockableobject.domain.Orc; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; + +/** + * The Lockable Object pattern is a concurrency pattern. Instead of using the "synchronized" word + * upon the methods to be synchronized, the object which implements the Lockable interface handles + * the request. + * + *

    In this example, we create a new Lockable object with the SwordOfAragorn implementation of it. + * Afterward we create 6 Creatures with the Elf, Orc and Human implementations and assign them each + * to a Fiend object and the Sword is the target object. Because there is only one Sword, and it + * uses the Lockable Object pattern, only one creature can hold the sword at a given time. When the + * sword is locked, any other alive Fiends will try to lock, which will result in a race to lock the + * sword. + */ +@Slf4j +public class App implements Runnable { + + private static final int WAIT_TIME = 3; + private static final int WORKERS = 2; + private static final int MULTIPLICATION_FACTOR = 3; + + /** + * main method. + * + * @param args as arguments for the main method. + */ + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + // The target object for this example. + var sword = new SwordOfAragorn(); + // Creation of creatures. + List creatures = new ArrayList<>(); + for (var i = 0; i < WORKERS; i++) { + creatures.add(new Elf(String.format("Elf %s", i))); + creatures.add(new Orc(String.format("Orc %s", i))); + creatures.add(new Human(String.format("Human %s", i))); + } + int totalFiends = WORKERS * MULTIPLICATION_FACTOR; + ExecutorService service = Executors.newFixedThreadPool(totalFiends); + // Attach every creature and the sword is a Fiend to fight for the sword. + for (var i = 0; i < totalFiends; i = i + MULTIPLICATION_FACTOR) { + service.submit(new Feind(creatures.get(i), sword)); + service.submit(new Feind(creatures.get(i + 1), sword)); + service.submit(new Feind(creatures.get(i + 2), sword)); + } + // Wait for program to terminate. + try { + if (!service.awaitTermination(WAIT_TIME, TimeUnit.SECONDS)) { + LOGGER.info("The master of the sword is now {}.", sword.getLocker().getName()); + } + } catch (InterruptedException e) { + LOGGER.error(e.getMessage()); + Thread.currentThread().interrupt(); + } finally { + service.shutdown(); + } + } +} diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/Lockable.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/Lockable.java new file mode 100644 index 000000000000..4f952b134a00 --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/Lockable.java @@ -0,0 +1,67 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject; + +import com.iluwatar.lockableobject.domain.Creature; + +/** This interface describes the methods to be supported by a lockable-object. */ +public interface Lockable { + + /** + * Checks if the object is locked. + * + * @return true if it is locked. + */ + boolean isLocked(); + + /** + * locks the object with the creature as the locker. + * + * @param creature as the locker. + * @return true if the object was locked successfully. + */ + boolean lock(Creature creature); + + /** + * Unlocks the object. + * + * @param creature as the locker. + */ + void unlock(Creature creature); + + /** + * Gets the locker. + * + * @return the Creature that holds the object. Returns null if no one is locking. + */ + Creature getLocker(); + + /** + * Returns the name of the object. + * + * @return the name of the object. + */ + String getName(); +} diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java new file mode 100644 index 000000000000..dd1d2b8f7d9b --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject; + +import java.io.Serial; + +/** An exception regarding the locking process of a Lockable object. */ +public class LockingException extends RuntimeException { + + @Serial private static final long serialVersionUID = 8556381044865867037L; + + public LockingException(String message) { + super(message); + } +} diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/SwordOfAragorn.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/SwordOfAragorn.java new file mode 100644 index 000000000000..8e05ea6e684b --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/SwordOfAragorn.java @@ -0,0 +1,90 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject; + +import com.iluwatar.lockableobject.domain.Creature; +import lombok.NonNull; +import lombok.extern.slf4j.Slf4j; + +/** + * An implementation of a Lockable object. This is the Sword of Aragorn and every creature wants to + * possess it! + */ +@Slf4j +public class SwordOfAragorn implements Lockable { + + private Creature locker; + private final Object synchronizer; + private static final String NAME = "The Sword of Aragorn"; + + public SwordOfAragorn() { + this.locker = null; + this.synchronizer = new Object(); + } + + @Override + public boolean isLocked() { + return this.locker != null; + } + + @Override + public boolean lock(@NonNull Creature creature) { + synchronized (synchronizer) { + LOGGER.info("{} is now trying to acquire {}!", creature.getName(), this.getName()); + if (!isLocked()) { + locker = creature; + return true; + } else { + if (!locker.getName().equals(creature.getName())) { + return false; + } + } + } + return false; + } + + @Override + public void unlock(@NonNull Creature creature) { + synchronized (synchronizer) { + if (locker != null && locker.getName().equals(creature.getName())) { + locker = null; + LOGGER.info("{} is now free!", this.getName()); + } + if (locker != null) { + throw new LockingException("You cannot unlock an object you are not the owner of."); + } + } + } + + @Override + public Creature getLocker() { + return this.locker; + } + + @Override + public String getName() { + return NAME; + } +} diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java new file mode 100644 index 000000000000..05b6db00129b --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java @@ -0,0 +1,112 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject.domain; + +import com.iluwatar.lockableobject.Lockable; +import java.util.HashSet; +import java.util.Set; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + +/** + * An abstract class of a creature that wanders across the wasteland. It can attack, get hit and + * acquire a Lockable object. + */ +@Getter +@Setter +@Slf4j +public abstract class Creature { + + private String name; + private CreatureType type; + private int health; + private int damage; + Set instruments; + + protected Creature(@NonNull String name) { + this.name = name; + this.instruments = new HashSet<>(); + } + + /** + * Reaches for the Lockable and tried to hold it. + * + * @param lockable as the Lockable to lock. + * @return true of Lockable was locked by this creature. + */ + public boolean acquire(@NonNull Lockable lockable) { + if (lockable.lock(this)) { + instruments.add(lockable); + return true; + } + return false; + } + + /** Terminates the Creature and unlocks all the Lockable that it possesses. */ + public synchronized void kill() { + LOGGER.info("{} {} has been slayed!", type, name); + for (Lockable lockable : instruments) { + lockable.unlock(this); + } + this.instruments.clear(); + } + + /** + * Attacks a foe. + * + * @param creature as the foe to be attacked. + */ + public synchronized void attack(@NonNull Creature creature) { + creature.hit(getDamage()); + } + + /** + * When a creature gets hit it removed the amount of damage from the creature's life. + * + * @param damage as the damage that was taken. + */ + public synchronized void hit(int damage) { + if (damage < 0) { + throw new IllegalArgumentException("Damage cannot be a negative number"); + } + if (isAlive()) { + setHealth(getHealth() - damage); + if (!isAlive()) { + kill(); + } + } + } + + /** + * Checks if the creature is still alive. + * + * @return true of creature is alive. + */ + public synchronized boolean isAlive() { + return getHealth() > 0; + } +} diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java new file mode 100644 index 000000000000..7996a0269f9a --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java @@ -0,0 +1,43 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject.domain; + +import lombok.Getter; + +/** Attribute constants of each Creature implementation. */ +public enum CreatureStats { + ELF_HEALTH(90), + ELF_DAMAGE(40), + ORC_HEALTH(70), + ORC_DAMAGE(50), + HUMAN_HEALTH(60), + HUMAN_DAMAGE(60); + + @Getter final int value; + + CreatureStats(int value) { + this.value = value; + } +} diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureType.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureType.java new file mode 100644 index 000000000000..5e86fb0a35bf --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureType.java @@ -0,0 +1,32 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject.domain; + +/** Constants of supported creatures. */ +public enum CreatureType { + ORC, + HUMAN, + ELF +} diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Elf.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Elf.java new file mode 100644 index 000000000000..ead2e3c687d7 --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Elf.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject.domain; + +/** An Elf implementation of a Creature. */ +public class Elf extends Creature { + + /** + * A constructor that initializes the attributes of an elf. + * + * @param name as the name of the creature. + */ + public Elf(String name) { + super(name); + setType(CreatureType.ELF); + setDamage(CreatureStats.ELF_DAMAGE.getValue()); + setHealth(CreatureStats.ELF_HEALTH.getValue()); + } +} diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Feind.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Feind.java new file mode 100644 index 000000000000..4bee7024f2a3 --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Feind.java @@ -0,0 +1,88 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject.domain; + +import com.iluwatar.lockableobject.Lockable; +import java.security.SecureRandom; +import lombok.NonNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** A Feind is a creature that wants to possess a Lockable object. */ +public class Feind implements Runnable { + + private final Creature creature; + private final Lockable target; + private final SecureRandom random; + private static final Logger LOGGER = LoggerFactory.getLogger(Feind.class.getName()); + + /** + * public constructor. + * + * @param feind as the creature to lock to he lockable. + * @param target as the target object. + */ + public Feind(@NonNull Creature feind, @NonNull Lockable target) { + this.creature = feind; + this.target = target; + this.random = new SecureRandom(); + } + + @Override + public void run() { + if (!creature.acquire(target)) { + fightForTheSword(creature, target.getLocker(), target); + } else { + LOGGER.info("{} has acquired the sword!", target.getLocker().getName()); + } + } + + /** + * Keeps on fighting until the Lockable is possessed. + * + * @param reacher as the source creature. + * @param holder as the foe. + * @param sword as the Lockable to possess. + */ + private void fightForTheSword(Creature reacher, @NonNull Creature holder, Lockable sword) { + LOGGER.info("A duel between {} and {} has been started!", reacher.getName(), holder.getName()); + boolean randBool; + while (this.target.isLocked() && reacher.isAlive() && holder.isAlive()) { + randBool = random.nextBoolean(); + if (randBool) { + reacher.attack(holder); + } else { + holder.attack(reacher); + } + } + if (reacher.isAlive()) { + if (!reacher.acquire(sword)) { + fightForTheSword(reacher, sword.getLocker(), sword); + } else { + LOGGER.info("{} has acquired the sword!", reacher.getName()); + } + } + } +} diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Human.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Human.java new file mode 100644 index 000000000000..c079ab376f9a --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Human.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject.domain; + +/** A human implementation of a Creature. */ +public class Human extends Creature { + + /** + * A constructor that initializes the attributes of a human. + * + * @param name as the name of the creature. + */ + public Human(String name) { + super(name); + setType(CreatureType.HUMAN); + setDamage(CreatureStats.HUMAN_DAMAGE.getValue()); + setHealth(CreatureStats.HUMAN_HEALTH.getValue()); + } +} diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Orc.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Orc.java new file mode 100644 index 000000000000..0f13fcc0d2c2 --- /dev/null +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Orc.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject.domain; + +/** An Orc implementation of a Creature. */ +public class Orc extends Creature { + /** + * A constructor that initializes the attributes of an orc. + * + * @param name as the name of the creature. + */ + public Orc(String name) { + super(name); + setType(CreatureType.ORC); + setDamage(CreatureStats.ORC_DAMAGE.getValue()); + setHealth(CreatureStats.ORC_HEALTH.getValue()); + } +} diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/AppTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/AppTest.java new file mode 100644 index 000000000000..db4b64fd045d --- /dev/null +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/AppTest.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } + + @Test + void shouldExecuteApplicationAsRunnableWithoutException() { + assertDoesNotThrow(() -> (new App()).run()); + } +} diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java new file mode 100644 index 000000000000..de7fc3678089 --- /dev/null +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java @@ -0,0 +1,103 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject; + +import com.iluwatar.lockableobject.domain.Creature; +import com.iluwatar.lockableobject.domain.CreatureStats; +import com.iluwatar.lockableobject.domain.CreatureType; +import com.iluwatar.lockableobject.domain.Elf; +import com.iluwatar.lockableobject.domain.Orc; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CreatureTest { + + private Creature orc; + private Creature elf; + private Lockable sword; + + @BeforeEach + void init() { + elf = new Elf("Elf test"); + orc = new Orc("Orc test"); + sword = new SwordOfAragorn(); + } + + @Test + void baseTest() { + Assertions.assertEquals("Elf test", elf.getName()); + Assertions.assertEquals(CreatureType.ELF, elf.getType()); + Assertions.assertThrows(NullPointerException.class, () -> new Elf(null)); + Assertions.assertThrows(NullPointerException.class, () -> elf.acquire(null)); + Assertions.assertThrows(NullPointerException.class, () -> elf.attack(null)); + Assertions.assertThrows(IllegalArgumentException.class, () -> elf.hit(-10)); + } + + @Test + void hitTest() { + elf.hit(CreatureStats.ELF_HEALTH.getValue() / 2); + Assertions.assertEquals(CreatureStats.ELF_HEALTH.getValue() / 2, elf.getHealth()); + elf.hit(CreatureStats.ELF_HEALTH.getValue() / 2); + Assertions.assertFalse(elf.isAlive()); + + Assertions.assertEquals(0, orc.getInstruments().size()); + Assertions.assertTrue(orc.acquire(sword)); + Assertions.assertEquals(1, orc.getInstruments().size()); + orc.kill(); + Assertions.assertEquals(0, orc.getInstruments().size()); + } + + @Test + void testFight() throws InterruptedException { + killCreature(elf, orc); + Assertions.assertTrue(elf.isAlive()); + Assertions.assertFalse(orc.isAlive()); + Assertions.assertTrue(elf.getHealth() > 0); + Assertions.assertTrue(orc.getHealth() <= 0); + } + + @Test + void testAcqusition() throws InterruptedException { + Assertions.assertTrue(elf.acquire(sword)); + Assertions.assertEquals(elf.getName(), sword.getLocker().getName()); + Assertions.assertTrue(elf.getInstruments().contains(sword)); + Assertions.assertFalse(orc.acquire(sword)); + killCreature(orc, elf); + Assertions.assertTrue(orc.acquire(sword)); + Assertions.assertEquals(orc, sword.getLocker()); + } + + void killCreature(Creature source, Creature target) { + while (target.isAlive()) { + source.attack(target); + } + } + + @Test + void invalidDamageTest() { + Assertions.assertThrows(IllegalArgumentException.class, () -> elf.hit(-50)); + } +} diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java new file mode 100644 index 000000000000..26a97853e78a --- /dev/null +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class ExceptionsTest { + + private static final String MSG = "test"; + + @Test + void testException() { + Exception e; + try { + throw new LockingException(MSG); + } catch (LockingException ex) { + e = ex; + } + Assertions.assertEquals(MSG, e.getMessage()); + } +} diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/FeindTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/FeindTest.java new file mode 100644 index 000000000000..cedaf65b0d59 --- /dev/null +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/FeindTest.java @@ -0,0 +1,70 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject; + +import com.iluwatar.lockableobject.domain.Creature; +import com.iluwatar.lockableobject.domain.Elf; +import com.iluwatar.lockableobject.domain.Feind; +import com.iluwatar.lockableobject.domain.Orc; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class FeindTest { + + private Creature elf; + private Creature orc; + private Lockable sword; + + @BeforeEach + void init() { + elf = new Elf("Nagdil"); + orc = new Orc("Ghandar"); + sword = new SwordOfAragorn(); + } + + @Test + void nullTests() { + Assertions.assertThrows(NullPointerException.class, () -> new Feind(null, null)); + Assertions.assertThrows(NullPointerException.class, () -> new Feind(elf, null)); + Assertions.assertThrows(NullPointerException.class, () -> new Feind(null, sword)); + } + + @Test + void testBaseCase() throws InterruptedException { + var base = new Thread(new Feind(orc, sword)); + Assertions.assertNull(sword.getLocker()); + base.start(); + base.join(); + Assertions.assertEquals(orc, sword.getLocker()); + var extend = new Thread(new Feind(elf, sword)); + extend.start(); + extend.join(); + Assertions.assertTrue(sword.isLocked()); + + sword.unlock(elf.isAlive() ? elf : orc); + Assertions.assertNull(sword.getLocker()); + } +} diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/SubCreaturesTests.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/SubCreaturesTests.java new file mode 100644 index 000000000000..b6db856853c4 --- /dev/null +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/SubCreaturesTests.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject; + +import com.iluwatar.lockableobject.domain.CreatureStats; +import com.iluwatar.lockableobject.domain.Elf; +import com.iluwatar.lockableobject.domain.Human; +import com.iluwatar.lockableobject.domain.Orc; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class SubCreaturesTests { + + @Test + void statsTest() { + var elf = new Elf("Limbar"); + var orc = new Orc("Dargal"); + var human = new Human("Jerry"); + Assertions.assertEquals(CreatureStats.ELF_HEALTH.getValue(), elf.getHealth()); + Assertions.assertEquals(CreatureStats.ELF_DAMAGE.getValue(), elf.getDamage()); + Assertions.assertEquals(CreatureStats.ORC_DAMAGE.getValue(), orc.getDamage()); + Assertions.assertEquals(CreatureStats.ORC_HEALTH.getValue(), orc.getHealth()); + Assertions.assertEquals(CreatureStats.HUMAN_DAMAGE.getValue(), human.getDamage()); + Assertions.assertEquals(CreatureStats.HUMAN_HEALTH.getValue(), human.getHealth()); + } +} diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/TheSwordOfAragornTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/TheSwordOfAragornTest.java new file mode 100644 index 000000000000..4c40f806b3cb --- /dev/null +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/TheSwordOfAragornTest.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.lockableobject; + +import com.iluwatar.lockableobject.domain.Human; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class TheSwordOfAragornTest { + + @Test + void basicSwordTest() { + var sword = new SwordOfAragorn(); + Assertions.assertNotNull(sword.getName()); + Assertions.assertNull(sword.getLocker()); + Assertions.assertFalse(sword.isLocked()); + var human = new Human("Tupac"); + Assertions.assertTrue(human.acquire(sword)); + Assertions.assertEquals(human, sword.getLocker()); + Assertions.assertTrue(sword.isLocked()); + } + + @Test + void invalidLockerTest() { + var sword = new SwordOfAragorn(); + Assertions.assertThrows(NullPointerException.class, () -> sword.lock(null)); + Assertions.assertThrows(NullPointerException.class, () -> sword.unlock(null)); + } +} diff --git a/lombok.config b/lombok.config new file mode 100644 index 000000000000..a3a1dc642fdf --- /dev/null +++ b/lombok.config @@ -0,0 +1,2 @@ +lombok.log.fieldName = LOGGER +lombok.addLombokGeneratedAnnotation = true diff --git a/map-reduce/README.md b/map-reduce/README.md new file mode 100644 index 000000000000..d832616ba5a2 --- /dev/null +++ b/map-reduce/README.md @@ -0,0 +1,265 @@ +--- +title: "MapReduce Pattern in Java" +shortTitle: MapReduce +description: "Learn the MapReduce pattern in Java with real-world examples, class diagrams, and tutorials. Understand its intent, applicability, benefits, and known uses to enhance your design pattern knowledge." +category: Functional +language: en +tag: + - Concurrency + - Data processing + - Data transformation + - Functional decomposition + - Immutable + - Multithreading + - Scalability +--- + +## Also known as + +* Map-Reduce +* Divide and Conquer for Data Processing + +## Intent of Map Reduce Design Pattern + +To efficiently process large-scale datasets by dividing computation into two phases: map and reduce, which can be executed in parallel and distributed across multiple nodes. + +## Detailed Explanation of Map Reduce Pattern with Real-World Examples + +Real-world example + +> Imagine a large e-commerce company that wants to analyze its sales data across multiple regions. They have terabytes of transaction data stored across hundreds of servers. Using MapReduce, they can efficiently process this data to calculate total sales by product category. The Map function would process individual sales records, emitting key-value pairs of (category, sale amount). The Reduce function would then sum up all sale amounts for each category, producing the final result. + +In plain words + +> MapReduce splits a large problem into smaller parts, processes them in parallel, and then combines the results. + +Wikipedia says + +> MapReduce is a programming model and associated implementation for processing and generating big data sets with a parallel, distributed algorithm on a cluster. MapReduce consists of two main steps: +The Map step: The master node takes the input, divides it into smaller sub-problems, and distributes them to worker nodes. A worker node may do this again in turn, leading to a multi-level tree structure. The worker node processes the smaller problem, and passes the answer back to its master node. The Reduce step: The master node then collects the answers to all the sub-problems and combines them in some way to form the output – the answer to the problem it was originally trying to solve. This approach allows for efficient processing of vast amounts of data across multiple machines, making it a fundamental technique in big data analytics and distributed computing. + +Flowchart + +![MapReduce flowchart](./etc/mapreduce-flowchart.png) + +## Programmatic Example of Map Reduce in Java + +### 1. Map Phase (Splitting & Processing Data) + +* Each input string is split into words, normalized, and counted. +* Output: A map `{word → count}` for each input string. + +#### `Mapper.java` + +```java +public class Mapper { + public static Map map(String input) { + Map wordCount = new HashMap<>(); + String[] words = input.split("\\s+"); + for (String word : words) { + word = word.toLowerCase().replaceAll("[^a-z]", ""); + if (!word.isEmpty()) { + wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); + } + } + return wordCount; + } +} +``` + +Example Input: ```"Hello world hello"``` +Output: ```{hello=2, world=1}``` + +### 2. Shuffle Phase – Grouping Words Across Inputs + +* Takes results from all mappers and groups values by word. +* Output: A map `{word → list of counts}`. + +#### `Shuffler.java` + +```java +public class Shuffler { + public static Map> shuffleAndSort(List> mapped) { + Map> grouped = new HashMap<>(); + for (Map map : mapped) { + for (Map.Entry entry : map.entrySet()) { + grouped.putIfAbsent(entry.getKey(), new ArrayList<>()); + grouped.get(entry.getKey()).add(entry.getValue()); + } + } + return grouped; + } +} +``` + +Example Input: + +``` +[ + {"hello": 2, "world": 1}, + {"hello": 1, "java": 1} +] +``` + +Output: + +``` +{ + "hello": [2, 1], + "world": [1], + "java": [1] +} +``` + +### 3. Reduce Phase – Aggregating Counts + +* Sums the list of counts for each word. +* Output: A sorted list of word counts in descending order. + +#### `Reducer.java` + +```java +public class Reducer { + public static List> reduce(Map> grouped) { + Map reduced = new HashMap<>(); + for (Map.Entry> entry : grouped.entrySet()) { + reduced.put(entry.getKey(), entry.getValue().stream().mapToInt(Integer::intValue).sum()); + } + + List> result = new ArrayList<>(reduced.entrySet()); + result.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); + return result; + } +} +``` + +Example Input: + +``` +{ + "hello": [2, 1], + "world": [1], + "java": [1] +} +``` + +Output: + +``` +[ + {"hello": 3}, + {"world": 1}, + {"java": 1} +] +``` + +### 4. MapReduce Coordinator – Running the Whole Pipeline + +* Coordinates map, shuffle, and reduce phases. + +#### `MapReduce.java` + +```java +public class MapReduce { + public static List> mapReduce(List inputs) { + List> mapped = new ArrayList<>(); + for (String input : inputs) { + mapped.add(Mapper.map(input)); + } + + Map> grouped = Shuffler.shuffleAndSort(mapped); + + return Reducer.reduce(grouped); + } +} +``` + +### 5. Main Execution – Example Usage + +* Runs the MapReduce process and prints results. + +#### `Main.java` + +```java + public static void main(String[] args) { + List inputs = Arrays.asList( + "Hello world hello", + "MapReduce is fun", + "Hello from the other side", + "Hello world" + ); + List> result = MapReduce.mapReduce(inputs); + for (Map.Entry entry : result) { + System.out.println(entry.getKey() + ": " + entry.getValue()); + } +} +``` + +Output: + +``` +hello: 4 +world: 2 +the: 1 +other: 1 +side: 1 +mapreduce: 1 +is: 1 +from: 1 +fun: 1 +``` + +## When to Use the Map Reduce Pattern in Java + +Use MapReduce when: + +* When processing large datasets that can be broken into independent chunks. +* When data operations can be naturally divided into map (transformation) and reduce (aggregation) phases. +* When horizontal scalability and parallelization are essential, especially in distributed or big data environments. +* When leveraging Java-based distributed computing platforms like Hadoop or Spark. + +## Map Reduce Pattern Java Tutorials + +* [MapReduce Tutorial(Apache Hadoop)](https://hadoop.apache.org/docs/stable/hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduceTutorial.html) +* [MapReduce Example(Simplilearn)](https://www.youtube.com/watch?v=l2clwKnrtO8) + +## Benefits and Trade-offs of Map Reduce Pattern + +Benefits: + +* Enables massive scalability by distributing processing across nodes. +* Encourages a functional style, promoting immutability and stateless operations. +* Simplifies complex data workflows by separating transformation (map) from aggregation (reduce). +* Fault-tolerant due to isolated, recoverable processing tasks. + +Trade-offs: + +* Requires a suitable problem structure — not all tasks fit the map/reduce paradigm. +* Data shuffling between map and reduce phases can be performance-intensive. +* Higher complexity in debugging and optimizing distributed jobs. +* Intermediate I/O can become a bottleneck in large-scale operations. + +## Real-World Applications of Map Reduce Pattern in Java + +* Hadoop MapReduce: Java-based framework for distributed data processing using MapReduce. +* Apache Spark: Utilizes similar map and reduce transformations in its RDD and Dataset APIs. +* Elasticsearch: Uses MapReduce-style aggregation pipelines for querying distributed data. +* Google Bigtable: Underlying storage engine influenced by MapReduce principles. +* MongoDB Aggregation Framework: Conceptually applies MapReduce in its data pipelines. + +## Related Java Design Patterns + +* [Master-Worker](https://java-design-patterns.com/patterns/master-worker/): Similar distribution of tasks among workers, with a master coordinating job execution. +* [Pipeline](https://java-design-patterns.com/patterns/pipeline/): Can be used to chain multiple MapReduce operations into staged transformations. +* [Iterator](https://java-design-patterns.com/patterns/iterator/): Often used under the hood to process input streams lazily in map and reduce steps. + +## References and Credits + +* [Big Data: Principles and Paradigms](https://amzn.to/3RJIGPZ) +* [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3E6VhtD) +* [Hadoop: The Definitive Guide: Storage and Analysis at Internet Scale](https://amzn.to/4ij2y7F) +* [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3QCmGXs) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3HWNf4U) +* [Programming Pig: Dataflow Scripting with Hadoop](https://amzn.to/4cAU36K) +* [What is MapReduce (IBM)](https://www.ibm.com/think/topics/mapreduce) +* [Why MapReduce is not dead (Codemotion)](https://www.codemotion.com/magazine/ai-ml/big-data/mapreduce-not-dead-heres-why-its-still-ruling-in-the-cloud/) diff --git a/map-reduce/etc/map-reduce.png b/map-reduce/etc/map-reduce.png new file mode 100644 index 000000000000..caf764553291 Binary files /dev/null and b/map-reduce/etc/map-reduce.png differ diff --git a/map-reduce/etc/map-reduce.urm.puml b/map-reduce/etc/map-reduce.urm.puml new file mode 100644 index 000000000000..508f1fd3363d --- /dev/null +++ b/map-reduce/etc/map-reduce.urm.puml @@ -0,0 +1,24 @@ +@startuml +package com.iluwatar { + class Main { + + Main() + + main(args : String[]) {static} + } + class MapReduce { + + MapReduce() + + mapReduce(inputs : List) : List> {static} + } + class Mapper { + + Mapper() + + map(input : String) : Map {static} + } + class Reducer { + + Reducer() + + reduce(grouped : Map>) : List> {static} + } + class Shuffler { + + Shuffler() + + shuffleAndSort(mapped : List>) : Map> {static} + } +} +@enduml \ No newline at end of file diff --git a/map-reduce/etc/mapreduce-flowchart.png b/map-reduce/etc/mapreduce-flowchart.png new file mode 100644 index 000000000000..dade8f7ccdf2 Binary files /dev/null and b/map-reduce/etc/mapreduce-flowchart.png differ diff --git a/map-reduce/pom.xml b/map-reduce/pom.xml new file mode 100644 index 000000000000..4778f1bdb7ca --- /dev/null +++ b/map-reduce/pom.xml @@ -0,0 +1,62 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + map-reduce + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.mapreduce.Main + + + + + + + + + diff --git a/map-reduce/src/main/java/com/iluwatar/Main.java b/map-reduce/src/main/java/com/iluwatar/Main.java new file mode 100644 index 000000000000..98e6381235ae --- /dev/null +++ b/map-reduce/src/main/java/com/iluwatar/Main.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +/** + * The Main class serves as the entry point for executing the MapReduce program. It processes a list + * of text inputs, applies the MapReduce pattern, and prints the results. + */ +public class Main { + private static final Logger logger = Logger.getLogger(Main.class.getName()); + + /** + * The main method initiates the MapReduce process and displays the word count results. + * + * @param args Command-line arguments (not used). + */ + public static void main(String[] args) { + List inputs = + Arrays.asList( + "Hello world hello", "MapReduce is fun", "Hello from the other side", "Hello world"); + List> result = MapReduce.mapReduce(inputs); + for (Map.Entry entry : result) { + logger.info(entry.getKey() + ": " + entry.getValue()); + } + } +} diff --git a/map-reduce/src/main/java/com/iluwatar/MapReduce.java b/map-reduce/src/main/java/com/iluwatar/MapReduce.java new file mode 100644 index 000000000000..49b6f0a1d3d6 --- /dev/null +++ b/map-reduce/src/main/java/com/iluwatar/MapReduce.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * The MapReduce class orchestrates the MapReduce process, calling the Mapper, Shuffler, and Reducer + * components. + */ +public class MapReduce { + private MapReduce() { + throw new UnsupportedOperationException( + "MapReduce is a utility class and cannot be instantiated."); + } + + /** + * Executes the MapReduce process on the given list of input strings. + * + * @param inputs List of input strings to be processed. + * @return A list of word counts sorted in descending order. + */ + public static List> mapReduce(List inputs) { + List> mapped = new ArrayList<>(); + for (String input : inputs) { + mapped.add(Mapper.map(input)); + } + + Map> grouped = Shuffler.shuffleAndSort(mapped); + + return Reducer.reduce(grouped); + } +} diff --git a/map-reduce/src/main/java/com/iluwatar/Mapper.java b/map-reduce/src/main/java/com/iluwatar/Mapper.java new file mode 100644 index 000000000000..c048c5e4a6d1 --- /dev/null +++ b/map-reduce/src/main/java/com/iluwatar/Mapper.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; + +import java.util.HashMap; +import java.util.Map; + +/** + * The Mapper class is responsible for processing an input string and generating a map of word + * occurrences. + */ +public class Mapper { + private Mapper() { + throw new UnsupportedOperationException( + "Mapper is a utility class and cannot be instantiated."); + } + + /** + * Splits a given input string into words and counts their occurrences. + * + * @param input The input string to be mapped. + * @return A map where keys are words and values are their respective counts. + */ + public static Map map(String input) { + Map wordCount = new HashMap<>(); + String[] words = input.split("\\s+"); + for (String word : words) { + word = word.toLowerCase().replaceAll("[^a-z]", ""); + if (!word.isEmpty()) { + wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); + } + } + return wordCount; + } +} diff --git a/map-reduce/src/main/java/com/iluwatar/Reducer.java b/map-reduce/src/main/java/com/iluwatar/Reducer.java new file mode 100644 index 000000000000..fbfc8d09d61a --- /dev/null +++ b/map-reduce/src/main/java/com/iluwatar/Reducer.java @@ -0,0 +1,56 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** The Reducer class is responsible for aggregating word counts from the shuffled data. */ +public class Reducer { + private Reducer() { + throw new UnsupportedOperationException( + "Reducer is a utility class and cannot be instantiated."); + } + + /** + * Sums the occurrences of each word and sorts the results in descending order. + * + * @param grouped A map where keys are words and values are lists of their occurrences. + * @return A sorted list of word counts in descending order. + */ + public static List> reduce(Map> grouped) { + Map reduced = new HashMap<>(); + for (Map.Entry> entry : grouped.entrySet()) { + reduced.put(entry.getKey(), entry.getValue().stream().mapToInt(Integer::intValue).sum()); + } + + List> result = new ArrayList<>(reduced.entrySet()); + result.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); + return result; + } +} diff --git a/map-reduce/src/main/java/com/iluwatar/Shuffler.java b/map-reduce/src/main/java/com/iluwatar/Shuffler.java new file mode 100644 index 000000000000..cf58bc9019e3 --- /dev/null +++ b/map-reduce/src/main/java/com/iluwatar/Shuffler.java @@ -0,0 +1,56 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** The Shuffler class is responsible for grouping word occurrences from multiple mappers. */ +public class Shuffler { + + private Shuffler() { + throw new UnsupportedOperationException( + "Shuffler is a utility class and cannot be instantiated."); + } + + /** + * Merges multiple word count maps into a single grouped map. + * + * @param mapped List of maps containing word counts from the mapping phase. + * @return A map where keys are words and values are lists of their occurrences across inputs. + */ + public static Map> shuffleAndSort(List> mapped) { + Map> grouped = new HashMap<>(); + for (Map map : mapped) { + for (Map.Entry entry : map.entrySet()) { + grouped.putIfAbsent(entry.getKey(), new ArrayList<>()); + grouped.get(entry.getKey()).add(entry.getValue()); + } + } + return grouped; + } +} diff --git a/map-reduce/src/test/java/com/iluwatar/MapReduceTest.java b/map-reduce/src/test/java/com/iluwatar/MapReduceTest.java new file mode 100644 index 000000000000..6abaa2142c7d --- /dev/null +++ b/map-reduce/src/test/java/com/iluwatar/MapReduceTest.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; +import org.junit.jupiter.api.Test; + +class MapReduceTest { + + @Test + void testMapReduce() { + List inputs = + Arrays.asList("Hello world hello", "MapReduce is fun", "Hello from the other side"); + + List> result = MapReduce.mapReduce(inputs); + + assertEquals("hello", result.get(0).getKey()); // hello = 3 + assertEquals(3, result.get(0).getValue()); + assertEquals(1, result.get(1).getValue()); + } +} diff --git a/map-reduce/src/test/java/com/iluwatar/MapperTest.java b/map-reduce/src/test/java/com/iluwatar/MapperTest.java new file mode 100644 index 000000000000..7ebd48407042 --- /dev/null +++ b/map-reduce/src/test/java/com/iluwatar/MapperTest.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Map; +import org.junit.jupiter.api.Test; + +class MapperTest { + + @Test + void testMapSingleSentence() { + String input = "Hello world hello"; + Map result = Mapper.map(input); + + assertEquals(2, result.get("hello")); + assertEquals(1, result.get("world")); + } + + @Test + void testMapCaseInsensitivity() { + String input = "HeLLo WoRLd hello WORLD"; + Map result = Mapper.map(input); + + assertEquals(2, result.get("hello")); + assertEquals(2, result.get("world")); + } +} diff --git a/map-reduce/src/test/java/com/iluwatar/ReducerTest.java b/map-reduce/src/test/java/com/iluwatar/ReducerTest.java new file mode 100644 index 000000000000..903b3828c8d7 --- /dev/null +++ b/map-reduce/src/test/java/com/iluwatar/ReducerTest.java @@ -0,0 +1,74 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; +import org.junit.jupiter.api.Test; + +class ReducerTest { + + @Test + void testReduceWithMultipleWords() { + Map> input = new HashMap<>(); + input.put("apple", Arrays.asList(2, 3, 1)); + input.put("banana", Arrays.asList(1, 1)); + input.put("cherry", List.of(4)); + + List> result = Reducer.reduce(input); + + assertEquals(3, result.size()); + assertEquals("apple", result.get(0).getKey()); + assertEquals(6, result.get(0).getValue()); + assertEquals("cherry", result.get(1).getKey()); + assertEquals(4, result.get(1).getValue()); + assertEquals("banana", result.get(2).getKey()); + assertEquals(2, result.get(2).getValue()); + } + + @Test + void testReduceWithEmptyInput() { + Map> input = new HashMap<>(); + + List> result = Reducer.reduce(input); + + assertTrue(result.isEmpty()); + } + + @Test + void testReduceWithTiedCounts() { + Map> input = new HashMap<>(); + input.put("tie1", Arrays.asList(2, 2)); + input.put("tie2", Arrays.asList(1, 3)); + + List> result = Reducer.reduce(input); + + assertEquals(2, result.size()); + assertEquals(4, result.get(0).getValue()); + assertEquals(4, result.get(1).getValue()); + // Note: The order of tie1 and tie2 is not guaranteed in case of a tie + } +} diff --git a/map-reduce/src/test/java/com/iluwatar/ShufflerTest.java b/map-reduce/src/test/java/com/iluwatar/ShufflerTest.java new file mode 100644 index 000000000000..3362f7ea20a5 --- /dev/null +++ b/map-reduce/src/test/java/com/iluwatar/ShufflerTest.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; +import org.junit.jupiter.api.Test; + +class ShufflerTest { + + @Test + void testShuffleAndSort() { + List> mappedData = + Arrays.asList(Map.of("hello", 1, "world", 2), Map.of("hello", 2, "java", 1)); + + Map> grouped = Shuffler.shuffleAndSort(mappedData); + + assertEquals(Arrays.asList(1, 2), grouped.get("hello")); + assertEquals(List.of(2), grouped.get("world")); + assertEquals(List.of(1), grouped.get("java")); + } +} diff --git a/eip-message-channel/.gitignore b/marker-interface/.gitignore similarity index 100% rename from eip-message-channel/.gitignore rename to marker-interface/.gitignore diff --git a/marker-interface/README.md b/marker-interface/README.md new file mode 100644 index 000000000000..c272093e0d9a --- /dev/null +++ b/marker-interface/README.md @@ -0,0 +1,132 @@ +--- +title: "Marker Interface Pattern in Java: Defining Behavior Through Empty Interfaces" +shortTitle: Marker Interface +description: "Explore the Marker Interface pattern in Java, its benefits, real-world examples, and common uses. Learn how to use marker interfaces for metadata and special class behaviors." +category: Structural +language: en +tag: + - Encapsulation + - Interface + - Polymorphism +--- + +## Also known as + +* Marker +* Tagging Interface + +## Intent of Marker Interface Design Pattern + +The Marker Interface pattern in Java is used to convey metadata about a class in a type-safe manner. Interfaces in Java that have no method declarations are known as marker interfaces. They are used to indicate that a class implementing such an interface possesses some special behavior or capability. + +## Detailed Explanation of Marker Interface Pattern with Real-World Examples + +Real-world example + +> Consider a scenario in a Java library system where certain books are rare and need special handling procedures, such as restricted check-outs or specific storage conditions. Analogous to the Marker Interface pattern, we could have a marker interface called `RareBook`. Books in the library catalog that implement this interface are flagged as requiring special treatment but don't necessarily have different methods from other books. +> +> When a library staff member processes transactions or handles storage, the system checks if a book implements the `RareBook` interface. If it does, the system automatically enforces rules like "Do not allow check-outs for more than three days" or "Store in a temperature-controlled environment." This use of the marker interface effectively communicates special requirements without altering how books are generally managed, serving simply as a marker for special conditions. + +In plain words + +> The Marker Interface design pattern in Java uses empty interfaces to signal or define certain properties and behaviors of objects in a type-safe way, without requiring specific method implementations. + +Wikipedia says + +> The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata. +> +> To use this pattern, a class implements a marker interface (also called tagging interface) which is an empty interface, and methods that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. Hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. + +Flowchart + +![Marker Interface flowchart](./etc/marker-interface-flowchart.png) + +## Programmatic Example of Marker Interface Pattern in Java + +The Marker Interface design pattern is a design pattern in computer science that is used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata. + +In the given Java code example, the Permission interface acts as a marker interface. Classes that implement this interface are marked as having special permissions. Let's break down the code to understand how this pattern is implemented. + +First, we define the `Permission` interface. This interface doesn't have any methods, making it a marker interface. + +```java +public interface Permission { + // This is a marker interface and does not contain any methods +} +``` + +Next, we have two classes `Guard` and `Thief` that represent different types of characters in our application. The `Guard` class implements the `Permission` interface, indicating that objects of this class have special permissions. + +```java +public class Guard implements Permission { + public void enter() { + // Implementation of enter method + } +} +``` + +On the other hand, the `Thief` class does not implement the `Permission` interface, indicating that objects of this class do not have special permissions. + +```java +public class Thief { + public void steal() { + // Implementation of steal method + } + + public void doNothing() { + // Implementation of doNothing method + } +} +``` + +In the `main` method of the `App` class, we create instances of `Guard` and `Thief`. We then use the `instanceof` operator to check if these objects implement the `Permission` interface. If an object implements the `Permission` interface, it is allowed to perform certain actions. If not, it is restricted from performing those actions. + +```java +public class App { + public static void main(String[] args) { + final var logger = LoggerFactory.getLogger(App.class); + var guard = new Guard(); + var thief = new Thief(); + + if (guard instanceof Permission) { + guard.enter(); + } else { + logger.info("You have no permission to enter, please leave this area"); + } + + if (thief instanceof Permission) { + thief.steal(); + } else { + thief.doNothing(); + } + } +} +``` + +In this way, the Marker Interface pattern allows us to associate metadata (in this case, special permissions) with a class in a type-safe manner. + +## When to Use the Marker Interface Pattern in Java + +Marker interfaces are applicable in scenarios where you want to impose a special behavior or capability on a class, but don't want to force the class to define specific methods. This pattern is commonly used to indicate that a class conforms to a particular contract without needing to implement methods. + +## Real-World Applications of Marker Interface Pattern in Java + +* java.io.Serializable: Classes that implement this interface are capable of being serialized by the Java runtime. +* java.lang.Cloneable: Classes that implement this interface can be cloned using the clone method in Java. + +## Benefits and Trade-offs of Marker Interface Pattern + +Benefits: + +* Enables type checking at compile time, allowing developers to use polymorphism to write cleaner and more flexible code. +* Allows the addition of metadata to classes without altering their actual behavior. + +Trade-offs: + +* Can lead to empty interfaces in the codebase, which some may consider as not clean or clear in purpose. +* Does not enforce any method implementations, which can lead to runtime errors if not properly handled. + +## References and Credits + +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525) diff --git a/marker-interface/etc/MarkerDiagram.png b/marker-interface/etc/MarkerDiagram.png new file mode 100644 index 000000000000..6ed4f9c56780 Binary files /dev/null and b/marker-interface/etc/MarkerDiagram.png differ diff --git a/marker/etc/MarkerDiagram.ucls b/marker-interface/etc/MarkerDiagram.ucls similarity index 100% rename from marker/etc/MarkerDiagram.ucls rename to marker-interface/etc/MarkerDiagram.ucls diff --git a/marker-interface/etc/marker-interface-flowchart.png b/marker-interface/etc/marker-interface-flowchart.png new file mode 100644 index 000000000000..289a2cdb6233 Binary files /dev/null and b/marker-interface/etc/marker-interface-flowchart.png differ diff --git a/marker-interface/etc/marker-interface.urm.puml b/marker-interface/etc/marker-interface.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/marker-interface/etc/marker-interface.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/marker-interface/etc/marker.urm.puml b/marker-interface/etc/marker.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/marker-interface/etc/marker.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/marker-interface/pom.xml b/marker-interface/pom.xml new file mode 100644 index 000000000000..f564d6756133 --- /dev/null +++ b/marker-interface/pom.xml @@ -0,0 +1,76 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + marker-interface + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.hamcrest + hamcrest-core + 3.0 + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + App + + + + + + + + + diff --git a/marker-interface/src/main/java/App.java b/marker-interface/src/main/java/App.java new file mode 100644 index 000000000000..c1f36664b495 --- /dev/null +++ b/marker-interface/src/main/java/App.java @@ -0,0 +1,68 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.slf4j.LoggerFactory; + +/** + * Created by Alexis on 28-Apr-17. With Marker interface idea is to make empty interface and extend + * it. Basically it is just to identify the special objects from normal objects. Like in case of + * serialization , objects that need to be serialized must implement serializable interface (it is + * empty interface) and down the line writeObject() method must be checking if it is an instance of + * serializable or not. + * + *

    Marker interface vs annotation Marker interfaces and marker annotations both have their uses, + * neither of them is obsolete or always better than the other one. If you want to define a type + * that does not have any new methods associated with it, a marker interface is the way to go. If + * you want to mark program elements other than classes and interfaces, to allow for the possibility + * of adding more information to the marker in the future, or to fit the marker into a framework + * that already makes heavy use of annotation types, then a marker annotation is the correct choice + */ +public class App { + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + final var logger = LoggerFactory.getLogger(App.class); + var guard = new Guard(); + var thief = new Thief(); + + //noinspection ConstantConditions + if (guard instanceof Permission) { + guard.enter(); + } else { + logger.info("You have no permission to enter, please leave this area"); + } + + //noinspection ConstantConditions + if (thief instanceof Permission) { + thief.steal(); + } else { + thief.doNothing(); + } + } +} diff --git a/marker/src/main/java/Guard.java b/marker-interface/src/main/java/Guard.java similarity index 80% rename from marker/src/main/java/Guard.java rename to marker-interface/src/main/java/Guard.java index 4dd2a48872e6..469ee2e7734f 100644 --- a/marker/src/main/java/Guard.java +++ b/marker-interface/src/main/java/Guard.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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,18 +22,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * Class defining Guard - */ +/** Class defining Guard. */ +@Slf4j public class Guard implements Permission { - private static final Logger LOGGER = LoggerFactory.getLogger(Guard.class); - - protected static void enter() { - + protected void enter() { LOGGER.info("You can enter"); } } diff --git a/marker/src/main/java/Permission.java b/marker-interface/src/main/java/Permission.java similarity index 78% rename from marker/src/main/java/Permission.java rename to marker-interface/src/main/java/Permission.java index 2a85b336304d..bdaf18375e91 100644 --- a/marker/src/main/java/Permission.java +++ b/marker-interface/src/main/java/Permission.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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,9 +22,5 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -/** - * Interface without any methods - * Marker interface is based on that assumption - */ -public interface Permission { -} +/** Interface without any methods Marker interface is based on that assumption. */ +public interface Permission {} diff --git a/marker-interface/src/main/java/Thief.java b/marker-interface/src/main/java/Thief.java new file mode 100644 index 000000000000..ae6bec874671 --- /dev/null +++ b/marker-interface/src/main/java/Thief.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 lombok.extern.slf4j.Slf4j; + +/** Class defining Thief. */ +@Slf4j +public class Thief { + + protected void steal() { + LOGGER.info("Steal valuable items"); + } + + protected void doNothing() { + LOGGER.info("Pretend nothing happened and just leave"); + } +} diff --git a/marker-interface/src/test/java/AppTest.java b/marker-interface/src/test/java/AppTest.java new file mode 100644 index 000000000000..4600eed4a063 --- /dev/null +++ b/marker-interface/src/test/java/AppTest.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application test */ +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/marker/src/test/java/GuardTest.java b/marker-interface/src/test/java/GuardTest.java similarity index 82% rename from marker/src/test/java/GuardTest.java rename to marker-interface/src/test/java/GuardTest.java index cadd82f827a9..7ae34f63d026 100644 --- a/marker/src/test/java/GuardTest.java +++ b/marker-interface/src/test/java/GuardTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014 Ilkka Seppälä + * Copyright © 2014-2022 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,20 +22,17 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -import org.junit.jupiter.api.Test; - import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; -/** - * Guard test - */ -public class GuardTest { +import org.junit.jupiter.api.Test; + +/** Guard test */ +class GuardTest { @Test - public void testGuard() { - Guard guard = new Guard(); + void testGuard() { + var guard = new Guard(); assertThat(guard, instanceOf(Permission.class)); } -} \ No newline at end of file +} diff --git a/marker-interface/src/test/java/ThiefTest.java b/marker-interface/src/test/java/ThiefTest.java new file mode 100644 index 000000000000..130dd12fcb25 --- /dev/null +++ b/marker-interface/src/test/java/ThiefTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +/** Thief test */ +class ThiefTest { + @Test + void testThief() { + var thief = new Thief(); + assertThat(thief, not(instanceOf(Permission.class))); + } +} diff --git a/marker/.gitignore b/marker/.gitignore deleted file mode 100644 index b83d22266ac8..000000000000 --- a/marker/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/marker/README.md b/marker/README.md deleted file mode 100644 index 6f5fc1e91c7a..000000000000 --- a/marker/README.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -layout: pattern -title: Marker Interface -folder: marker -permalink: /patterns/marker/ -categories: Other -tags: - - Java - - Difficulty-Beginner ---- - -## Intent -Using empty interfaces as markers to distinguish special treated objects. - -![alt text](./etc/MarkerDiagram.png "Marker Interface") - -## Applicability -Use the Marker Interface pattern when - -* you want to identify the special objects from normal objects (to treat them differently) -* you want to mark that some object is available for certain sort of operations - -## Real world examples - -* [javase.8.docs.api.java.io.Serializable](https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html) -* [javase.8.docs.api.java.lang.Cloneable](https://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html) - -## Credits - -* [Effective Java 2nd Edition by Joshua Bloch](https://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683) diff --git a/marker/pom.xml b/marker/pom.xml deleted file mode 100644 index 138ab0c30612..000000000000 --- a/marker/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - java-design-patterns - com.iluwatar - 1.20.0-SNAPSHOT - - 4.0.0 - - marker - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.hamcrest - hamcrest-core - 1.3 - test - - - - - diff --git a/marker/src/main/java/App.java b/marker/src/main/java/App.java deleted file mode 100644 index d8fd54ecb3b9..000000000000 --- a/marker/src/main/java/App.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * 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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Created by Alexis on 28-Apr-17. - * With Marker interface idea is to make empty interface and extend it. - * Basically it is just to identify the special objects from normal objects. - * Like in case of serialization , objects that need to be serialized must implement serializable interface - * (it is empty interface) and down the line writeObject() method must be checking - * if it is a instance of serializable or not. - *

    - * Marker interface vs annotation - * Marker interfaces and marker annotations both have their uses, - * neither of them is obsolete or always better then the other one. - * If you want to define a type that does not have any new methods associated with it, - * a marker interface is the way to go. - * If you want to mark program elements other than classes and interfaces, - * to allow for the possibility of adding more information to the marker in the future, - * or to fit the marker into a framework that already makes heavy use of annotation types, - * then a marker annotation is the correct choice - */ -public class App { - - /** - * Program entry point - * - * @param args command line args - */ - public static void main(String[] args) { - - final Logger logger = LoggerFactory.getLogger(App.class); - Guard guard = new Guard(); - Thief thief = new Thief(); - - if (guard instanceof Permission) { - guard.enter(); - } else { - logger.info("You have no permission to enter, please leave this area"); - } - - if (thief instanceof Permission) { - thief.steal(); - } else { - thief.doNothing(); - } - } -} - diff --git a/marker/src/main/java/Thief.java b/marker/src/main/java/Thief.java deleted file mode 100644 index b8d6464e51ac..000000000000 --- a/marker/src/main/java/Thief.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class defining Thief - */ -public class Thief { - - private static final Logger LOGGER = LoggerFactory.getLogger(Thief.class); - - protected static void steal() { - LOGGER.info("Steal valuable items"); - } - - protected static void doNothing() { - LOGGER.info("Pretend nothing happened and just leave"); - } -} diff --git a/marker/src/test/java/AppTest.java b/marker/src/test/java/AppTest.java deleted file mode 100644 index 856635007c35..000000000000 --- a/marker/src/test/java/AppTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 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 org.junit.jupiter.api.Test; - -/** - * Application test - */ -public class AppTest { - - @Test - public void test() { - String[] args = {}; - App.main(args); - } -} diff --git a/marker/src/test/java/ThiefTest.java b/marker/src/test/java/ThiefTest.java deleted file mode 100644 index 56492334c957..000000000000 --- a/marker/src/test/java/ThiefTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 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 org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertFalse; - -/** - * Thief test - */ -public class ThiefTest { - @Test - public void testThief() { - Thief thief = new Thief(); - assertFalse(thief instanceof Permission); - } -} \ No newline at end of file diff --git a/master-worker/README.md b/master-worker/README.md new file mode 100644 index 000000000000..70885952240d --- /dev/null +++ b/master-worker/README.md @@ -0,0 +1,153 @@ +--- +title: "Master-Worker Pattern in Java: Coordinating Concurrent Processing with Ease" +shortTitle: Master-Worker +description: "Discover the Master-Worker design pattern in Java. Learn how it improves concurrency, scalability, and performance through parallel task processing. Includes real-world examples and code snippets." +category: Concurrency +language: en +tag: + - Multithreading + - Performance + - Scalability +--- + +## Also known as + +* Master-Slave +* Controller-Worker + +## Intent of Master-Worker Design Pattern + +The Master-Worker design pattern is designed to perform parallel computations by distributing tasks between a master process and multiple worker processes. This pattern enhances concurrency, performance, and scalability in software systems. + +## Detailed Explanation of Master-Worker Pattern with Real-World Examples + +Real-world example + +> The Master-Worker pattern optimizes parallel task processing and throughput. For instance, in a restaurant kitchen, the head chef (master) delegates tasks to line cooks (workers), who work concurrently to prepare the order. The head chef receives the orders from the dining area and breaks down each order into specific tasks, such as grilling meat, preparing salads, and cooking desserts. Each task is assigned to a different line cook based on their expertise and current workload. The line cooks work in parallel to prepare their portion of the order, while the head chef oversees the process, ensuring everything is prepared correctly and timely. Once each component of the order is ready, the head chef gathers all parts, gives them a final check, and then plates the dishes for service. This kitchen operation mimics the Master-Worker pattern by distributing and managing tasks to optimize efficiency and output. + +In plain words + +> The Master-Worker pattern involves a master process delegating tasks to multiple worker processes, which execute them concurrently and report back, optimizing parallel task processing and throughput. + +Wikipedia says + +> Master–slave is a model of asymmetric communication or control where one device or process (the master) controls one or more other devices or processes (the slaves) and serves as their communication hub. In some systems, a master is selected from a group of eligible devices, with the other devices acting in the role of slaves. + +Sequence diagram + +![Master-Worker sequence diagram](./etc/master-worker-sequence-diagram.png) + +## Programmatic Example of Master-Worker Pattern in Java + +In the provided code, the `MasterWorker` class initiates the concurrent computation process. The `Master` class divides the work among `Worker` objects, each performing its task in parallel, thus optimizing task processing and enhancing system efficiency. + +```java +// The MasterWorker class acts as the main entry point for the Master-Worker system. +public class MasterWorker { + private Master master; + + public MasterWorker(Master master) { + this.master = master; + } + + public Result getResult(Input input) { + return master.computeResult(input); + } +} +``` + +In this code, the `MasterWorker` class is initialized with a `Master` object. The `getResult` method is used to start the computation process. + +```java +// The Master class is responsible for dividing the work among the workers. +public abstract class Master { + protected List workers; + + public Master(List workers) { + this.workers = workers; + } + + public abstract Result computeResult(Input input); +} +``` + +The `Master` class has a list of `Worker` objects. The `computeResult` method is abstract and should be implemented in a subclass to define how the work is divided and how the results are aggregated. + +```java +// The Worker class is responsible for performing the actual computation. +public abstract class Worker extends Thread { + protected Input input; + + public void setInput(Input input) { + this.input = input; + } + + public abstract Result compute(); +} +``` + +The `Worker` class extends `Thread`, allowing it to perform computations in parallel. The `compute` method is abstract and should be implemented in a subclass to define the actual computation logic. + +```java +// The Input and Result classes are used to encapsulate the input data and the result data. +public abstract class Input { + public final T data; + + public Input(T data) { + this.data = data; + } + + public abstract List> divideData(int num); +} + +public abstract class Result { + public final T data; + + public Result(T data) { + this.data = data; + } +} +``` + +The `Input` class has a `divideData` method that is used to divide the input data into subtasks. The `Result` class simply encapsulates the result data. + +## When to Use the Master-Worker Pattern in Java + +* Suitable for scenarios where a task can be decomposed into smaller, independent tasks. +* Useful in applications requiring concurrent execution to enhance performance. +* Applicable in distributed computing where tasks need to be processed by multiple processors or machines. + +## Master-Worker Pattern Java Tutorials + +* [Master-Worker Pattern (Gigaspaces)](https://docs.gigaspaces.com/sbp/master-worker-pattern.html) + +## Real-World Applications of Master-Worker Pattern in Java + +* Implemented in distributed systems to manage tasks across different computing resources. +* Used in server architectures to process multiple client requests simultaneously. +* Utilized in scientific computation frameworks where large datasets require parallel processing. + +## Benefits and Trade-offs of Master-Worker Pattern + +Benefits: + +* Enhances performance by parallelizing tasks. +* Increases responsiveness of systems handling large volumes of requests. +* Provides a clear separation of concerns between task coordination and task execution, simplifying design. + +Trade-offs: + +* Complexity in managing synchronization and state consistency between master and workers. +* Overhead of managing communication between master and workers, especially in distributed environments. + +## Related Java Design Patterns + +* Task Parallelism and Data Parallelism: Master-Worker utilizes these patterns to divide work into tasks or data segments. +* [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Similar in structure but focuses on balancing production and consumption rates; Master-Worker is more about task distribution and aggregation. +* [Pipeline](https://java-design-patterns.com/patterns/pipeline/): Both organize processing steps but Pipeline arranges them linearly whereas Master-Worker may not impose such a sequence. + +## References and Credits + +* [Distributed Systems: Principles and Paradigms](https://amzn.to/3UN2vbH) +* [Java Concurrency in Practice](https://amzn.to/4aRMruW) +* [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) diff --git a/master-worker/etc/master-worker-pattern.urm.png b/master-worker/etc/master-worker-pattern.urm.png new file mode 100644 index 000000000000..a4c7a16d3ac9 Binary files /dev/null and b/master-worker/etc/master-worker-pattern.urm.png differ diff --git a/master-worker/etc/master-worker-pattern.urm.puml b/master-worker/etc/master-worker-pattern.urm.puml new file mode 100644 index 000000000000..b3b5add30671 --- /dev/null +++ b/master-worker/etc/master-worker-pattern.urm.puml @@ -0,0 +1,78 @@ +@startuml +package com.iluwatar.masterworker.system.systemmaster { + class ArrayTransposeMaster { + + ArrayTransposeMaster(numOfWorkers : int) + ~ aggregateData() : ArrayResult + ~ setWorkers(num : int) : ArrayList + } + abstract class Master { + - allResultData : Hashtable> + - expectedNumResults : int + - finalResult : Result + - numOfWorkers : int + - workers : ArrayList + ~ Master(numOfWorkers : int) + ~ aggregateData() : Result {abstract} + - collectResult(data : Result, workerId : int) + - divideWork(input : Input) + + doWork(input : Input) + ~ getAllResultData() : Hashtable> + ~ getExpectedNumResults() : int + + getFinalResult() : Result + ~ getWorkers() : ArrayList + + receiveData(data : Result, w : Worker) + ~ setWorkers(int) : ArrayList {abstract} + } +} +package com.iluwatar.masterworker.system { + class ArrayTransposeMasterWorker { + + ArrayTransposeMasterWorker() + ~ setMaster(numOfWorkers : int) : Master + } + abstract class MasterWorker { + - master : Master + + MasterWorker(numOfWorkers : int) + + getResult(input : Input) : Result + ~ setMaster(int) : Master {abstract} + } +} +package com.iluwatar.masterworker { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class ArrayInput { + + ArrayInput(data : int[][]) + + divideData(num : int) : ArrayList> + ~ makeDivisions(data : int[][], num : int) : int[] {static} + } + class ArrayResult { + + ArrayResult(data : int[][]) + } + class ArrayUtilityMethods { + - LOGGER : Logger {static} + - RANDOM : Random {static} + + ArrayUtilityMethods() + + arraysSame(a1 : int[], a2 : int[]) : boolean {static} + + createRandomIntMatrix(rows : int, columns : int) : int[][] {static} + + matricesSame(m1 : int[][], m2 : int[][]) : boolean {static} + + printMatrix(matrix : int[][]) {static} + } + abstract class Input { + + data : T + + Input(data : T) + + divideData(int) : ArrayList> {abstract} + } + abstract class Result { + + data : T + + Result(data : T) + } +} +Master --> "-finalResult" Result +MasterWorker --> "-master" Master +ArrayInput --|> Input +ArrayResult --|> Result +ArrayTransposeMasterWorker --|> MasterWorker +ArrayTransposeMaster --|> Master +@enduml \ No newline at end of file diff --git a/master-worker/etc/master-worker-sequence-diagram.png b/master-worker/etc/master-worker-sequence-diagram.png new file mode 100644 index 000000000000..e2e28a262646 Binary files /dev/null and b/master-worker/etc/master-worker-sequence-diagram.png differ diff --git a/master-worker/etc/master-worker.urm.puml b/master-worker/etc/master-worker.urm.puml new file mode 100644 index 000000000000..d5fc9e5d0967 --- /dev/null +++ b/master-worker/etc/master-worker.urm.puml @@ -0,0 +1,78 @@ +@startuml +package com.iluwatar.masterworker.system.systemmaster { + class ArrayTransposeMaster { + + ArrayTransposeMaster(numOfWorkers : int) + ~ aggregateData() : ArrayResult + ~ setWorkers(num : int) : ArrayList + } + abstract class Master { + - allResultData : Hashtable> + - expectedNumResults : int + - finalResult : Result + - numOfWorkers : int + - workers : List + ~ Master(numOfWorkers : int) + ~ aggregateData() : Result {abstract} + - collectResult(data : Result, workerId : int) + - divideWork(input : Input) + + doWork(input : Input) + ~ getAllResultData() : Hashtable> + ~ getExpectedNumResults() : int + + getFinalResult() : Result + ~ getWorkers() : List + + receiveData(data : Result, w : Worker) + ~ setWorkers(int) : List {abstract} + } +} +package com.iluwatar.masterworker.system { + class ArrayTransposeMasterWorker { + + ArrayTransposeMasterWorker() + ~ setMaster(numOfWorkers : int) : Master + } + abstract class MasterWorker { + - master : Master + + MasterWorker(numOfWorkers : int) + + getResult(input : Input) : Result + ~ setMaster(int) : Master {abstract} + } +} +package com.iluwatar.masterworker { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class ArrayInput { + + ArrayInput(data : int[][]) + + divideData(num : int) : List> + ~ makeDivisions(data : int[][], num : int) : int[] {static} + } + class ArrayResult { + + ArrayResult(data : int[][]) + } + class ArrayUtilityMethods { + - LOGGER : Logger {static} + - RANDOM : SecureRandom {static} + + ArrayUtilityMethods() + + arraysSame(a1 : int[], a2 : int[]) : boolean {static} + + createRandomIntMatrix(rows : int, columns : int) : int[][] {static} + + matricesSame(m1 : int[][], m2 : int[][]) : boolean {static} + + printMatrix(matrix : int[][]) {static} + } + abstract class Input { + + data : T + + Input(data : T) + + divideData(int) : List> {abstract} + } + abstract class Result { + + data : T + + Result(data : T) + } +} +Master --> "-finalResult" Result +MasterWorker --> "-master" Master +ArrayInput --|> Input +ArrayResult --|> Result +ArrayTransposeMasterWorker --|> MasterWorker +ArrayTransposeMaster --|> Master +@enduml \ No newline at end of file diff --git a/master-worker/pom.xml b/master-worker/pom.xml new file mode 100644 index 000000000000..630fbb6f5b84 --- /dev/null +++ b/master-worker/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + master-worker + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.masterworker.App + + + + + + + + + diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/App.java b/master-worker/src/main/java/com/iluwatar/masterworker/App.java new file mode 100644 index 000000000000..fbe31eca8b76 --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/App.java @@ -0,0 +1,80 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker; + +import com.iluwatar.masterworker.system.ArrayTransposeMasterWorker; +import com.iluwatar.masterworker.system.MasterWorker; +import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster; +import com.iluwatar.masterworker.system.systemmaster.Master; +import com.iluwatar.masterworker.system.systemworkers.ArrayTransposeWorker; +import com.iluwatar.masterworker.system.systemworkers.Worker; +import lombok.extern.slf4j.Slf4j; + +/** + * The Master-Worker pattern is used when the problem at hand can be solved by + * dividing into multiple parts which need to go through the same computation and may need to be + * aggregated to get final result. Parallel processing is performed using a system consisting of a + * master and some number of workers, where a master divides the work among the workers, gets the + * result back from them and assimilates all the results to give final result. The only + * communication is between the master and the worker - none of the workers communicate among one + * another and the user only communicates with the master to get required job done. + * + *

    In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and + * {@link Worker} which have to be extended by the classes which will perform the specific job at + * hand (in this case finding transpose of matrix, done by {@link ArrayTransposeMasterWorker}, + * {@link ArrayTransposeMaster} and {@link ArrayTransposeWorker}). The Master class divides the work + * into parts to be given to the workers, collects the results from the workers and aggregates it + * when all workers have responded before returning the solution. The Worker class extends the + * Thread class to enable parallel processing, and does the work once the data has been received + * from the Master. The MasterWorker contains a reference to the Master class, gets the input from + * the App and passes it on to the Master. These 3 classes define the system which computes the + * result. We also have 2 abstract classes {@link Input} and {@link Result}, which contain the input + * data and result data respectively. The Input class also has an abstract method divideData which + * defines how the data is to be divided into segments. These classes are extended by {@link + * ArrayInput} and {@link ArrayResult}. + */ +@Slf4j +public class App { + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + var mw = new ArrayTransposeMasterWorker(); + var rows = 10; + var columns = 20; + var inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows, columns); + var input = new ArrayInput(inputMatrix); + var result = (ArrayResult) mw.getResult(input); + if (result != null) { + ArrayUtilityMethods.printMatrix(inputMatrix); + ArrayUtilityMethods.printMatrix(result.data); + } else { + LOGGER.info("Please enter non-zero input"); + } + } +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/ArrayInput.java b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayInput.java new file mode 100644 index 000000000000..3d492aa08089 --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayInput.java @@ -0,0 +1,82 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** Class ArrayInput extends abstract class {@link Input} and contains data of type int[][]. */ +public class ArrayInput extends Input { + + public ArrayInput(int[][] data) { + super(data); + } + + static int[] makeDivisions(int[][] data, int num) { + var initialDivision = data.length / num; // equally dividing + var divisions = new int[num]; + Arrays.fill(divisions, initialDivision); + if (initialDivision * num != data.length) { + var extra = data.length - initialDivision * num; + var l = 0; + // equally dividing extra among all parts + while (extra > 0) { + divisions[l] = divisions[l] + 1; + extra--; + if (l == num - 1) { + l = 0; + } else { + l++; + } + } + } + return divisions; + } + + @Override + public List> divideData(int num) { + if (this.data == null) { + return null; + } else { + var divisions = makeDivisions(this.data, num); + var result = new ArrayList>(num); + var rowsDone = 0; // number of rows divided so far + for (var i = 0; i < num; i++) { + var rows = divisions[i]; + if (rows != 0) { + var divided = new int[rows][this.data[0].length]; + System.arraycopy(this.data, rowsDone, divided, 0, rows); + rowsDone += rows; + var dividedInput = new ArrayInput(divided); + result.add(dividedInput); + } else { + break; // rest of divisions will also be 0 + } + } + return result; + } + } +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/ArrayResult.java b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayResult.java new file mode 100644 index 000000000000..fa99b5ce6c1f --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayResult.java @@ -0,0 +1,33 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker; + +/** Class ArrayResult extends abstract class {@link Result} and contains data of type int[][]. */ +public class ArrayResult extends Result { + + public ArrayResult(int[][] data) { + super(data); + } +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java new file mode 100644 index 000000000000..8d3e9e7904ad --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java @@ -0,0 +1,105 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker; + +import java.security.SecureRandom; +import lombok.extern.slf4j.Slf4j; + +/** Class ArrayUtilityMethods has some utility methods for matrices and arrays. */ +@Slf4j +public class ArrayUtilityMethods { + + private static final SecureRandom RANDOM = new SecureRandom(); + + /** + * Method arraysSame compares 2 arrays @param a1 and @param a2 and @return whether their values + * are equal (boolean). + */ + public static boolean arraysSame(int[] a1, int[] a2) { + // compares if 2 arrays have the same value + if (a1.length != a2.length) { + return false; + } else { + var answer = false; + for (var i = 0; i < a1.length; i++) { + if (a1[i] == a2[i]) { + answer = true; + } else { + answer = false; + break; + } + } + return answer; + } + } + + /** + * Method matricesSame compares 2 matrices @param m1 and @param m2 and @return whether their + * values are equal (boolean). + */ + public static boolean matricesSame(int[][] m1, int[][] m2) { + if (m1.length != m2.length) { + return false; + } else { + var answer = false; + for (var i = 0; i < m1.length; i++) { + if (arraysSame(m1[i], m2[i])) { + answer = true; + } else { + answer = false; + break; + } + } + return answer; + } + } + + /** + * Method createRandomIntMatrix creates a random matrix of size @param rows and @param columns. + * + * @return it (int[][]). + */ + public static int[][] createRandomIntMatrix(int rows, int columns) { + var matrix = new int[rows][columns]; + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + // filling cells in matrix + matrix[i][j] = RANDOM.nextInt(10); + } + } + return matrix; + } + + /** Method printMatrix prints input matrix @param matrix. */ + public static void printMatrix(int[][] matrix) { + // prints out int[][] + for (var ints : matrix) { + for (var j = 0; j < matrix[0].length; j++) { + LOGGER.info(ints[j] + " "); + } + LOGGER.info(""); + } + } +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/Input.java b/master-worker/src/main/java/com/iluwatar/masterworker/Input.java new file mode 100644 index 000000000000..4e7c73d8633e --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/Input.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker; + +import java.util.List; + +/** + * The abstract Input class, having 1 public field which contains input data, and abstract method + * divideData. + * + * @param T will be type of data. + */ +public abstract class Input { + + public final T data; + + public Input(T data) { + this.data = data; + } + + public abstract List> divideData(int num); +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/Result.java b/master-worker/src/main/java/com/iluwatar/masterworker/Result.java new file mode 100644 index 000000000000..cc0bd4682101 --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/Result.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker; + +/** + * The abstract Result class, which contains 1 public field containing result data. + * + * @param T will be type of data. + */ +public abstract class Result { + + public final T data; + + public Result(T data) { + this.data = data; + } +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java new file mode 100644 index 000000000000..0ebef7dd82ff --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java @@ -0,0 +1,44 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker.system; + +import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster; +import com.iluwatar.masterworker.system.systemmaster.Master; + +/** + * Class ArrayTransposeMasterWorker extends abstract class {@link MasterWorker} and specifically + * solves the problem of finding transpose of input array. + */ +public class ArrayTransposeMasterWorker extends MasterWorker { + + public ArrayTransposeMasterWorker() { + super(4); + } + + @Override + Master setMaster(int numOfWorkers) { + return new ArrayTransposeMaster(numOfWorkers); + } +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java new file mode 100644 index 000000000000..5f785ebff144 --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker.system; + +import com.iluwatar.masterworker.Input; +import com.iluwatar.masterworker.Result; +import com.iluwatar.masterworker.system.systemmaster.Master; + +/** The abstract MasterWorker class which contains reference to master. */ +public abstract class MasterWorker { + private final Master master; + + public MasterWorker(int numOfWorkers) { + this.master = setMaster(numOfWorkers); + } + + abstract Master setMaster(int numOfWorkers); + + public Result getResult(Input input) { + this.master.doWork(input); + return this.master.getFinalResult(); + } +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java new file mode 100644 index 000000000000..50ee1c2b16fe --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java @@ -0,0 +1,77 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker.system.systemmaster; + +import com.iluwatar.masterworker.ArrayResult; +import com.iluwatar.masterworker.system.systemworkers.ArrayTransposeWorker; +import com.iluwatar.masterworker.system.systemworkers.Worker; +import java.util.ArrayList; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * Class ArrayTransposeMaster extends abstract class {@link Master} and contains definition of + * aggregateData, which will obtain final result from all data obtained and for setWorkers. + */ +public class ArrayTransposeMaster extends Master { + public ArrayTransposeMaster(int numOfWorkers) { + super(numOfWorkers); + } + + @Override + ArrayList setWorkers(int num) { + // i+1 will be id + return IntStream.range(0, num) + .mapToObj(i -> new ArrayTransposeWorker(this, i + 1)) + .collect(Collectors.toCollection(() -> new ArrayList<>(num))); + } + + @Override + ArrayResult aggregateData() { + // number of rows in final result is number of rows in any of obtained results from workers + var allResultData = this.getAllResultData(); + var rows = ((ArrayResult) allResultData.elements().nextElement()).data.length; + var elements = allResultData.elements(); + var columns = 0; // columns = sum of number of columns in all results obtained from workers + while (elements.hasMoreElements()) { + columns += ((ArrayResult) elements.nextElement()).data[0].length; + } + var resultData = new int[rows][columns]; + var columnsDone = 0; // columns aggregated so far + var workers = this.getWorkers(); + for (var i = 0; i < this.getExpectedNumResults(); i++) { + // result obtained from ith worker + var worker = workers.get(i); + var workerId = worker.getWorkerId(); + var work = ((ArrayResult) allResultData.get(workerId)).data; + for (var m = 0; m < work.length; m++) { + // m = row number, n = columns number + System.arraycopy(work[m], 0, resultData[m], columnsDone, work[0].length); + } + columnsDone += work[0].length; + } + return new ArrayResult(resultData); + } +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java new file mode 100644 index 000000000000..791de82c9266 --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java @@ -0,0 +1,106 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker.system.systemmaster; + +import com.iluwatar.masterworker.Input; +import com.iluwatar.masterworker.Result; +import com.iluwatar.masterworker.system.systemworkers.Worker; +import java.util.Hashtable; +import java.util.List; +import lombok.Getter; + +/** + * The abstract Master class which contains private fields numOfWorkers (number of workers), workers + * (arraylist of workers), expectedNumResults (number of divisions of input data, same as expected + * number of results), allResultData (hashtable of results obtained from workers, mapped by their + * ids) and finalResult (aggregated from allResultData). + */ +public abstract class Master { + private final int numOfWorkers; + private final List workers; + private final Hashtable> allResultData; + private int expectedNumResults; + @Getter private Result finalResult; + + Master(int numOfWorkers) { + this.numOfWorkers = numOfWorkers; + this.workers = setWorkers(numOfWorkers); + this.expectedNumResults = 0; + this.allResultData = new Hashtable<>(numOfWorkers); + this.finalResult = null; + } + + Hashtable> getAllResultData() { + return this.allResultData; + } + + int getExpectedNumResults() { + return this.expectedNumResults; + } + + List getWorkers() { + return this.workers; + } + + abstract List setWorkers(int num); + + public void doWork(Input input) { + divideWork(input); + } + + private void divideWork(Input input) { + var dividedInput = input.divideData(numOfWorkers); + if (dividedInput != null) { + this.expectedNumResults = dividedInput.size(); + for (var i = 0; i < this.expectedNumResults; i++) { + // ith division given to ith worker in this.workers + this.workers.get(i).setReceivedData(this, dividedInput.get(i)); + this.workers.get(i).start(); + } + for (var i = 0; i < this.expectedNumResults; i++) { + try { + this.workers.get(i).join(); + } catch (InterruptedException e) { + System.err.println("Error while executing thread"); + } + } + } + } + + public void receiveData(Result data, Worker w) { + // check if we can receive... if yes: + collectResult(data, w.getWorkerId()); + } + + private void collectResult(Result data, int workerId) { + this.allResultData.put(workerId, data); + if (this.allResultData.size() == this.expectedNumResults) { + // all data received + this.finalResult = aggregateData(); + } + } + + abstract Result aggregateData(); +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java new file mode 100644 index 000000000000..0d83fd3eb1e3 --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java @@ -0,0 +1,56 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker.system.systemworkers; + +import com.iluwatar.masterworker.ArrayInput; +import com.iluwatar.masterworker.ArrayResult; +import com.iluwatar.masterworker.system.systemmaster.Master; + +/** + * Class ArrayTransposeWorker extends abstract class {@link Worker} and defines method + * executeOperation(), to be performed on data received from master. + */ +public class ArrayTransposeWorker extends Worker { + + public ArrayTransposeWorker(Master master, int id) { + super(master, id); + } + + @Override + ArrayResult executeOperation() { + // number of rows in result matrix is equal to number of columns in input matrix and vice versa + var arrayInput = (ArrayInput) this.getReceivedData(); + final var rows = arrayInput.data[0].length; + final var cols = arrayInput.data.length; + var resultData = new int[rows][cols]; + for (var i = 0; i < cols; i++) { + for (var j = 0; j < rows; j++) { + // flipping element positions along diagonal + resultData[j][i] = arrayInput.data[i][j]; + } + } + return new ArrayResult(resultData); + } +} diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java new file mode 100644 index 000000000000..0f154c1953d8 --- /dev/null +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java @@ -0,0 +1,66 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker.system.systemworkers; + +import com.iluwatar.masterworker.Input; +import com.iluwatar.masterworker.Result; +import com.iluwatar.masterworker.system.systemmaster.Master; +import lombok.Getter; + +/** + * The abstract Worker class which extends Thread class to enable parallel processing. Contains + * fields master(holding reference to master), workerId (unique id) and receivedData(from master). + */ +public abstract class Worker extends Thread { + private final Master master; + @Getter private final int workerId; + private Input receivedData; + + Worker(Master master, int id) { + this.master = master; + this.workerId = id; + this.receivedData = null; + } + + Input getReceivedData() { + return this.receivedData; + } + + public void setReceivedData(Master m, Input i) { + // check if we are ready to receive... if yes: + this.receivedData = i; + } + + abstract Result executeOperation(); + + private void sendToMaster(Result data) { + this.master.receiveData(data, this); + } + + public void run() { // from Thread class + var work = executeOperation(); + sendToMaster(work); + } +} diff --git a/master-worker/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java b/master-worker/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java new file mode 100644 index 000000000000..30cee36ce34e --- /dev/null +++ b/master-worker/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java @@ -0,0 +1,59 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker; + +import static com.iluwatar.masterworker.ArrayUtilityMethods.matricesSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Random; +import org.junit.jupiter.api.Test; + +/** Testing divideData method in {@link ArrayInput} class. */ +class ArrayInputTest { + + @Test + void divideDataTest() { + var rows = 10; + var columns = 10; + var inputMatrix = new int[rows][columns]; + var rand = new Random(); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + inputMatrix[i][j] = rand.nextInt(10); + } + } + var i = new ArrayInput(inputMatrix); + var table = i.divideData(4); + var division1 = new int[][] {inputMatrix[0], inputMatrix[1], inputMatrix[2]}; + var division2 = new int[][] {inputMatrix[3], inputMatrix[4], inputMatrix[5]}; + var division3 = new int[][] {inputMatrix[6], inputMatrix[7]}; + var division4 = new int[][] {inputMatrix[8], inputMatrix[9]}; + assertTrue( + matricesSame(table.get(0).data, division1) + && matricesSame(table.get(1).data, division2) + && matricesSame(table.get(2).data, division3) + && matricesSame(table.get(3).data, division4)); + } +} diff --git a/master-worker/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java b/master-worker/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java new file mode 100644 index 000000000000..2c3cbaa7595b --- /dev/null +++ b/master-worker/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java @@ -0,0 +1,47 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** Testing utility methods in {@link ArrayUtilityMethods} class. */ +class ArrayUtilityMethodsTest { + + @Test + void arraysSameTest() { + var arr1 = new int[] {1, 4, 2, 6}; + var arr2 = new int[] {1, 4, 2, 6}; + assertTrue(ArrayUtilityMethods.arraysSame(arr1, arr2)); + } + + @Test + void matricesSameTest() { + var matrix1 = new int[][] {{1, 4, 2, 6}, {5, 8, 6, 7}}; + var matrix2 = new int[][] {{1, 4, 2, 6}, {5, 8, 6, 7}}; + assertTrue(ArrayUtilityMethods.matricesSame(matrix1, matrix2)); + } +} diff --git a/master-worker/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java b/master-worker/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java new file mode 100644 index 000000000000..9d037ada05f3 --- /dev/null +++ b/master-worker/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java @@ -0,0 +1,60 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker.system; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.masterworker.ArrayInput; +import com.iluwatar.masterworker.ArrayResult; +import com.iluwatar.masterworker.ArrayUtilityMethods; +import org.junit.jupiter.api.Test; + +/** Testing getResult method in {@link ArrayTransposeMasterWorker} class. */ +class ArrayTransposeMasterWorkerTest { + + @Test + void getResultTest() { + var atmw = new ArrayTransposeMasterWorker(); + var matrix = + new int[][] { + {1, 2, 3, 4, 5}, + {1, 2, 3, 4, 5}, + {1, 2, 3, 4, 5}, + {1, 2, 3, 4, 5}, + {1, 2, 3, 4, 5} + }; + var matrixTranspose = + new int[][] { + {1, 1, 1, 1, 1}, + {2, 2, 2, 2, 2}, + {3, 3, 3, 3, 3}, + {4, 4, 4, 4, 4}, + {5, 5, 5, 5, 5} + }; + var i = new ArrayInput(matrix); + var r = (ArrayResult) atmw.getResult(i); + assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose)); + } +} diff --git a/master-worker/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java b/master-worker/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java new file mode 100644 index 000000000000..b1fedbd97faf --- /dev/null +++ b/master-worker/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.masterworker.system.systemworkers; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.masterworker.ArrayInput; +import com.iluwatar.masterworker.ArrayUtilityMethods; +import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster; +import org.junit.jupiter.api.Test; + +/** Testing executeOperation method in {@link ArrayTransposeWorker} class. */ +class ArrayTransposeWorkerTest { + + @Test + void executeOperationTest() { + var atm = new ArrayTransposeMaster(1); + var atw = new ArrayTransposeWorker(atm, 1); + var matrix = new int[][] {{2, 4}, {3, 5}}; + var matrixTranspose = new int[][] {{2, 3}, {4, 5}}; + var i = new ArrayInput(matrix); + atw.setReceivedData(atm, i); + var r = atw.executeOperation(); + assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose)); + } +} diff --git a/mediator/README.md b/mediator/README.md index 3452082ef8e6..bcf64f022b87 100644 --- a/mediator/README.md +++ b/mediator/README.md @@ -1,37 +1,220 @@ --- -layout: pattern -title: Mediator -folder: mediator -permalink: /patterns/mediator/ -categories: Behavioral -tags: - - Java - - Gang Of Four - - Difficulty-Intermediate +title: "Mediator Pattern in Java: Simplifying Object Communications in Complex Systems" +shortTitle: Mediator +description: "Learn how the Mediator Design Pattern reduces complexity in object communication and improves system maintainability with a centralized mediator in Java. Explore examples and implementation." +category: Behavioral +language: en +tag: + - Decoupling + - Gang of Four + - Messaging + - Object composition --- -## Intent -Define an object that encapsulates how a set of objects interact. -Mediator promotes loose coupling by keeping objects from referring to each -other explicitly, and it lets you vary their interaction independently. +## Also known as -![alt text](./etc/mediator_1.png "Mediator") +* Controller + +## Intent of Mediator Design Pattern + +The Mediator design pattern is intended to reduce the complexity of communication between multiple objects or classes in a system. It achieves this by providing a centralized mediator class that handles the interactions between different classes, thus reducing their direct dependencies on each other. + +## Detailed Explanation of Mediator Pattern with Real-World Examples + +Real-world example + +> Imagine an air traffic control system at a busy airport, where the air traffic controller acts as a mediator. In this scenario, numerous airplanes wish to take off, land, or navigate around the airport's airspace. Instead of each pilot communicating directly with every other pilot, which could lead to confusion and potential accidents, all communication goes through the air traffic controller. The controller receives requests, processes them, and gives clear, organized instructions to each pilot. This centralized system reduces the complexity of communications and ensures safety and efficiency in managing the airport's operations. This is analogous to the Mediator design pattern in software, where a central mediator class handles and coordinates the interaction between different objects or systems. + +In plain words + +> Mediator decouples a set of classes by forcing their communications flow through a mediating object. + +Wikipedia says + +> In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior. In object-oriented programming, programs often consist of many classes. Business logic and computation are distributed among these classes. However, as more classes are added to a program, especially during maintenance and/or refactoring, the problem of communication between these classes may become more complex. This makes the program harder to read and maintain. Furthermore, it can become difficult to change the program, since any change may affect code in several other classes. With the mediator pattern, communication between objects is encapsulated within a mediator object. Objects no longer communicate directly with each other, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby reducing coupling. + +Sequence diagram + +![Mediator sequence diagram](./etc/mediator-sequence-diagram.png) + +## Programmatic Example of Mediator Pattern in Java + +In this example, the mediator encapsulates how a set of objects interact. Instead of referring to each other directly, they use the mediator interface. + +The party members `Rogue`, `Wizard`, `Hobbit`, and `Hunter` all inherit from the `PartyMemberBase`implementing the `PartyMember` interface. + +```java +public interface PartyMember { + + void joinedParty(Party party); + + void partyAction(Action action); + + void act(Action action); +} + +@Slf4j +public abstract class PartyMemberBase implements PartyMember { + + protected Party party; + + @Override + public void joinedParty(Party party) { + LOGGER.info("{} joins the party", this); + this.party = party; + } + + @Override + public void partyAction(Action action) { + LOGGER.info("{} {}", this, action.getDescription()); + } + + @Override + public void act(Action action) { + if (party != null) { + LOGGER.info("{} {}", this, action); + party.act(this, action); + } + } + + @Override + public abstract String toString(); +} + +public class Rogue extends PartyMemberBase { + + @Override + public String toString() { + return "Rogue"; + } +} + +// Wizard, Hobbit, and Hunter are implemented similarly +``` + +Our mediator system consists of `Party` interface and its implementation. + +```java +public interface Party { + + void addMember(PartyMember member); + + void act(PartyMember actor, Action action); +} + +public class PartyImpl implements Party { + + private final List members; + + public PartyImpl() { + members = new ArrayList<>(); + } + + @Override + public void act(PartyMember actor, Action action) { + for (var member : members) { + if (!member.equals(actor)) { + member.partyAction(action); + } + } + } + + @Override + public void addMember(PartyMember member) { + members.add(member); + member.joinedParty(this); + } +} +``` + +Here's a demo showing the mediator pattern in action. + +```java +public static void main(String[] args) { + + // create party and members + Party party = new PartyImpl(); + var hobbit = new Hobbit(); + var wizard = new Wizard(); + var rogue = new Rogue(); + var hunter = new Hunter(); + + // add party members + party.addMember(hobbit); + party.addMember(wizard); + party.addMember(rogue); + party.addMember(hunter); + + // perform actions -> the other party members + // are notified by the party + hobbit.act(Action.ENEMY); + wizard.act(Action.TALE); + rogue.act(Action.GOLD); + hunter.act(Action.HUNT); +} +``` + +Here's the console output from running the example. + +``` +14:05:15.081 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hobbit joins the party +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Wizard joins the party +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue joins the party +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hunter joins the party +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hobbit spotted enemies +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Wizard runs for cover +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue runs for cover +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hunter runs for cover +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Wizard tells a tale +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hobbit comes to listen +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue comes to listen +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hunter comes to listen +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue found gold +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hobbit takes his share of the gold +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Wizard takes his share of the gold +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hunter takes his share of the gold +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hunter hunted a rabbit +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hobbit arrives for dinner +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Wizard arrives for dinner +14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue arrives for dinner +``` + +## When to Use the Mediator Pattern in Java -## Applicability Use the Mediator pattern when -* a set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand -* reusing an object is difficult because it refers to and communicates with many other objects -* a behavior that's distributed between several classes should be customizable without a lot of subclassing +* A set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand +* Reusing an object is difficult because it refers to and communicates with many other objects +* A behavior that's distributed between several classes should be customizable without a lot of subclassing -## Real world examples +## Real-World Applications of Mediator Pattern in Java * All scheduleXXX() methods of [java.util.Timer](http://docs.oracle.com/javase/8/docs/api/java/util/Timer.html) * [java.util.concurrent.Executor#execute()](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-) * submit() and invokeXXX() methods of [java.util.concurrent.ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) * scheduleXXX() methods of [java.util.concurrent.ScheduledExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html) * [java.lang.reflect.Method#invoke()](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#invoke-java.lang.Object-java.lang.Object...-) +* Java Message Service (JMS) uses mediators to handle message exchanges between clients and servers. +* JavaBeans property change support class (java.beans.PropertyChangeSupport) acts as a mediator by handling communication between beans regarding property changes. + +## Benefits and Trade-offs of Mediator Pattern + +Benefits: + +* Reduces coupling between components of a program, fostering better organization and easier maintenance. +* Centralizes control. The mediator pattern centralizes the control logic, making it easier to comprehend and manage. + +Trade-offs: + +* Mediator can become a god object coupled with all classes in the system, gaining too much responsibility and complexity. + +## Related Java Design Patterns + +* [Observer](https://java-design-patterns.com/patterns/observer/): Often used together, where the mediator pattern can use the observer pattern to notify various objects about state changes. Mediators effectively act as a channel of communication managed by an observer. +* [Facade](https://java-design-patterns.com/patterns/facade/): Mediator simplifies communication between components, similar to how a facade simplifies a subsystem interface, but a mediator’s colleagues can communicate back to the mediator. +* [Command](https://java-design-patterns.com/patterns/command/): Commands can be mediated as they are dispatched to their receivers, encapsulating a request as an object. -## Credits +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/mediator/etc/mediator-sequence-diagram.png b/mediator/etc/mediator-sequence-diagram.png new file mode 100644 index 000000000000..e79a4aaec9ef Binary files /dev/null and b/mediator/etc/mediator-sequence-diagram.png differ diff --git a/mediator/etc/mediator.urm.puml b/mediator/etc/mediator.urm.puml new file mode 100644 index 000000000000..04e75d2b8841 --- /dev/null +++ b/mediator/etc/mediator.urm.puml @@ -0,0 +1,69 @@ +@startuml +package com.iluwatar.mediator { + enum Action { + + ENEMY {static} + + GOLD {static} + + HUNT {static} + + NONE {static} + + TALE {static} + - description : String + - title : String + + getDescription() : String + + toString() : String + + valueOf(name : String) : Action {static} + + values() : Action[] {static} + } + class App { + + App() + + main(args : String[]) {static} + } + class Hobbit { + + Hobbit() + + toString() : String + } + class Hunter { + + Hunter() + + toString() : String + } + interface Party { + + act(PartyMember, Action) {abstract} + + addMember(PartyMember) {abstract} + } + class PartyImpl { + - members : List + + PartyImpl() + + act(actor : PartyMember, action : Action) + + addMember(member : PartyMember) + } + interface PartyMember { + + act(Action) {abstract} + + joinedParty(Party) {abstract} + + partyAction(Action) {abstract} + } + abstract class PartyMemberBase { + - LOGGER : Logger {static} + # party : Party + + PartyMemberBase() + + act(action : Action) + + joinedParty(party : Party) + + partyAction(action : Action) + + toString() : String {abstract} + } + class Rogue { + + Rogue() + + toString() : String + } + class Wizard { + + Wizard() + + toString() : String + } +} +PartyImpl --> "-members" PartyMember +PartyMemberBase --> "-party" Party +Hobbit --|> PartyMemberBase +Hunter --|> PartyMemberBase +PartyImpl ..|> Party +PartyMemberBase ..|> PartyMember +Rogue --|> PartyMemberBase +Wizard --|> PartyMemberBase +@enduml \ No newline at end of file diff --git a/mediator/pom.xml b/mediator/pom.xml index 77c29addae5b..737f818838b2 100644 --- a/mediator/pom.xml +++ b/mediator/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT mediator - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -54,4 +58,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.mediator.App + + + + + + + + diff --git a/mediator/src/main/java/com/iluwatar/mediator/Action.java b/mediator/src/main/java/com/iluwatar/mediator/Action.java index 4deb0388dab5..d61873e69d70 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Action.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Action.java @@ -1,51 +1,48 @@ -/** - * 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.mediator; - -/** - * - * Action enumeration. - * - */ -public enum Action { - - HUNT("hunted a rabbit", "arrives for dinner"), TALE("tells a tale", "comes to listen"), GOLD( - "found gold", "takes his share of the gold"), ENEMY("spotted enemies", "runs for cover"), NONE( - "", ""); - - private String title; - private String description; - - Action(String title, String description) { - this.title = title; - this.description = description; - } - - public String getDescription() { - return description; - } - - public String toString() { - return title; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.mediator; + +import lombok.Getter; + +/** Action enumeration. */ +public enum Action { + HUNT("hunted a rabbit", "arrives for dinner"), + TALE("tells a tale", "comes to listen"), + GOLD("found gold", "takes his share of the gold"), + ENEMY("spotted enemies", "runs for cover"), + NONE("", ""); + + private final String title; + @Getter private final String description; + + Action(String title, String description) { + this.title = title; + this.description = description; + } + + public String toString() { + return title; + } +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/App.java b/mediator/src/main/java/com/iluwatar/mediator/App.java index 09433da26d42..aaab69f4d23b 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/App.java +++ b/mediator/src/main/java/com/iluwatar/mediator/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,42 +25,40 @@ package com.iluwatar.mediator; /** - * * The Mediator pattern defines an object that encapsulates how a set of objects interact. This * pattern is considered to be a behavioral pattern due to the way it can alter the program's * running behavior. - *

    - * Usually a program is made up of a large number of classes. So the logic and computation is + * + *

    Usually a program is made up of a large number of classes. So the logic and computation is * distributed among these classes. However, as more classes are developed in a program, especially * during maintenance and/or refactoring, the problem of communication between these classes may * become more complex. This makes the program harder to read and maintain. Furthermore, it can * become difficult to change the program, since any change may affect code in several other * classes. - *

    - * With the Mediator pattern, communication between objects is encapsulated with a mediator object. - * Objects no longer communicate directly with each other, but instead communicate through the - * mediator. This reduces the dependencies between communicating objects, thereby lowering the + * + *

    With the Mediator pattern, communication between objects is encapsulated with a mediator + * object. Objects no longer communicate directly with each other, but instead communicate through + * the mediator. This reduces the dependencies between communicating objects, thereby lowering the * coupling. - *

    - * In this example the mediator encapsulates how a set of objects ({@link PartyMember}) interact. + * + *

    In this example the mediator encapsulates how a set of objects ({@link PartyMember}) interact. * Instead of referring to each other directly they use the mediator ({@link Party}) interface. - * */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { // create party and members Party party = new PartyImpl(); - Hobbit hobbit = new Hobbit(); - Wizard wizard = new Wizard(); - Rogue rogue = new Rogue(); - Hunter hunter = new Hunter(); + var hobbit = new Hobbit(); + var wizard = new Wizard(); + var rogue = new Rogue(); + var hunter = new Hunter(); // add party members party.addMember(hobbit); diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java index 654048d55df6..c0b5fc967bcc 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java @@ -1,37 +1,34 @@ -/** - * 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.mediator; - -/** - * - * Hobbit party member. - * - */ -public class Hobbit extends PartyMemberBase { - - @Override - public String toString() { - return "Hobbit"; - } - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.mediator; + +/** Hobbit party member. */ +public class Hobbit extends PartyMemberBase { + + @Override + public String toString() { + return "Hobbit"; + } +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java index 23988bd58939..ddf0c2810440 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java @@ -1,36 +1,34 @@ -/** - * 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.mediator; - -/** - * - * Hunter party member. - * - */ -public class Hunter extends PartyMemberBase { - - @Override - public String toString() { - return "Hunter"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.mediator; + +/** Hunter party member. */ +public class Hunter extends PartyMemberBase { + + @Override + public String toString() { + return "Hunter"; + } +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/Party.java b/mediator/src/main/java/com/iluwatar/mediator/Party.java index d68e027913fb..b7c87f162a68 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Party.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Party.java @@ -1,36 +1,33 @@ -/** - * 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.mediator; - -/** - * - * Party interface. - * - */ -public interface Party { - - void addMember(PartyMember member); - - void act(PartyMember actor, Action action); - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.mediator; + +/** Party interface. */ +public interface Party { + + void addMember(PartyMember member); + + void act(PartyMember actor, Action action); +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java index d30ee3ba41a6..92e37506f9d9 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java +++ b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java @@ -1,55 +1,53 @@ -/** - * 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.mediator; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * Party implementation. - * - */ -public class PartyImpl implements Party { - - private final List members; - - public PartyImpl() { - members = new ArrayList<>(); - } - - @Override - public void act(PartyMember actor, Action action) { - for (PartyMember member : members) { - if (!member.equals(actor)) { - member.partyAction(action); - } - } - } - - @Override - public void addMember(PartyMember member) { - members.add(member); - member.joinedParty(this); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.mediator; + +import java.util.ArrayList; +import java.util.List; + +/** Party implementation. */ +public class PartyImpl implements Party { + + private final List members; + + public PartyImpl() { + members = new ArrayList<>(); + } + + @Override + public void act(PartyMember actor, Action action) { + for (var member : members) { + if (!member.equals(actor)) { + member.partyAction(action); + } + } + } + + @Override + public void addMember(PartyMember member) { + members.add(member); + member.joinedParty(this); + } +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java index 09f64c215981..4fad4e85b646 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java +++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,11 +24,7 @@ */ package com.iluwatar.mediator; -/** - * - * Interface for party members interacting with {@link Party}. - * - */ +/** Interface for party members interacting with {@link Party}. */ public interface PartyMember { void joinedParty(Party party); diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java index 4c60a3b43b64..8a67b8f59f7c 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java +++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java @@ -1,61 +1,56 @@ -/** - * 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.mediator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Abstract base class for party members. - * - */ -public abstract class PartyMemberBase implements PartyMember { - - private static final Logger LOGGER = LoggerFactory.getLogger(PartyMemberBase.class); - - protected Party party; - - @Override - public void joinedParty(Party party) { - LOGGER.info("{} joins the party", this); - this.party = party; - } - - @Override - public void partyAction(Action action) { - LOGGER.info("{} {}", this, action.getDescription()); - } - - @Override - public void act(Action action) { - if (party != null) { - LOGGER.info("{} {}", this, action); - party.act(this, action); - } - } - - @Override - public abstract String toString(); - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.mediator; + +import lombok.extern.slf4j.Slf4j; + +/** Abstract base class for party members. */ +@Slf4j +public abstract class PartyMemberBase implements PartyMember { + + protected Party party; + + @Override + public void joinedParty(Party party) { + LOGGER.info("{} joins the party", this); + this.party = party; + } + + @Override + public void partyAction(Action action) { + LOGGER.info("{} {}", this, action.getDescription()); + } + + @Override + public void act(Action action) { + if (party != null) { + LOGGER.info("{} {}", this, action); + party.act(this, action); + } + } + + @Override + public abstract String toString(); +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/Rogue.java b/mediator/src/main/java/com/iluwatar/mediator/Rogue.java index e0b6c7847791..5edeff28fbf8 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Rogue.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Rogue.java @@ -1,37 +1,34 @@ -/** - * 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.mediator; - -/** - * - * Rogue party member. - * - */ -public class Rogue extends PartyMemberBase { - - @Override - public String toString() { - return "Rogue"; - } - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.mediator; + +/** Rogue party member. */ +public class Rogue extends PartyMemberBase { + + @Override + public String toString() { + return "Rogue"; + } +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/Wizard.java b/mediator/src/main/java/com/iluwatar/mediator/Wizard.java index fb0833e57cca..126766ea9a95 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Wizard.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Wizard.java @@ -1,37 +1,34 @@ -/** - * 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.mediator; - -/** - * - * Wizard party member. - * - */ -public class Wizard extends PartyMemberBase { - - @Override - public String toString() { - return "Wizard"; - } - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.mediator; + +/** Wizard party member. */ +public class Wizard extends PartyMemberBase { + + @Override + public String toString() { + return "Wizard"; + } +} diff --git a/mediator/src/test/java/com/iluwatar/mediator/AppTest.java b/mediator/src/test/java/com/iluwatar/mediator/AppTest.java index a375490cd2d1..85be64afe7ac 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/AppTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.mediator; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java b/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java index 820bf17ee419..7353bc83b354 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,30 +24,25 @@ */ package com.iluwatar.mediator; -import org.junit.jupiter.api.Test; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; -/** - * Date: 12/19/15 - 10:00 PM - * - * @author Jeroen Meulemeester - */ -public class PartyImplTest { +import org.junit.jupiter.api.Test; + +/** PartyImplTest */ +class PartyImplTest { /** * Verify if a member is notified when it's joining a party. Generate an action and see if the * other member gets it. Also check members don't get their own actions. */ @Test - public void testPartyAction() { - final PartyMember partyMember1 = mock(PartyMember.class); - final PartyMember partyMember2 = mock(PartyMember.class); + void testPartyAction() { + final var partyMember1 = mock(PartyMember.class); + final var partyMember2 = mock(PartyMember.class); - final PartyImpl party = new PartyImpl(); + final var party = new PartyImpl(); party.addMember(partyMember1); party.addMember(partyMember2); @@ -53,11 +50,9 @@ public void testPartyAction() { verify(partyMember2).joinedParty(party); party.act(partyMember1, Action.GOLD); - verifyZeroInteractions(partyMember1); + verifyNoMoreInteractions(partyMember1); verify(partyMember2).partyAction(Action.GOLD); verifyNoMoreInteractions(partyMember1, partyMember2); - } - } diff --git a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java index 03db825e9dcf..46be9593ae79 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,108 +24,96 @@ */ package com.iluwatar.mediator; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.LoggerFactory; -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.function.Supplier; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; +/** PartyMemberTest */ +class PartyMemberTest { -/** - * Date: 12/19/15 - 10:13 PM - * - * @author Jeroen Meulemeester - */ -public class PartyMemberTest { - - static Collection[]> dataProvider() { - return Arrays.asList( - new Supplier[]{Hobbit::new}, - new Supplier[]{Hunter::new}, - new Supplier[]{Rogue::new}, - new Supplier[]{Wizard::new} - ); + static Stream dataProvider() { + return Stream.of( + Arguments.of((Supplier) Hobbit::new), + Arguments.of((Supplier) Hunter::new), + Arguments.of((Supplier) Rogue::new), + Arguments.of((Supplier) Wizard::new)); } private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(PartyMemberBase.class); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } - /** - * Verify if a party action triggers the correct output to the std-Out - */ + /** Verify if a party action triggers the correct output to the std-Out */ @ParameterizedTest @MethodSource("dataProvider") - public void testPartyAction(Supplier memberSupplier) { - final PartyMember member = memberSupplier.get(); + void testPartyAction(Supplier memberSupplier) { + final var member = memberSupplier.get(); - for (final Action action : Action.values()) { + for (final var action : Action.values()) { member.partyAction(action); - assertEquals(member.toString() + " " + action.getDescription(), appender.getLastMessage()); + assertEquals(member + " " + action.getDescription(), appender.getLastMessage()); } assertEquals(Action.values().length, appender.getLogSize()); } - /** - * Verify if a member action triggers the expected interactions with the party class - */ + /** Verify if a member action triggers the expected interactions with the party class */ @ParameterizedTest @MethodSource("dataProvider") - public void testAct(Supplier memberSupplier) { - final PartyMember member = memberSupplier.get(); + void testAct(Supplier memberSupplier) { + final var member = memberSupplier.get(); member.act(Action.GOLD); assertEquals(0, appender.getLogSize()); - final Party party = mock(Party.class); + final var party = mock(Party.class); member.joinedParty(party); - assertEquals(member.toString() + " joins the party", appender.getLastMessage()); + assertEquals(member + " joins the party", appender.getLastMessage()); - for (final Action action : Action.values()) { + for (final var action : Action.values()) { member.act(action); - assertEquals(member.toString() + " " + action.toString(), appender.getLastMessage()); + assertEquals(member + " " + action.toString(), appender.getLastMessage()); verify(party).act(member, action); } assertEquals(Action.values().length + 1, appender.getLogSize()); } - /** - * Verify if {@link PartyMemberBase#toString()} generate the expected output - */ + /** Verify if {@link PartyMemberBase#toString()} generate the expected output */ @ParameterizedTest @MethodSource("dataProvider") - public void testToString(Supplier memberSupplier) throws Exception { - final PartyMember member = memberSupplier.get(); - final Class memberClass = member.getClass(); + void testToString(Supplier memberSupplier) { + final var member = memberSupplier.get(); + final var memberClass = member.getClass(); assertEquals(memberClass.getSimpleName(), member.toString()); } - private class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); + private static class InMemoryAppender extends AppenderBase { + private final List log = new LinkedList<>(); - public InMemoryAppender(Class clazz) { + public InMemoryAppender(Class clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } @@ -141,6 +131,4 @@ public String getLastMessage() { return log.get(log.size() - 1).getFormattedMessage(); } } - - } diff --git a/memento/README.md b/memento/README.md index 463b5fec0836..520c4b4ecc53 100644 --- a/memento/README.md +++ b/memento/README.md @@ -1,34 +1,199 @@ --- -layout: pattern -title: Memento -folder: memento -permalink: /patterns/memento/ -categories: Behavioral -tags: - - Java - - Gang Of Four - - Difficulty-Intermediate +title: "Memento Pattern in Java: Preserving Object State for Undo Operations" +shortTitle: Memento +description: "Learn how to implement the Memento design pattern in Java to capture and restore object state without violating encapsulation. Ideal for undo functionality in applications." +category: Behavioral +language: en +tag: + - Encapsulation + - Gang of Four + - Memory management + - Object composition + - State tracking + - Undo --- ## Also known as -Token -## Intent -Without violating encapsulation, capture and externalize an -object's internal state so that the object can be restored to this state later. +* Snapshot +* Token -![alt text](./etc/memento.png "Memento") +## Intent of Memento Design Pattern + +The Memento design pattern in Java allows developers to capture and restore an object's internal state without violating encapsulation. + +## Detailed Explanation of Memento Pattern with Real-World Examples + +Real-world example + +> A text editor application can utilize the Memento design pattern in Java to enable undo and redo functionalities. By capturing the current state of a document as a memento each time a change is made, the application can easily restore the document to any previous state. The snapshots are stored in a history list. When the user clicks the undo button, the editor restores the document to the state saved in the most recent memento. This process allows users to revert to previous versions of their document without exposing or altering the internal data structures of the editor. + +In plain words + +> Memento pattern captures object internal state making it easy to store and restore objects in any point of time. + +Wikipedia says + +> The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback). + +Sequence diagram + +![Memento sequence diagram](./etc/memento-sequence-diagram.png) + +## Programmatic Example of Memento Pattern in Java + +In our astrology application, we use the Memento pattern to capture and restore the state of star objects. Each state is saved as a memento, allowing us to revert to previous states as needed. + +Let's first define the types of stars we are capable to handle. + +```java +public enum StarType { + SUN("sun"), + RED_GIANT("red giant"), + WHITE_DWARF("white dwarf"), + SUPERNOVA("supernova"), + DEAD("dead star"); + // ... +} +``` + +Next, let's jump straight to the essentials. Here's the `Star` class along with the mementos that we need to manipulate. Especially pay attention to `getMemento` and `setMemento` methods. + +```java +public interface StarMemento { +} + +public class Star { + + private StarType type; + private int ageYears; + private int massTons; + + public Star(StarType startType, int startAge, int startMass) { + this.type = startType; + this.ageYears = startAge; + this.massTons = startMass; + } + + public void timePasses() { + ageYears *= 2; + massTons *= 8; + switch (type) { + case RED_GIANT -> type = StarType.WHITE_DWARF; + case SUN -> type = StarType.RED_GIANT; + case SUPERNOVA -> type = StarType.DEAD; + case WHITE_DWARF -> type = StarType.SUPERNOVA; + case DEAD -> { + ageYears *= 2; + massTons = 0; + } + default -> { + } + } + } + + StarMemento getMemento() { + var state = new StarMementoInternal(); + state.setAgeYears(ageYears); + state.setMassTons(massTons); + state.setType(type); + return state; + } + + void setMemento(StarMemento memento) { + var state = (StarMementoInternal) memento; + this.type = state.getType(); + this.ageYears = state.getAgeYears(); + this.massTons = state.getMassTons(); + } + + @Override + public String toString() { + return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons); + } + + private static class StarMementoInternal implements StarMemento { + + private StarType type; + private int ageYears; + private int massTons; + + // setters and getters -> + // ... + } +} +``` + +And finally here's how we use the mementos to store and restore star states. + +```java +public static void main(String[] args) { + var states = new Stack(); + + var star = new Star(StarType.SUN, 10000000, 500000); + LOGGER.info(star.toString()); + states.add(star.getMemento()); + star.timePasses(); + LOGGER.info(star.toString()); + states.add(star.getMemento()); + star.timePasses(); + LOGGER.info(star.toString()); + states.add(star.getMemento()); + star.timePasses(); + LOGGER.info(star.toString()); + states.add(star.getMemento()); + star.timePasses(); + LOGGER.info(star.toString()); + while (!states.isEmpty()) { + star.setMemento(states.pop()); + LOGGER.info(star.toString()); + } +} +``` + +Program output: + +``` +14:09:15.878 [main] INFO com.iluwatar.memento.App -- sun age: 10000000 years mass: 500000 tons +14:09:15.880 [main] INFO com.iluwatar.memento.App -- red giant age: 20000000 years mass: 4000000 tons +14:09:15.880 [main] INFO com.iluwatar.memento.App -- white dwarf age: 40000000 years mass: 32000000 tons +14:09:15.880 [main] INFO com.iluwatar.memento.App -- supernova age: 80000000 years mass: 256000000 tons +14:09:15.880 [main] INFO com.iluwatar.memento.App -- dead star age: 160000000 years mass: 2048000000 tons +14:09:15.880 [main] INFO com.iluwatar.memento.App -- supernova age: 80000000 years mass: 256000000 tons +14:09:15.880 [main] INFO com.iluwatar.memento.App -- white dwarf age: 40000000 years mass: 32000000 tons +14:09:15.881 [main] INFO com.iluwatar.memento.App -- red giant age: 20000000 years mass: 4000000 tons +14:09:15.881 [main] INFO com.iluwatar.memento.App -- sun age: 10000000 years mass: 500000 tons +``` + +## When to Use the Memento Pattern in Java -## Applicability Use the Memento pattern when -* a snapshot of an object's state must be saved so that it can be restored to that state later, and -* a direct interface to obtaining the state would expose implementation details and break the object's encapsulation +* You need to capture an object's state in Java and restore it later without exposing its internal structure. This is crucial for maintaining encapsulation and simplifying the management of object states. +* A direct interface to obtaining the state would expose implementation details and break the object's encapsulation. + +## Real-World Applications of Memento Pattern in Java + +The Memento pattern is used in various Java applications, including the java.util.Date and java.util.Calendar classes, which can revert to previous states. It's also common in text editors and graphic editors for undo mechanisms. + +## Benefits and Trade-offs of Memento Pattern + +Benefits: + +* Preserves encapsulation boundaries. +* Simplifies the originator by removing the need to manage version history or undo functionality directly. + +Trade-offs: + +* Can be expensive in terms of memory if a large number of states are saved. +* Care must be taken to manage the lifecycle of mementos to avoid memory leaks. -## Real world examples +## Related Java Design Patterns -* [java.util.Date](http://docs.oracle.com/javase/8/docs/api/java/util/Date.html) +* [Command](https://java-design-patterns.com/patterns/command/): Often used together; commands store state for undoing operations in mementos. +* [Prototype](https://java-design-patterns.com/patterns/prototype/): Mementos may use prototyping to store the state. -## Credits +## References and Credits -* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) diff --git a/memento/etc/memento-sequence-diagram.png b/memento/etc/memento-sequence-diagram.png new file mode 100644 index 000000000000..8d70255a129b Binary files /dev/null and b/memento/etc/memento-sequence-diagram.png differ diff --git a/memento/etc/memento.urm.puml b/memento/etc/memento.urm.puml new file mode 100644 index 000000000000..319227ad242c --- /dev/null +++ b/memento/etc/memento.urm.puml @@ -0,0 +1,49 @@ +@startuml +package com.iluwatar.memento { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Star { + - ageYears : int + - massTons : int + - type : StarType + + Star(startType : StarType, startAge : int, startMass : int) + ~ getMemento() : StarMemento + ~ setMemento(memento : StarMemento) + + timePasses() + + toString() : String + } + -class StarMementoInternal { + - ageYears : int + - massTons : int + - type : StarType + - StarMementoInternal() + + getAgeYears() : int + + getMassTons() : int + + getType() : StarType + + setAgeYears(ageYears : int) + + setMassTons(massTons : int) + + setType(type : StarType) + } + interface StarMemento { + } + enum StarType { + + DEAD {static} + + RED_GIANT {static} + + SUN {static} + + SUPERNOVA {static} + + UNDEFINED {static} + + WHITE_DWARF {static} + - title : String + + toString() : String + + valueOf(name : String) : StarType {static} + + values() : StarType[] {static} + } +} +StarMementoInternal --> "-type" StarType +Star --> "-type" StarType +StarMementoInternal ..+ Star +StarMementoInternal ..|> StarMemento +@enduml \ No newline at end of file diff --git a/memento/pom.xml b/memento/pom.xml index ad4a55236a66..6ec5ca5d010c 100644 --- a/memento/pom.xml +++ b/memento/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT memento - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -44,4 +48,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.memento.App + + + + + + + + diff --git a/memento/src/main/java/com/iluwatar/memento/App.java b/memento/src/main/java/com/iluwatar/memento/App.java index c20ad4654baf..d47bc20db84a 100644 --- a/memento/src/main/java/com/iluwatar/memento/App.java +++ b/memento/src/main/java/com/iluwatar/memento/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,41 +24,34 @@ */ package com.iluwatar.memento; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Stack; +import lombok.extern.slf4j.Slf4j; /** - * * The Memento pattern is a software design pattern that provides the ability to restore an object * to its previous state (undo via rollback). - *

    - * The Memento pattern is implemented with three objects: the originator, a caretaker and a memento. - * The originator is some object that has an internal state. The caretaker is going to do something - * to the originator, but wants to be able to undo the change. The caretaker first asks the - * originator for a memento object. Then it does whatever operation (or sequence of operations) it - * was going to do. To roll back to the state before the operations, it returns the memento object - * to the originator. The memento object itself is an opaque object (one which the caretaker cannot, - * or should not, change). When using this pattern, care should be taken if the originator may - * change other objects or resources - the memento pattern operates on a single object. - *

    - * In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that + * + *

    The Memento pattern is implemented with three objects: the originator, a caretaker and a + * memento. The originator is some object that has an internal state. The caretaker is going to do + * something to the originator, but wants to be able to undo the change. The caretaker first asks + * the originator for a memento object. Then it does whatever operation (or sequence of operations) + * it was going to do. To roll back to the state before the operations, it returns the memento + * object to the originator. The memento object itself is an opaque object (one which the caretaker + * cannot, or should not, change). When using this pattern, care should be taken if the originator + * may change other objects or resources - the memento pattern operates on a single object. + * + *

    In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that * contains the state of the object. Later on the memento can be set back to the object restoring * the state. - * */ +@Slf4j public class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * Program entry point - */ + /** Program entry point. */ public static void main(String[] args) { - Stack states = new Stack<>(); + var states = new Stack(); - Star star = new Star(StarType.SUN, 10000000, 500000); + var star = new Star(StarType.SUN, 10000000, 500000); LOGGER.info(star.toString()); states.add(star.getMemento()); star.timePasses(); @@ -70,7 +65,7 @@ public static void main(String[] args) { states.add(star.getMemento()); star.timePasses(); LOGGER.info(star.toString()); - while (states.size() > 0) { + while (!states.isEmpty()) { star.setMemento(states.pop()); LOGGER.info(star.toString()); } diff --git a/memento/src/main/java/com/iluwatar/memento/Star.java b/memento/src/main/java/com/iluwatar/memento/Star.java index aac1e75fc301..8f806b1e1fe1 100644 --- a/memento/src/main/java/com/iluwatar/memento/Star.java +++ b/memento/src/main/java/com/iluwatar/memento/Star.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,71 +24,53 @@ */ package com.iluwatar.memento; -/** - * - * Star uses "mementos" to store and restore state. - * - */ +import lombok.Getter; +import lombok.Setter; + +/** Star uses "mementos" to store and restore state. */ public class Star { private StarType type; private int ageYears; private int massTons; - /** - * Constructor - */ + /** Constructor. */ public Star(StarType startType, int startAge, int startMass) { this.type = startType; this.ageYears = startAge; this.massTons = startMass; } - /** - * Makes time pass for the star - */ + /** Makes time pass for the star. */ public void timePasses() { ageYears *= 2; massTons *= 8; switch (type) { - case RED_GIANT: - type = StarType.WHITE_DWARF; - break; - case SUN: - type = StarType.RED_GIANT; - break; - case SUPERNOVA: - type = StarType.DEAD; - break; - case WHITE_DWARF: - type = StarType.SUPERNOVA; - break; - case DEAD: + case RED_GIANT -> type = StarType.WHITE_DWARF; + case SUN -> type = StarType.RED_GIANT; + case SUPERNOVA -> type = StarType.DEAD; + case WHITE_DWARF -> type = StarType.SUPERNOVA; + case DEAD -> { ageYears *= 2; massTons = 0; - break; - default: - break; + } + default -> {} } } StarMemento getMemento() { - - StarMementoInternal state = new StarMementoInternal(); + var state = new StarMementoInternal(); state.setAgeYears(ageYears); state.setMassTons(massTons); state.setType(type); return state; - } void setMemento(StarMemento memento) { - - StarMementoInternal state = (StarMementoInternal) memento; + var state = (StarMementoInternal) memento; this.type = state.getType(); this.ageYears = state.getAgeYears(); this.massTons = state.getMassTons(); - } @Override @@ -94,39 +78,13 @@ public String toString() { return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons); } - /** - * - * StarMemento implementation - * - */ + /** StarMemento implementation. */ + @Getter + @Setter private static class StarMementoInternal implements StarMemento { private StarType type; private int ageYears; private int massTons; - - public StarType getType() { - return type; - } - - public void setType(StarType type) { - this.type = type; - } - - public int getAgeYears() { - return ageYears; - } - - public void setAgeYears(int ageYears) { - this.ageYears = ageYears; - } - - public int getMassTons() { - return massTons; - } - - public void setMassTons(int massTons) { - this.massTons = massTons; - } } } diff --git a/memento/src/main/java/com/iluwatar/memento/StarMemento.java b/memento/src/main/java/com/iluwatar/memento/StarMemento.java index 94e6da186d29..b0214ad1acc2 100644 --- a/memento/src/main/java/com/iluwatar/memento/StarMemento.java +++ b/memento/src/main/java/com/iluwatar/memento/StarMemento.java @@ -1,32 +1,28 @@ -/** - * 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.memento; - -/** - * - * External interface to memento. - * - */ -public interface StarMemento { - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.memento; + +/** External interface to memento. */ +public interface StarMemento {} diff --git a/memento/src/main/java/com/iluwatar/memento/StarType.java b/memento/src/main/java/com/iluwatar/memento/StarType.java index 414cccc465e7..41e1659ef0e5 100644 --- a/memento/src/main/java/com/iluwatar/memento/StarType.java +++ b/memento/src/main/java/com/iluwatar/memento/StarType.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,17 +24,15 @@ */ package com.iluwatar.memento; -/** - * - * StarType enumeration - * - */ +/** StarType enumeration. */ public enum StarType { + SUN("sun"), + RED_GIANT("red giant"), + WHITE_DWARF("white dwarf"), + SUPERNOVA("supernova"), + DEAD("dead star"); - SUN("sun"), RED_GIANT("red giant"), WHITE_DWARF("white dwarf"), SUPERNOVA("supernova"), DEAD( - "dead star"), UNDEFINED(""); - - private String title; + private final String title; StarType(String title) { this.title = title; diff --git a/memento/src/test/java/com/iluwatar/memento/AppTest.java b/memento/src/test/java/com/iluwatar/memento/AppTest.java index c6ea91e9bccc..ad7ea0019c68 100644 --- a/memento/src/test/java/com/iluwatar/memento/AppTest.java +++ b/memento/src/test/java/com/iluwatar/memento/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.memento; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/memento/src/test/java/com/iluwatar/memento/StarTest.java b/memento/src/test/java/com/iluwatar/memento/StarTest.java index c3d16efe5d8b..4411efaab3fa 100644 --- a/memento/src/test/java/com/iluwatar/memento/StarTest.java +++ b/memento/src/test/java/com/iluwatar/memento/StarTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,23 +24,17 @@ */ package com.iluwatar.memento; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Date: 12/20/15 - 10:08 AM - * - * @author Jeroen Meulemeester - */ -public class StarTest { +import org.junit.jupiter.api.Test; + +/** StarTest */ +class StarTest { - /** - * Verify the stages of a dying sun, without going back in time - */ + /** Verify the stages of a dying sun, without going back in time */ @Test - public void testTimePasses() { - final Star star = new Star(StarType.SUN, 1, 2); + void testTimePasses() { + final var star = new Star(StarType.SUN, 1, 2); assertEquals("sun age: 1 years mass: 2 tons", star.toString()); star.timePasses(); @@ -60,21 +56,19 @@ public void testTimePasses() { assertEquals("dead star age: 256 years mass: 0 tons", star.toString()); } - /** - * Verify some stage of a dying sun, but go back in time to test the memento - */ + /** Verify some stage of a dying sun, but go back in time to test the memento */ @Test - public void testSetMemento() { - final Star star = new Star(StarType.SUN, 1, 2); - final StarMemento firstMemento = star.getMemento(); + void testSetMemento() { + final var star = new Star(StarType.SUN, 1, 2); + final var firstMemento = star.getMemento(); assertEquals("sun age: 1 years mass: 2 tons", star.toString()); star.timePasses(); - final StarMemento secondMemento = star.getMemento(); + final var secondMemento = star.getMemento(); assertEquals("red giant age: 2 years mass: 16 tons", star.toString()); star.timePasses(); - final StarMemento thirdMemento = star.getMemento(); + final var thirdMemento = star.getMemento(); assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString()); star.timePasses(); @@ -91,7 +85,5 @@ public void testSetMemento() { star.setMemento(firstMemento); assertEquals("sun age: 1 years mass: 2 tons", star.toString()); - } - } diff --git a/metadata-mapping/README.md b/metadata-mapping/README.md new file mode 100644 index 000000000000..3ca71dc9d4d0 --- /dev/null +++ b/metadata-mapping/README.md @@ -0,0 +1,267 @@ +--- +title: "Metadata Mapping Pattern in Java: Bridging Objects and Data Stores Seamlessly" +shortTitle: Metadata Mapping +description: "Explore the Metadata Mapping Design Pattern for managing the mapping between database records and objects in Java applications. Learn implementation with Hibernate, use cases, benefits, and best practices." +category: Data access +language: en +tag: + - Decoupling + - Enterprise patterns + - Object mapping + - Persistence +--- + +## Intent of Metadata Mapping Design Pattern + +Metadata Mapping Design Pattern is designed to manage the mapping between database records and Java objects in a way that keeps the database schema and object model decoupled and manageable. + +## Detailed Explanation of Metadata Mapping Pattern with Real-World Examples + +Real-world example + +> An analogous real-world example of the Metadata Mapping design pattern can be seen in online retail systems. In such systems, products often have varying attributes depending on their category. For instance, electronics might have attributes like battery life and screen size, while clothing might have attributes like size and fabric type. Using Metadata Mapping, the system can dynamically map these varying attributes to the product objects without modifying the underlying class structure. This flexibility allows for easy updates and management of product attributes as new categories and attributes are introduced, ensuring that the system can evolve with the changing product landscape. + +In plain words + +> Metadata Mapping specifies the mapping between classes and tables so that we could treat a table of any database like a Java class. + +Wikipedia says + +> Create a "virtual [object database](https://en.wikipedia.org/wiki/Object_database)" that can be used from within the programming language. + +Flowchart + +![Metadata Mapping flowchart](./etc/metadata-mapping-flowchart.png) + +## Programmatic Example of Metadata Mapping Pattern in Java + +Hibernate ORM Tool uses Metadata Mapping Pattern to specify the mapping between classes and tables either using XML or annotations in code. + +We give an example about visiting the information of `user_account` table in `h2` database. Firstly, we create `user_account` table with `h2`: + +```java +@Slf4j +public class DatabaseUtil { + private static final String DB_URL = "jdbc:h2:mem:metamapping"; + private static final String CREATE_SCHEMA_SQL = "DROP TABLE IF EXISTS `user_account`;" + + "CREATE TABLE `user_account` (\n" + + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + + " `username` varchar(255) NOT NULL,\n" + + " `password` varchar(255) NOT NULL,\n" + + " PRIMARY KEY (`id`)\n" + + ");"; + + static { + LOGGER.info("create h2 database"); + var source = new JdbcDataSource(); + source.setURL(DB_URL); + try (var statement = source.getConnection().createStatement()) { + statement.execute(CREATE_SCHEMA_SQL); + } catch (SQLException e) { + LOGGER.error("unable to create h2 data source", e); + } + } +} +``` + +Correspondingly, here's the basic `User` entity. + +```java +@Setter +@Getter +@ToString +public class User { + private Integer id; + private String username; + private String password; + + public User(String username, String password) { + this.username = username; + this.password = password; + } +} +``` + +Then we write a `xml` file to show the mapping between the table and the object: + +```xml + + + + + + + + + + + + +``` + +We use `Hibernate` to resolve the mapping and connect to our database, here's its configuration: + +```xml + + + + + + jdbc:h2:mem:metamapping + org.h2.Driver + + 1 + + org.hibernate.dialect.H2Dialect + + false + + create-drop + + + +``` + +Then we can get access to the table just like an object with `Hibernate`, here's some CRUDs: + +```java +@Slf4j +public class UserService { + private static final SessionFactory factory = HibernateUtil.getSessionFactory(); + + public List listUser() { + LOGGER.info("list all users."); + List users = new ArrayList<>(); + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + List userIter = session.createQuery("FROM User").list(); + for (var iterator = userIter.iterator(); iterator.hasNext();) { + users.add(iterator.next()); + } + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to get users", e); + } + return users; + } + + // other CRUDs -> + // ... + + public void close() { + HibernateUtil.shutdown(); + } +} +``` + +Here is our `App` class with `main` function for running the example. + +```java +@Slf4j +public class App { + + public static void main(String[] args) { + // get service + var userService = new UserService(); + // use create service to add users + for (var user : generateSampleUsers()) { + var id = userService.createUser(user); + LOGGER.info("Add user" + user + "at" + id + "."); + } + // use list service to get users + var users = userService.listUser(); + LOGGER.info(String.valueOf(users)); + // use get service to get a user + var user = userService.getUser(1); + LOGGER.info(String.valueOf(user)); + // change password of user 1 + user.setPassword("new123"); + // use update service to update user 1 + userService.updateUser(1, user); + // use delete service to delete user 2 + userService.deleteUser(2); + // close service + userService.close(); + } + + public static List generateSampleUsers() { + final var user1 = new User("ZhangSan", "zhs123"); + final var user2 = new User("LiSi", "ls123"); + final var user3 = new User("WangWu", "ww123"); + return List.of(user1, user2, user3); + } +} +``` + +Console output: + +``` +14:44:17.792 [main] INFO org.hibernate.Version - HHH000412: Hibernate ORM core version 5.6.12.Final +14:44:17.977 [main] INFO o.h.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.1.2.Final} +14:44:18.216 [main] WARN o.hibernate.orm.connections.pooling - HHH10001002: Using Hibernate built-in connection pool (not for production use!) +14:44:18.217 [main] INFO o.hibernate.orm.connections.pooling - HHH10001005: using driver [org.h2.Driver] at URL [jdbc:h2:mem:metamapping] +14:44:18.217 [main] INFO o.hibernate.orm.connections.pooling - HHH10001001: Connection properties: {} +14:44:18.217 [main] INFO o.hibernate.orm.connections.pooling - HHH10001003: Autocommit mode: false +14:44:18.219 [main] INFO o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 1 (min=1) +14:44:18.276 [main] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.H2Dialect +14:44:18.463 [main] INFO o.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@73a8e994] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode. +14:44:18.465 [main] INFO o.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@7affc159] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode. +14:44:18.470 [main] INFO o.h.e.t.j.p.i.JtaPlatformInitiator - HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] +14:44:18.473 [main] INFO c.i.metamapping.service.UserService - create user: ZhangSan +14:44:18.508 [main] INFO c.i.metamapping.service.UserService - create user ZhangSan at 1 +14:44:18.508 [main] INFO com.iluwatar.metamapping.App - Add userUser(id=1, username=ZhangSan, password=zhs123)at1. +14:44:18.508 [main] INFO c.i.metamapping.service.UserService - create user: LiSi +14:44:18.509 [main] INFO c.i.metamapping.service.UserService - create user LiSi at 2 +14:44:18.509 [main] INFO com.iluwatar.metamapping.App - Add userUser(id=2, username=LiSi, password=ls123)at2. +14:44:18.509 [main] INFO c.i.metamapping.service.UserService - create user: WangWu +14:44:18.512 [main] INFO c.i.metamapping.service.UserService - create user WangWu at 3 +14:44:18.512 [main] INFO com.iluwatar.metamapping.App - Add userUser(id=3, username=WangWu, password=ww123)at3. +14:44:18.512 [main] INFO c.i.metamapping.service.UserService - list all users. +14:44:18.542 [main] INFO com.iluwatar.metamapping.App - [User(id=1, username=ZhangSan, password=zhs123), User(id=2, username=LiSi, password=ls123), User(id=3, username=WangWu, password=ww123)] +14:44:18.542 [main] INFO c.i.metamapping.service.UserService - get user at: 1 +14:44:18.545 [main] INFO com.iluwatar.metamapping.App - User(id=1, username=ZhangSan, password=zhs123) +14:44:18.545 [main] INFO c.i.metamapping.service.UserService - update user at 1 +14:44:18.548 [main] INFO c.i.metamapping.service.UserService - delete user at: 2 +14:44:18.550 [main] INFO o.h.t.s.i.SchemaDropperImpl$DelayedDropActionImpl - HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down' +14:44:18.550 [main] INFO o.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@7b5cc918] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode. +14:44:18.551 [main] INFO o.hibernate.orm.connections.pooling - HHH10001008: Cleaning up connection pool [jdbc:h2:mem:metamapping] +``` + +## When to Use the Metadata Mapping Pattern in Java + +Use the Metadata Mapping Design Pattern when you need to bridge the gap between an object-oriented domain model and a relational database in Java applications, without hard-coding database queries into the domain logic. + +## Real-World Applications of Metadata Mapping Pattern in Java + +* Object-Relational Mapping (ORM) frameworks like Hibernate, JPA, EclipseLink, and MyBatis frequently utilize the Metadata Mapping Design Pattern to map Java objects to database tables. +* Mapping database rows to domain objects in enterprise applications. + +## Benefits and Trade-offs of Metadata Mapping Pattern + +Benefits: + +* Decouples object model and database schema, allowing independent evolution. +* Reduces boilerplate code associated with data access. +* Centralizes mapping logic, making changes more manageable. + +Trade-offs: + +* Adds complexity due to an additional layer of abstraction. +* Can impact performance if not properly optimized. + +## Related Java Design Patterns + +* [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): Metadata Mapping is often used within the broader Data Mapper pattern to facilitate the mapping process. +* Active Record: Differently from Active Record, Metadata Mapping separates the data access logic from the domain entities. +* [Repository](https://java-design-patterns.com/patterns/repository/): Works well with the Repository pattern by abstracting data access further, allowing more complex domain logic to be cleanly separated from data mapping. + +## References and Credits + +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Java Persistence with Hibernate](https://amzn.to/44tP1ox) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) +* [Pro JPA 2: Mastering the Java Persistence API](https://amzn.to/4b7UoMC) diff --git a/metadata-mapping/etc/metadata-mapping-flowchart.png b/metadata-mapping/etc/metadata-mapping-flowchart.png new file mode 100644 index 000000000000..88f7d9953cfa Binary files /dev/null and b/metadata-mapping/etc/metadata-mapping-flowchart.png differ diff --git a/metadata-mapping/etc/metadata-mapping.urm.puml b/metadata-mapping/etc/metadata-mapping.urm.puml new file mode 100644 index 000000000000..41c097a81f18 --- /dev/null +++ b/metadata-mapping/etc/metadata-mapping.urm.puml @@ -0,0 +1,55 @@ +@startuml +package com.iluwatar.metamapping.model { + class User { + - id : Integer + - password : String + - username : String + + User() + + User(username : String, password : String) + + getId() : Integer + + getPassword() : String + + getUsername() : String + + setId(id : Integer) + + setPassword(password : String) + + setUsername(username : String) + + toString() : String + } +} +package com.iluwatar.metamapping.utils { + class DatabaseUtil { + - CREATE_SCHEMA_SQL : String {static} + - DB_URL : String {static} + - LOGGER : Logger {static} + - DatabaseUtil() + } + class HibernateUtil { + - LOGGER : Logger {static} + - sessionFactory : SessionFactory {static} + - HibernateUtil() + - buildSessionFactory() : SessionFactory {static} + + getSessionFactory() : SessionFactory {static} + + shutdown() {static} + } +} +package com.iluwatar.metamapping { + class App { + - LOGGER : Logger {static} + + App() + + generateSampleUsers() : List {static} + + main(args : String[]) {static} + } +} +package com.iluwatar.metamapping.service { + class UserService { + - LOGGER : Logger {static} + - factory : SessionFactory {static} + + UserService() + + close() + + createUser(user : User) : int + + deleteUser(id : Integer) + + getUser(id : Integer) : User + + listUser() : List + + updateUser(id : Integer, user : User) + } +} +@enduml \ No newline at end of file diff --git a/metadata-mapping/etc/metamapping.png b/metadata-mapping/etc/metamapping.png new file mode 100644 index 000000000000..b1e89f8af56f Binary files /dev/null and b/metadata-mapping/etc/metamapping.png differ diff --git a/metadata-mapping/etc/metamapping.puml b/metadata-mapping/etc/metamapping.puml new file mode 100644 index 000000000000..daa8c37de36e --- /dev/null +++ b/metadata-mapping/etc/metamapping.puml @@ -0,0 +1,32 @@ +@startuml +interface com.iluwatar.metamapping.service.UserService { ++ List listUser() ++ int createUser(User) ++ void updateUser(Integer,User) ++ void deleteUser(Integer) ++ User getUser(Integer) ++ void close() +} +class com.iluwatar.metamapping.utils.DatabaseUtil { ++ {static} void createDataSource() +} +class com.iluwatar.metamapping.model.User { +- Integer id +- String username +- String password ++ User(String username, String password) +} +class com.iluwatar.metamapping.utils.HibernateUtil { ++ {static} SessionFactory getSessionFactory() ++ {static} void shutdown() +} +class com.iluwatar.metamapping.App { ++ {static} void main(String[]) ++ {static} List generateSampleUsers() +} + +com.iluwatar.metamapping.service.UserService <.. com.iluwatar.metamapping.App +com.iluwatar.metamapping.model.User <.. com.iluwatar.metamapping.service.UserService +com.iluwatar.metamapping.utils.HibernateUtil <.. com.iluwatar.metamapping.service.UserService +com.iluwatar.metamapping.utils.DatabaseUtil <-- com.iluwatar.metamapping.utils.HibernateUtil +@enduml \ No newline at end of file diff --git a/metadata-mapping/pom.xml b/metadata-mapping/pom.xml new file mode 100644 index 000000000000..7aa802d7ff2a --- /dev/null +++ b/metadata-mapping/pom.xml @@ -0,0 +1,92 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + + metadata-mapping + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.hibernate + hibernate-core + 6.6.11.Final + + + javax.xml.bind + jaxb-api + 2.4.0-b180830.0359 + + + org.glassfish.jaxb + jaxb-runtime + 4.0.5 + + + com.h2database + h2 + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.metamapping.App + + + + + + + + + \ No newline at end of file diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java new file mode 100644 index 000000000000..6b5624ac54f9 --- /dev/null +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java @@ -0,0 +1,92 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.metamapping; + +import com.iluwatar.metamapping.model.User; +import com.iluwatar.metamapping.service.UserService; +import com.iluwatar.metamapping.utils.DatabaseUtil; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.hibernate.service.ServiceRegistry; + +/** + * Metadata Mapping specifies the mapping between classes and tables so that we could treat a table + * of any database like a Java class. + * + *

    With hibernate, we achieve list/create/update/delete/get operations: 1)Create the H2 Database + * in {@link DatabaseUtil}. 2)Hibernate resolve hibernate.cfg.xml and generate service like + * save/list/get/delete. For learning metadata mapping pattern, we go deeper into Hibernate here: + * a)read properties from hibernate.cfg.xml and mapping from *.hbm.xml b)create session factory to + * generate session interacting with database c)generate session with factory pattern d)create query + * object or use basic api with session, hibernate will convert all query to database query + * according to metadata 3)We encapsulate hibernate service in {@link UserService} for our use. + * + * @see org.hibernate.cfg.Configuration#configure(String) + * @see org.hibernate.cfg.Configuration#buildSessionFactory(ServiceRegistry) + * @see org.hibernate.internal.SessionFactoryImpl#openSession() + */ +@Slf4j +public class App { + /** + * Program entry point. + * + * @param args command line args. + */ + public static void main(String[] args) { + // get service + var userService = new UserService(); + // use create service to add users + for (var user : generateSampleUsers()) { + var id = userService.createUser(user); + LOGGER.info("Add user" + user + "at" + id + "."); + } + // use list service to get users + var users = userService.listUser(); + LOGGER.info(String.valueOf(users)); + // use get service to get a user + var user = userService.getUser(1); + LOGGER.info(String.valueOf(user)); + // change password of user 1 + user.setPassword("new123"); + // use update service to update user 1 + userService.updateUser(1, user); + // use delete service to delete user 2 + userService.deleteUser(2); + // close service + userService.close(); + } + + /** + * Generate users. + * + * @return list of users. + */ + public static List generateSampleUsers() { + final var user1 = new User("ZhangSan", "zhs123"); + final var user2 = new User("LiSi", "ls123"); + final var user3 = new User("WangWu", "ww123"); + return List.of(user1, user2, user3); + } +} diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java new file mode 100644 index 000000000000..7d2275234ec1 --- /dev/null +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java @@ -0,0 +1,52 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.metamapping.model; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** User Entity. */ +@Setter +@Getter +@ToString +public class User { + private Integer id; + private String username; + private String password; + + public User() {} + + /** + * Get a user. + * + * @param username user name + * @param password user password + */ + public User(String username, String password) { + this.username = username; + this.password = password; + } +} diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java new file mode 100644 index 000000000000..e1943a6a944b --- /dev/null +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java @@ -0,0 +1,139 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.metamapping.service; + +import com.iluwatar.metamapping.model.User; +import com.iluwatar.metamapping.utils.HibernateUtil; +import java.util.ArrayList; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.hibernate.HibernateException; +import org.hibernate.SessionFactory; + +/** Service layer for user. */ +@Slf4j +public class UserService { + private static final SessionFactory factory = HibernateUtil.getSessionFactory(); + + /** + * List all users. + * + * @return list of users + */ + public List listUser() { + LOGGER.info("list all users."); + List users = new ArrayList<>(); + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + List userIter = session.createQuery("FROM User").list(); + for (User user : userIter) { + users.add(user); + } + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to get users", e); + } + return users; + } + + /** + * Add a user. + * + * @param user user entity + * @return user id + */ + public int createUser(User user) { + LOGGER.info("create user: " + user.getUsername()); + var id = -1; + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + id = (Integer) session.save(user); + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to create user", e); + } + LOGGER.info("create user " + user.getUsername() + " at " + id); + return id; + } + + /** + * Update user. + * + * @param id user id + * @param user new user entity + */ + public void updateUser(Integer id, User user) { + LOGGER.info("update user at " + id); + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + user.setId(id); + session.update(user); + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to update user", e); + } + } + + /** + * Delete user. + * + * @param id user id + */ + public void deleteUser(Integer id) { + LOGGER.info("delete user at: " + id); + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + var user = session.get(User.class, id); + session.delete(user); + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to delete user", e); + } + } + + /** + * Get user. + * + * @param id user id + * @return deleted user + */ + public User getUser(Integer id) { + LOGGER.info("get user at: " + id); + User user = null; + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + user = session.get(User.class, id); + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to get user", e); + } + return user; + } + + /** Close hibernate. */ + public void close() { + HibernateUtil.shutdown(); + } +} diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java new file mode 100644 index 000000000000..9c3c8469df55 --- /dev/null +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java @@ -0,0 +1,57 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.metamapping.utils; + +import java.sql.SQLException; +import lombok.extern.slf4j.Slf4j; +import org.h2.jdbcx.JdbcDataSource; + +/** Create h2 database. */ +@Slf4j +public class DatabaseUtil { + private static final String DB_URL = "jdbc:h2:mem:metamapping"; + private static final String CREATE_SCHEMA_SQL = + """ + DROP TABLE IF EXISTS `user_account`;CREATE TABLE `user_account` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `username` varchar(255) NOT NULL, + `password` varchar(255) NOT NULL, + PRIMARY KEY (`id`) + );"""; + + /** Hide constructor. */ + private DatabaseUtil() {} + + static { + LOGGER.info("create h2 database"); + var source = new JdbcDataSource(); + source.setURL(DB_URL); + try (var statement = source.getConnection().createStatement()) { + statement.execute(CREATE_SCHEMA_SQL); + } catch (SQLException e) { + LOGGER.error("unable to create h2 data source", e); + } + } +} diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/HibernateUtil.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/HibernateUtil.java new file mode 100644 index 000000000000..54c0b3c36640 --- /dev/null +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/HibernateUtil.java @@ -0,0 +1,56 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.metamapping.utils; + +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +/** Manage hibernate. */ +@Slf4j +public class HibernateUtil { + + @Getter private static final SessionFactory sessionFactory = buildSessionFactory(); + + /** Hide constructor. */ + private HibernateUtil() {} + + /** + * Build session factory. + * + * @return session factory + */ + private static SessionFactory buildSessionFactory() { + // Create the SessionFactory from hibernate.cfg.xml + return new Configuration().configure().buildSessionFactory(); + } + + /** Close session factory. */ + public static void shutdown() { + // Close caches and connection pools + getSessionFactory().close(); + } +} diff --git a/metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml b/metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml new file mode 100644 index 000000000000..38862c67a3f4 --- /dev/null +++ b/metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/metadata-mapping/src/main/resources/hibernate.cfg.xml b/metadata-mapping/src/main/resources/hibernate.cfg.xml new file mode 100644 index 000000000000..9c2d51b3a5ec --- /dev/null +++ b/metadata-mapping/src/main/resources/hibernate.cfg.xml @@ -0,0 +1,20 @@ + + + + + + jdbc:h2:mem:metamapping + org.h2.Driver + + 1 + + org.hibernate.dialect.H2Dialect + + false + + create-drop + + + \ No newline at end of file diff --git a/metadata-mapping/src/main/resources/logback.xml b/metadata-mapping/src/main/resources/logback.xml new file mode 100644 index 000000000000..ce9892722558 --- /dev/null +++ b/metadata-mapping/src/main/resources/logback.xml @@ -0,0 +1,35 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + diff --git a/metadata-mapping/src/test/java/com/iluwatar/metamapping/AppTest.java b/metadata-mapping/src/test/java/com/iluwatar/metamapping/AppTest.java new file mode 100644 index 000000000000..2b159b52617a --- /dev/null +++ b/metadata-mapping/src/test/java/com/iluwatar/metamapping/AppTest.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.metamapping; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Tests that metadata mapping example runs without errors. */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ + @Test + void shouldExecuteMetaMappingWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/microservices-aggregrator/README.md b/microservices-aggregrator/README.md new file mode 100644 index 000000000000..e77d997b9aeb --- /dev/null +++ b/microservices-aggregrator/README.md @@ -0,0 +1,144 @@ +--- +title: "Microservices Aggregator Pattern in Java: Building Efficient Composite Services in Java" +shortTitle: Microservices Aggregator +description: "Learn about the Microservices Aggregator Design Pattern with Java examples. Understand its intent, real-world applications, benefits, and trade-offs for scalable system design." +category: Architectural +language: en +tag: + - API design + - Client-server + - Data processing + - Decoupling + - Integration + - Microservices + - Scalability +--- + +## Also known as + +* API Composition + +## Intent of Microservices Aggregator Design Pattern + +The Microservices Aggregator pattern helps aggregate responses from multiple microservices into a single unified response, optimizing client-server interactions in scalable systems. + +## Detailed Explanation of Microservices Aggregator Pattern with Real-World Examples + +Real-world example + +> In a travel booking platform, an Aggregator Microservice consolidates data from flights, hotels, and car rentals microservices, providing a seamless user experience and enhancing scalability. Instead of the user making separate requests to each service, the platform employs an Aggregator Microservice. This microservice calls each of these services, collects their responses, and then consolidates the information into a single, unified response that is sent back to the user. This simplifies the user experience by providing all necessary travel details in one place and reduces the number of direct interactions the user needs to have with the underlying services. + +In plain words + +> Microservices Aggregator collects pieces of data from various microservices and returns an aggregate for processing. + +Stack Overflow says + +> Microservices Aggregator invokes multiple services to achieve the functionality required by the application. + +Architecture diagram + +![Microservices Aggregator Architecture Diagram](./etc/microservices-aggregator-architecture-diagram.png) + +## Programmatic Example of Microservices Aggregator Pattern in Java + +Our web marketplace utilizes an Aggregator microservice to fetch combined product and inventory information from separate microservices, ensuring efficient data processing and improved system performance. + +Let's start from the data model. Here's our `Product`. + +```java +public class Product { + private String title; + private int productInventories; + // Other properties and methods... +} +``` + +Next we can introduce our `Aggregator` microservice. It contains clients `ProductInformationClient` and `ProductInventoryClient` for calling respective microservices. + +```java + +@RestController +public class Aggregator { + + @Resource + private ProductInformationClient informationClient; + + @Resource + private ProductInventoryClient inventoryClient; + + @RequestMapping(path = "/product", method = RequestMethod.GET) + public Product getProduct() { + + var product = new Product(); + var productTitle = informationClient.getProductTitle(); + var productInventory = inventoryClient.getProductInventories(); + + //Fallback to error message + product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed")); + + //Fallback to default error inventory + product.setProductInventories(requireNonNullElse(productInventory, -1)); + + return product; + } +} +``` + +Here's the essence of information microservice implementation. Inventory microservice is similar, it just returns inventory counts. + +```java + +@RestController +public class InformationController { + @RequestMapping(value = "/information", method = RequestMethod.GET) + public String getProductTitle() { + return "The Product Title."; + } +} +``` + +Now calling our `Aggregator` REST API returns the product information. + +```bash +# Example bash call +curl http://localhost:50004/product + +# Example output +{"title":"The Product Title.","productInventories":5} +``` + +## When to Use the Microservices Aggregator Pattern in Java + +The Microservices Aggregator pattern is ideal for scenarios requiring composite responses from multiple microservices, such as in e-commerce and dashboard applications where aggregated data enhances user experience and system efficiency. + +## Benefits and Trade-offs of Microservices Aggregator Pattern + +Benefits: + +* Simplified Client: Clients interact with just one service rather than managing calls to multiple microservices, which simplifies client-side logic. +* Reduced Latency: By aggregating responses, the number of network calls is reduced, which can improve the application's overall latency. +* Decoupling: Clients are decoupled from the individual microservices, allowing for more flexibility in changing the microservices landscape without impacting clients. +* Centralized Logic: Aggregation allows for centralized transformation and logic application on the data collected from various services, which can be more efficient than handling it in the client or spreading it across multiple services. + +Trade-offs: + +* Single Point of Failure: The aggregator service can become a bottleneck or a single point of failure if not designed with high availability and scalability in mind. +* Complexity: Implementing an aggregator can introduce complexity, especially in terms of data aggregation logic and error handling when dealing with multiple services. + +## Related Java Design Patterns + +* [API Gateway](https://java-design-patterns.com/patterns/microservices-api-gateway/): The Microservices Aggregator pattern is often used in conjunction with an API Gateway, which provides a single entry point for clients to access multiple microservices. +* [Composite](https://java-design-patterns.com/patterns/composite/): The Microservices Aggregator pattern can be seen as a form of the Composite pattern, where the composite is the aggregated response from multiple microservices. +* [Facade](https://java-design-patterns.com/patterns/facade/): The Microservices Aggregator pattern can be seen as a form of the Facade pattern, where the facade is the aggregator service that provides a simplified interface to the client. + +## References and Credits + +* [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/43aGpSR) +* [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z) +* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://amzn.to/3T9g9Uj) +* [Microservice Architecture: Aligning Principles, Practices, and Culture](https://amzn.to/3T9jZNi) +* [Microservices Patterns: With examples in Java](https://amzn.to/4a5LHkP) +* [Pattern: API Composition](https://microservices.io/patterns/data/api-composition.html) +* [Production-Ready Microservices: Building Standardized Systems Across an Engineering Organization](https://amzn.to/4a0Vk4c) +* [Microservice Design Patterns (Arun Gupta)](http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/) diff --git a/microservices-aggregrator/aggregator-service/etc/aggregator-service.png b/microservices-aggregrator/aggregator-service/etc/aggregator-service.png new file mode 100644 index 000000000000..75ee82328bbe Binary files /dev/null and b/microservices-aggregrator/aggregator-service/etc/aggregator-service.png differ diff --git a/microservices-aggregrator/aggregator-service/etc/aggregator-service.urm.puml b/microservices-aggregrator/aggregator-service/etc/aggregator-service.urm.puml new file mode 100644 index 000000000000..32ab28920b87 --- /dev/null +++ b/microservices-aggregrator/aggregator-service/etc/aggregator-service.urm.puml @@ -0,0 +1,43 @@ +@startuml +package com.iluwatar.aggregator.microservices { + class Aggregator { + - informationClient : ProductInformationClient + - inventoryClient : ProductInventoryClient + + Aggregator() + + getProduct() : Product + } + class App { + + App() + + main(args : String[]) {static} + } + class Product { + - productInventories : int + - title : String + + Product() + + getProductInventories() : int + + getTitle() : String + + setProductInventories(productInventories : int) + + setTitle(title : String) + } + interface ProductInformationClient { + + getProductTitle() : String {abstract} + } + class ProductInformationClientImpl { + - LOGGER : Logger {static} + + ProductInformationClientImpl() + + getProductTitle() : String + } + interface ProductInventoryClient { + + getProductInventories() : Integer {abstract} + } + class ProductInventoryClientImpl { + - LOGGER : Logger {static} + + ProductInventoryClientImpl() + + getProductInventories() : Integer + } +} +Aggregator --> "-informationClient" ProductInformationClient +Aggregator --> "-inventoryClient" ProductInventoryClient +ProductInformationClientImpl ..|> ProductInformationClient +ProductInventoryClientImpl ..|> ProductInventoryClient +@enduml \ No newline at end of file diff --git a/microservices-aggregrator/aggregator-service/pom.xml b/microservices-aggregrator/aggregator-service/pom.xml new file mode 100644 index 000000000000..fe83826910ce --- /dev/null +++ b/microservices-aggregrator/aggregator-service/pom.xml @@ -0,0 +1,79 @@ + + + + + microservices-aggregrator + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + aggregator-service + jar + + + org.springframework + spring-webmvc + 6.2.5 + + + org.springframework.boot + spring-boot-starter-web + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.aggregator.microservices.App + + + + + + + + + diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java new file mode 100644 index 000000000000..0fd19e7efbd8 --- /dev/null +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java @@ -0,0 +1,64 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.aggregator.microservices; + +import static java.util.Objects.requireNonNullElse; + +import jakarta.annotation.Resource; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * The aggregator aggregates calls on various micro-services, collects data and further publishes + * them under a REST endpoint. + */ +@RestController +public class Aggregator { + + @Resource private ProductInformationClient informationClient; + + @Resource private ProductInventoryClient inventoryClient; + + /** + * Retrieves product data. + * + * @return a Product. + */ + @GetMapping("/product") + public Product getProduct() { + + var product = new Product(); + var productTitle = informationClient.getProductTitle(); + var productInventory = inventoryClient.getProductInventories(); + + // Fallback to error message + product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed")); + + // Fallback to default error inventory + product.setProductInventories(requireNonNullElse(productInventory, -1)); + + return product; + } +} diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java new file mode 100644 index 000000000000..26424eb9c98e --- /dev/null +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.aggregator.microservices; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** Spring Boot EntryPoint Class. */ +@SpringBootApplication +public class App { + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } +} diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Product.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Product.java new file mode 100644 index 000000000000..66626d814871 --- /dev/null +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Product.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.aggregator.microservices; + +import lombok.Getter; +import lombok.Setter; + +/** Encapsulates all the data for a Product that clients will request. */ +@Getter +@Setter +public class Product { + + /** The title of the product. */ + private String title; + + /** The inventories of the product. */ + private int productInventories; +} diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClient.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClient.java similarity index 82% rename from aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClient.java rename to microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClient.java index 81cfdc87bb36..d183656edc09 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClient.java +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClient.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,11 +24,8 @@ */ package com.iluwatar.aggregator.microservices; -/** - * Interface for the Information micro-service. - */ +/** Interface for the Information micro-service. */ public interface ProductInformationClient { String getProductTitle(); - } diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java new file mode 100644 index 000000000000..2bda000b397f --- /dev/null +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java @@ -0,0 +1,59 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.aggregator.microservices; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** An adapter to communicate with information micro-service. */ +@Slf4j +@Component +public class ProductInformationClientImpl implements ProductInformationClient { + + @Override + public String getProductTitle() { + var request = + HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:51515/information")) + .build(); + var client = HttpClient.newHttpClient(); + try { + var httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException ioe) { + LOGGER.error("IOException Occurred", ioe); + } catch (InterruptedException ie) { + LOGGER.error("InterruptedException Occurred", ie); + Thread.currentThread().interrupt(); + } + return null; + } +} diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java similarity index 80% rename from aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java rename to microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java index c5953dc30dc0..02ebac8732d6 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,10 +24,8 @@ */ package com.iluwatar.aggregator.microservices; -/** - * Interface to Inventory micro-service. - */ +/** Interface to Inventory micro-service. */ public interface ProductInventoryClient { - int getProductInventories(); + Integer getProductInventories(); } diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java new file mode 100644 index 000000000000..d5a918e4629d --- /dev/null +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java @@ -0,0 +1,65 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.aggregator.microservices; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** An adapter to communicate with inventory micro-service. */ +@Slf4j +@Component +public class ProductInventoryClientImpl implements ProductInventoryClient { + + @Override + public Integer getProductInventories() { + var response = ""; + + var request = + HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:51516/inventories")) + .build(); + var client = HttpClient.newHttpClient(); + try { + var httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString()); + response = httpResponse.body(); + } catch (IOException ioe) { + LOGGER.error("IOException Occurred", ioe); + } catch (InterruptedException ie) { + LOGGER.error("InterruptedException Occurred", ie); + Thread.currentThread().interrupt(); + } + if ("".equalsIgnoreCase(response)) { + return null; + } else { + return Integer.parseInt(response); + } + } +} diff --git a/microservices-aggregrator/aggregator-service/src/main/resources/application.properties b/microservices-aggregrator/aggregator-service/src/main/resources/application.properties new file mode 100644 index 000000000000..79c2622b2e47 --- /dev/null +++ b/microservices-aggregrator/aggregator-service/src/main/resources/application.properties @@ -0,0 +1,24 @@ +# +# The MIT License +# Copyright © 2014-2021 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. +# + +server.port=50004 \ No newline at end of file diff --git a/microservices-aggregrator/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java b/microservices-aggregrator/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java new file mode 100644 index 000000000000..914e15dad28d --- /dev/null +++ b/microservices-aggregrator/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java @@ -0,0 +1,64 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.aggregator.microservices; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +/** Test Aggregation of domain objects */ +class AggregatorTest { + + @InjectMocks private Aggregator aggregator; + + @Mock private ProductInformationClient informationClient; + + @Mock private ProductInventoryClient inventoryClient; + + @BeforeEach + void setup() { + MockitoAnnotations.openMocks(this); + } + + /** Tests getting the data for a desktop client */ + @Test + void testGetProduct() { + var title = "The Product Title."; + var inventories = 5; + + when(informationClient.getProductTitle()).thenReturn(title); + when(inventoryClient.getProductInventories()).thenReturn(inventories); + + var testProduct = aggregator.getProduct(); + + assertEquals(title, testProduct.getTitle()); + assertEquals(inventories, testProduct.getProductInventories()); + } +} diff --git a/microservices-aggregrator/etc/aggregator-microservices.urm.puml b/microservices-aggregrator/etc/aggregator-microservices.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/microservices-aggregrator/etc/aggregator-microservices.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/microservices-aggregrator/etc/microservices-aggregator-architecture-diagram.png b/microservices-aggregrator/etc/microservices-aggregator-architecture-diagram.png new file mode 100644 index 000000000000..34d5113e5a3a Binary files /dev/null and b/microservices-aggregrator/etc/microservices-aggregator-architecture-diagram.png differ diff --git a/microservices-aggregrator/etc/microservices-aggregrator.urm.puml b/microservices-aggregrator/etc/microservices-aggregrator.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/microservices-aggregrator/etc/microservices-aggregrator.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/microservices-aggregrator/information-microservice/etc/information-microservice.urm.puml b/microservices-aggregrator/information-microservice/etc/information-microservice.urm.puml new file mode 100644 index 000000000000..e0a2ccb24fb2 --- /dev/null +++ b/microservices-aggregrator/information-microservice/etc/information-microservice.urm.puml @@ -0,0 +1,12 @@ +@startuml +package com.iluwatar.information.microservice { + class InformationApplication { + + InformationApplication() + + main(args : String[]) {static} + } + class InformationController { + + InformationController() + + getProductTitle() : String + } +} +@enduml \ No newline at end of file diff --git a/microservices-aggregrator/information-microservice/pom.xml b/microservices-aggregrator/information-microservice/pom.xml new file mode 100644 index 000000000000..5b27df62516d --- /dev/null +++ b/microservices-aggregrator/information-microservice/pom.xml @@ -0,0 +1,72 @@ + + + + + microservices-aggregrator + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + information-microservice + jar + + + org.springframework + spring-webmvc + 6.2.5 + + + org.springframework.boot + spring-boot-starter-web + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.information.microservices.InformationApplication + + + + + + + + + diff --git a/aggregator-microservices/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationApplication.java b/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationApplication.java similarity index 82% rename from aggregator-microservices/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationApplication.java rename to microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationApplication.java index 67d568e17dc4..68ff8856eb9b 100644 --- a/aggregator-microservices/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationApplication.java +++ b/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationApplication.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -25,9 +27,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -/** - * Inventory Application starts container (Spring Boot) and exposes the Inventory micro-service. - */ +/** Inventory Application starts container (Spring Boot) and exposes the Inventory micro-service. */ @SpringBootApplication public class InformationApplication { diff --git a/aggregator-microservices/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java b/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java similarity index 76% rename from aggregator-microservices/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java rename to microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java index 63b6fb9d5c0b..cc826e497195 100644 --- a/aggregator-microservices/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java +++ b/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,22 +24,19 @@ */ package com.iluwatar.information.microservice; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -/** - * Controller providing endpoints to retrieve information about products - */ +/** Controller providing endpoints to retrieve information about products. */ @RestController public class InformationController { /** - * Endpoint to retrieve a product's informations. + * Endpoint to retrieve a product's information. * * @return product inventory. */ - @RequestMapping(value = "/information", method = RequestMethod.GET) + @GetMapping("/information") public String getProductTitle() { return "The Product Title."; } diff --git a/microservices-aggregrator/information-microservice/src/main/resources/application.properties b/microservices-aggregrator/information-microservice/src/main/resources/application.properties new file mode 100644 index 000000000000..8f2a5f1748ae --- /dev/null +++ b/microservices-aggregrator/information-microservice/src/main/resources/application.properties @@ -0,0 +1,24 @@ +# +# The MIT License +# Copyright © 2014-2021 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. +# + +server.port=51515 \ No newline at end of file diff --git a/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java b/microservices-aggregrator/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java similarity index 75% rename from aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java rename to microservices-aggregrator/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java index d030cfcb4d0e..3f344d9d8d39 100644 --- a/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java +++ b/microservices-aggregrator/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,22 +24,17 @@ */ package com.iluwatar.information.microservice; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test for Information Rest Controller - */ -public class InformationControllerTest { - - @Test - public void shouldGetProductTitle() { - InformationController infoController = new InformationController(); +import org.junit.jupiter.api.Test; - String title = infoController.getProductTitle(); +/** Test for Information Rest Controller */ +class InformationControllerTest { + @Test + void shouldGetProductTitle() { + var infoController = new InformationController(); + var title = infoController.getProductTitle(); assertEquals("The Product Title.", title); } - } diff --git a/microservices-aggregrator/inventory-microservice/etc/inventory-microservice.urm.puml b/microservices-aggregrator/inventory-microservice/etc/inventory-microservice.urm.puml new file mode 100644 index 000000000000..90f327e07db8 --- /dev/null +++ b/microservices-aggregrator/inventory-microservice/etc/inventory-microservice.urm.puml @@ -0,0 +1,12 @@ +@startuml +package com.iluwatar.inventory.microservice { + class InventoryApplication { + + InventoryApplication() + + main(args : String[]) {static} + } + class InventoryController { + + InventoryController() + + getProductInventories() : int + } +} +@enduml \ No newline at end of file diff --git a/microservices-aggregrator/inventory-microservice/pom.xml b/microservices-aggregrator/inventory-microservice/pom.xml new file mode 100644 index 000000000000..64203b09edcf --- /dev/null +++ b/microservices-aggregrator/inventory-microservice/pom.xml @@ -0,0 +1,72 @@ + + + + + microservices-aggregrator + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + inventory-microservice + jar + + + org.springframework + spring-webmvc + 6.2.5 + + + org.springframework.boot + spring-boot-starter-web + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.inventory.microservices.InventoryApplication + + + + + + + + + diff --git a/aggregator-microservices/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryApplication.java b/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryApplication.java similarity index 82% rename from aggregator-microservices/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryApplication.java rename to microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryApplication.java index 73b4c0b18925..5627c37c9161 100644 --- a/aggregator-microservices/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryApplication.java +++ b/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryApplication.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -25,14 +27,11 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -/** - * Inventory Application starts container (Spring Boot) and exposes the Inventory micro-service. - */ +/** Inventory Application starts container (Spring Boot) and exposes the Inventory micro-service. */ @SpringBootApplication public class InventoryApplication { public static void main(String[] args) { SpringApplication.run(InventoryApplication.class, args); } - } diff --git a/aggregator-microservices/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java b/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java similarity index 79% rename from aggregator-microservices/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java rename to microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java index e6b2eca80863..bf5abd510bc0 100644 --- a/aggregator-microservices/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java +++ b/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,13 +24,10 @@ */ package com.iluwatar.inventory.microservice; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -/** - * Controller providing endpoints to retrieve product inventories - */ +/** Controller providing endpoints to retrieve product inventories. */ @RestController public class InventoryController { @@ -37,9 +36,8 @@ public class InventoryController { * * @return product inventory. */ - @RequestMapping(value = "/inventories", method = RequestMethod.GET) + @GetMapping("/inventories") public int getProductInventories() { return 5; } - } diff --git a/microservices-aggregrator/inventory-microservice/src/main/resources/application.properties b/microservices-aggregrator/inventory-microservice/src/main/resources/application.properties new file mode 100644 index 000000000000..380791d88f92 --- /dev/null +++ b/microservices-aggregrator/inventory-microservice/src/main/resources/application.properties @@ -0,0 +1,24 @@ +# +# The MIT License +# Copyright © 2014-2021 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. +# + +server.port=51516 \ No newline at end of file diff --git a/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java b/microservices-aggregrator/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java similarity index 75% rename from aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java rename to microservices-aggregrator/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java index 78af8582e00e..27b41594d30b 100644 --- a/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java +++ b/microservices-aggregrator/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java @@ -1,17 +1,19 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä - *

    + * Copyright © 2014-2022 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 @@ -22,20 +24,17 @@ */ package com.iluwatar.inventory.microservice; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test Inventory Rest Controller - */ -public class InventoryControllerTest { - @Test - public void testGetProductInventories() throws Exception { - InventoryController inventoryController = new InventoryController(); +import org.junit.jupiter.api.Test; - int numberOfInventories = inventoryController.getProductInventories(); +/** Test Inventory Rest Controller */ +class InventoryControllerTest { + @Test + void testGetProductInventories() { + var inventoryController = new InventoryController(); + var numberOfInventories = inventoryController.getProductInventories(); assertEquals(5, numberOfInventories); } } diff --git a/microservices-aggregrator/pom.xml b/microservices-aggregrator/pom.xml new file mode 100644 index 000000000000..bf1edb1c8b76 --- /dev/null +++ b/microservices-aggregrator/pom.xml @@ -0,0 +1,42 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + microservices-aggregrator + pom + + information-microservice + aggregator-service + inventory-microservice + + diff --git a/microservices-api-gateway/README.md b/microservices-api-gateway/README.md new file mode 100644 index 000000000000..ff5d4099376f --- /dev/null +++ b/microservices-api-gateway/README.md @@ -0,0 +1,181 @@ +--- +title: "Microservices API Gateway Pattern in Java: Simplifying Service Access with a Unified Endpoint" +shortTitle: Microservices API Gateway +description: "Learn how the API Gateway pattern simplifies client-side development, enhances security, and optimizes communication in microservices architecture. Explore examples, benefits, and best practices." +category: Integration +language: en +tag: + - API design + - Cloud distributed + - Decoupling + - Enterprise patterns + - Integration + - Microservices + - Scalability + - Security +--- + +## Intent of Microservices API Gateway Design Pattern + +The API Gateway design pattern aims to provide a unified interface to a set of microservices within a microservices architecture. It acts as a single entry point for clients, routing requests to the appropriate microservices and aggregating results, thereby simplifying the client-side code. + +## Also known as + +* API Facade +* Backend for Frontends (BFF) + +## Detailed Explanation of Microservices API Gateway Pattern with Real-World Examples + +Real-world example + +> In a large e-commerce platform, an API Gateway is used as the single entry point for all client requests, simplifying client-side development. When a user visits the site or uses the mobile app, their requests for product information, user authentication, order processing, and payment are all routed through the API Gateway. The API Gateway handles tasks such as user authentication, rate limiting to prevent abuse, and logging for monitoring purposes, enhancing overall security optimization. This setup simplifies the client interface and ensures that all backend microservices can evolve independently without affecting the client directly, thereby enhancing microservices communication. This also enhances security by providing a centralized point to enforce policies and monitor traffic. + +In plain words + +> For a system implemented using microservices architecture, API Gateway is the single entry point that aggregates the calls to the individual microservices. + +Wikipedia says + +> API Gateway is a server that acts as an API front-end, receives API requests, enforces throttling and security policies, passes requests to the back-end service and then passes the response back to the requester. A gateway often includes a transformation engine to orchestrate and modify the requests and responses on the fly. A gateway can also provide functionality such as collecting analytics data and providing caching. The gateway can provide functionality to support authentication, authorization, security, audit and regulatory compliance. + +Sequence diagram + +![Microservices API Gateway sequence diagram](./etc/microservices-api-gateway-sequence-diagram.png) + +## Programmatic Example of Microservice API Gateway in Java + +This implementation shows what the API Gateway pattern could look like for an e-commerce site. The`ApiGateway` makes calls to the Image and Price microservices using the `ImageClientImpl` and `PriceClientImpl` respectively. Customers viewing the site on a desktop device can see both price information and an image of a product, so the `ApiGateway` calls both of the microservices and aggregates the data in the `DesktopProduct` model. However, mobile users only see price information; they do not see a product image. For mobile users, the `ApiGateway` only retrieves price information, which it uses to populate the `MobileProduct`. + +Here's the Image microservice implementation. + +```java +public interface ImageClient { + String getImagePath(); +} + +public class ImageClientImpl implements ImageClient { + @Override + public String getImagePath() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50005/image-path")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +Here's the Price microservice implementation. + +```java +public interface PriceClient { + String getPrice(); +} + +public class PriceClientImpl implements PriceClient { + + @Override + public String getPrice() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:50006/price")) + .build(); + + try { + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + return httpResponse.body(); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } +} +``` + +Here we can see how API Gateway maps the requests to the microservices. + +```java +public class ApiGateway { + + @Resource + private ImageClient imageClient; + + @Resource + private PriceClient priceClient; + + @RequestMapping(path = "/desktop", method = RequestMethod.GET) + public DesktopProduct getProductDesktop() { + var desktopProduct = new DesktopProduct(); + desktopProduct.setImagePath(imageClient.getImagePath()); + desktopProduct.setPrice(priceClient.getPrice()); + return desktopProduct; + } + + @RequestMapping(path = "/mobile", method = RequestMethod.GET) + public MobileProduct getProductMobile() { + var mobileProduct = new MobileProduct(); + mobileProduct.setPrice(priceClient.getPrice()); + return mobileProduct; + } +} +``` + +## When to Use the Microservices API Gateway Pattern in Java + +* When building a microservices architecture, and there's a need to abstract the complexity of microservices from the client. +* When multiple microservices need to be consumed in a single request. +* For authentication, authorization, and security enforcement at a single point. +* To optimize communication between clients and services, especially in a cloud environment. + +## Microservices API Gateway Pattern Java Tutorials + +* [Exploring the New Spring Cloud Gateway (Baeldung)](https://www.baeldung.com/spring-cloud-gateway) +* [Spring Cloud - Gateway(tutorialspoint)](https://www.tutorialspoint.com/spring_cloud/spring_cloud_gateway.htm) +* [Getting Started With Spring Cloud Gateway (DZone)](https://dzone.com/articles/getting-started-with-spring-cloud-gateway) + +## Benefits and Trade-offs of Microservices API Gateway Pattern + +Benefits: + +* Decouples client from microservices, allowing services to evolve independently. +* Simplifies client by aggregating requests to multiple services. +* Centralized location for cross-cutting concerns like security, logging, and rate limiting. +* Potential for performance optimizations like caching and request compression. + +Trade-offs: + +* Introduces a single point of failure, although this can be mitigated with high availability setups. +* Can become a bottleneck if not properly scaled. +* Adds complexity in terms of deployment and management. + +## Real-World Applications of Microservices API Gateway Pattern in Java + +* E-commerce platforms where multiple services (product info, pricing, inventory) are aggregated for a single view. +* Mobile applications that consume various backend services but require a simplified interface for ease of use. +* Cloud-native applications that leverage multiple microservices architectures. + +## Related Java Design Patterns + +* [Aggregator Microservice](https://java-design-patterns.com/patterns/microservices-aggregator/) - The API Gateway pattern is often used in conjunction with the Aggregator Microservice pattern to provide a unified interface to a set of microservices. +* [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/) - API Gateways can use the Circuit Breaker pattern to prevent cascading failures when calling multiple microservices. +* [Proxy](https://java-design-patterns.com/patterns/proxy/) - The API Gateway pattern is a specialized form of the Proxy pattern, where the gateway acts as a single entry point for clients, routing requests to the appropriate microservices and aggregating results. + +## References and Credits + +* [Building Microservices](https://amzn.to/3UACtrU) +* [Cloud Native Patterns: Designing change-tolerant software](https://amzn.to/3uV12WN) +* [Designing Data-Intensive Applications](https://amzn.to/3PfRk7Y) +* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O) +* [API Gateway (microservices.io)](http://microservices.io/patterns/apigateway.html) +* [Building Microservices: Using an API Gateway (nginx)](https://www.nginx.com/blog/building-microservices-using-an-api-gateway/) diff --git a/microservices-api-gateway/api-gateway-service/etc/api-gateway-service.urm.puml b/microservices-api-gateway/api-gateway-service/etc/api-gateway-service.urm.puml new file mode 100644 index 000000000000..5fabc6a0fab4 --- /dev/null +++ b/microservices-api-gateway/api-gateway-service/etc/api-gateway-service.urm.puml @@ -0,0 +1,48 @@ +@startuml +package com.iluwatar.api.gateway { + class ApiGateway { + - imageClient : ImageClient + - priceClient : PriceClient + + ApiGateway() + + getProductDesktop() : DesktopProduct + + getProductMobile() : MobileProduct + } + class App { + + App() + + main(args : String[]) {static} + } + class DesktopProduct { + - imagePath : String + - price : String + + DesktopProduct() + + getImagePath() : String + + getPrice() : String + + setImagePath(imagePath : String) + + setPrice(price : String) + } + interface ImageClient { + + getImagePath() : String {abstract} + } + class ImageClientImpl { + + ImageClientImpl() + + getImagePath() : String + } + class MobileProduct { + - price : String + + MobileProduct() + + getPrice() : String + + setPrice(price : String) + } + interface PriceClient { + + getPrice() : String {abstract} + } + class PriceClientImpl { + + PriceClientImpl() + + getPrice() : String + } +} +ApiGateway --> "-imageClient" ImageClient +ApiGateway --> "-priceClient" PriceClient +ImageClientImpl ..|> ImageClient +PriceClientImpl ..|> PriceClient +@enduml \ No newline at end of file diff --git a/microservices-api-gateway/api-gateway-service/pom.xml b/microservices-api-gateway/api-gateway-service/pom.xml new file mode 100644 index 000000000000..b84bebe6f237 --- /dev/null +++ b/microservices-api-gateway/api-gateway-service/pom.xml @@ -0,0 +1,77 @@ + + + + + microservices-api-gateway + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + api-gateway-service + jar + + + org.springframework + spring-webmvc + 6.2.5 + + + org.springframework.boot + spring-boot-starter-web + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.api.gateway.App + + + + + + + + + diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java new file mode 100644 index 000000000000..c4110509747c --- /dev/null +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java @@ -0,0 +1,65 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.api.gateway; + +import jakarta.annotation.Resource; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * The ApiGateway aggregates calls to microservices based on the needs of the individual clients. + */ +@RestController +public class ApiGateway { + + @Resource private ImageClient imageClient; + + @Resource private PriceClient priceClient; + + /** + * Retrieves product information that desktop clients need. + * + * @return Product information for clients on a desktop + */ + @GetMapping("/desktop") + public DesktopProduct getProductDesktop() { + var desktopProduct = new DesktopProduct(); + desktopProduct.setImagePath(imageClient.getImagePath()); + desktopProduct.setPrice(priceClient.getPrice()); + return desktopProduct; + } + + /** + * Retrieves product information that mobile clients need. + * + * @return Product information for clients on a mobile device + */ + @GetMapping("/mobile") + public MobileProduct getProductMobile() { + var mobileProduct = new MobileProduct(); + mobileProduct.setPrice(priceClient.getPrice()); + return mobileProduct; + } +} diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java new file mode 100644 index 000000000000..4754ba0a55a2 --- /dev/null +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java @@ -0,0 +1,65 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.api.gateway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * With the Microservices pattern, a client may need data from multiple different microservices. If + * the client called each microservice directly, that could contribute to longer load times, since + * the client would have to make a network request for each microservice called. Moreover, having + * the client call each microservice directly ties the client to that microservice - if the internal + * implementations of the microservices change (for example, if two microservices are combined + * sometime in the future) or if the location (host and port) of a microservice changes, then every + * client that makes use of those microservices must be updated. + * + *

    The intent of the API Gateway pattern is to alleviate some of these issues. In the API Gateway + * pattern, an additional entity (the API Gateway) is placed between the client and the + * microservices. The job of the API Gateway is to aggregate the calls to the microservices. Rather + * than the client calling each microservice individually, the client calls the API Gateway a single + * time. The API Gateway then calls each of the microservices that the client needs. + * + *

    This implementation shows what the API Gateway pattern could look like for an e-commerce site. + * The {@link ApiGateway} makes calls to the Image and Price microservices using the {@link + * ImageClientImpl} and {@link PriceClientImpl} respectively. Customers viewing the site on a + * desktop device can see both price information and an image of a product, so the {@link + * ApiGateway} calls both of the microservices and aggregates the data in the {@link DesktopProduct} + * model. However, mobile users only see price information; they do not see a product image. For + * mobile users, the {@link ApiGateway} only retrieves price information, which it uses to populate + * the {@link MobileProduct}. + */ +@SpringBootApplication +public class App { + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } +} diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java new file mode 100644 index 000000000000..40cc795fd9a0 --- /dev/null +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.api.gateway; + +import lombok.Getter; +import lombok.Setter; + +/** Encapsulates all of the information that a desktop client needs to display a product. */ +@Getter +@Setter +public class DesktopProduct { + + /** The price of the product. */ + private String price; + + /** The path to the image of the product. */ + private String imagePath; +} diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java similarity index 82% rename from api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java rename to microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java index dca012a412d2..9f7e08c89f43 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,9 +24,7 @@ */ package com.iluwatar.api.gateway; -/** - * An interface used to communicate with the Image microservice - */ +/** An interface used to communicate with the Image microservice. */ public interface ImageClient { String getImagePath(); } diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java new file mode 100644 index 000000000000..2ebef5bd39b3 --- /dev/null +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java @@ -0,0 +1,79 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.api.gateway; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** An adapter to communicate with the Image microservice. */ +@Slf4j +@Component +public class ImageClientImpl implements ImageClient { + + /** + * Makes a simple HTTP Get request to the Image microservice. + * + * @return The path to the image + */ + @Override + public String getImagePath() { + + var httpClient = HttpClient.newHttpClient(); + var httpGet = + HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:50005/image-path")).build(); + + try { + LOGGER.info("Sending request to fetch image path"); + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + logResponse(httpResponse); + return httpResponse.body(); + } catch (IOException ioe) { + LOGGER.error("Failure occurred while getting image path", ioe); + } catch (InterruptedException ie) { + LOGGER.error("Failure occurred while getting image path", ie); + Thread.currentThread().interrupt(); + } + + return null; + } + + private void logResponse(HttpResponse httpResponse) { + if (isSuccessResponse(httpResponse.statusCode())) { + LOGGER.info("Image path received successfully"); + } else { + LOGGER.warn("Image path request failed"); + } + } + + private boolean isSuccessResponse(int responseCode) { + return responseCode >= 200 && responseCode <= 299; + } +} diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java similarity index 76% rename from api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java rename to microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java index c057379fca81..ed42248eadee 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,13 @@ */ package com.iluwatar.api.gateway; -/** - * Encapsulates all of the information that mobile client needs to display a product. - */ +import lombok.Getter; +import lombok.Setter; + +/** Encapsulates all of the information that mobile client needs to display a product. */ +@Getter +@Setter public class MobileProduct { - /** - * The price of the product - */ + /** The price of the product. */ private String price; - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } } diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java similarity index 82% rename from api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java rename to microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java index 4f4d2bbfc1eb..003fa478be2f 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,9 +24,7 @@ */ package com.iluwatar.api.gateway; -/** - * An interface used to communicate with the Price microservice - */ +/** An interface used to communicate with the Price microservice. */ public interface PriceClient { String getPrice(); } diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java new file mode 100644 index 000000000000..47fb0617db6c --- /dev/null +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java @@ -0,0 +1,78 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.api.gateway; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** An adapter to communicate with the Price microservice. */ +@Slf4j +@Component +public class PriceClientImpl implements PriceClient { + + /** + * Makes a simple HTTP Get request to the Price microservice. + * + * @return The price of the product + */ + @Override + public String getPrice() { + var httpClient = HttpClient.newHttpClient(); + var httpGet = + HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:50006/price")).build(); + + try { + LOGGER.info("Sending request to fetch price info"); + var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + logResponse(httpResponse); + return httpResponse.body(); + } catch (IOException e) { + LOGGER.error("Failure occurred while getting price info", e); + } catch (InterruptedException e) { + LOGGER.error("Failure occurred while getting price info", e); + Thread.currentThread().interrupt(); + } + + return null; + } + + private void logResponse(HttpResponse httpResponse) { + if (isSuccessResponse(httpResponse.statusCode())) { + LOGGER.info("Price info received successfully"); + } else { + LOGGER.warn("Price info request failed"); + } + } + + private boolean isSuccessResponse(int responseCode) { + return responseCode >= 200 && responseCode <= 299; + } +} diff --git a/microservices-api-gateway/api-gateway-service/src/main/resources/application.properties b/microservices-api-gateway/api-gateway-service/src/main/resources/application.properties new file mode 100644 index 000000000000..79c2622b2e47 --- /dev/null +++ b/microservices-api-gateway/api-gateway-service/src/main/resources/application.properties @@ -0,0 +1,24 @@ +# +# The MIT License +# Copyright © 2014-2021 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. +# + +server.port=50004 \ No newline at end of file diff --git a/microservices-api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java b/microservices-api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java new file mode 100644 index 000000000000..f177512f5976 --- /dev/null +++ b/microservices-api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java @@ -0,0 +1,74 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.api.gateway; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +/** Test API Gateway Pattern */ +class ApiGatewayTest { + + @InjectMocks private ApiGateway apiGateway; + + @Mock private ImageClient imageClient; + + @Mock private PriceClient priceClient; + + @BeforeEach + void setup() { + MockitoAnnotations.openMocks(this); + } + + /** Tests getting the data for a desktop client */ + @Test + void testGetProductDesktop() { + var imagePath = "/product-image.png"; + var price = "20"; + when(imageClient.getImagePath()).thenReturn(imagePath); + when(priceClient.getPrice()).thenReturn(price); + + var desktopProduct = apiGateway.getProductDesktop(); + + assertEquals(price, desktopProduct.getPrice()); + assertEquals(imagePath, desktopProduct.getImagePath()); + } + + /** Tests getting the data for a mobile client */ + @Test + void testGetProductMobile() { + var price = "20"; + when(priceClient.getPrice()).thenReturn(price); + + var mobileProduct = apiGateway.getProductMobile(); + + assertEquals(price, mobileProduct.getPrice()); + } +} diff --git a/microservices-api-gateway/etc/api-gateway.png b/microservices-api-gateway/etc/api-gateway.png new file mode 100644 index 000000000000..bb3ec2e2e1a8 Binary files /dev/null and b/microservices-api-gateway/etc/api-gateway.png differ diff --git a/api-gateway/etc/api-gateway.ucls b/microservices-api-gateway/etc/api-gateway.ucls similarity index 100% rename from api-gateway/etc/api-gateway.ucls rename to microservices-api-gateway/etc/api-gateway.ucls diff --git a/microservices-api-gateway/etc/api-gateway.urm.puml b/microservices-api-gateway/etc/api-gateway.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/microservices-api-gateway/etc/api-gateway.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/microservices-api-gateway/etc/microservices-api-gateway-sequence-diagram.png b/microservices-api-gateway/etc/microservices-api-gateway-sequence-diagram.png new file mode 100644 index 000000000000..9186b32322a7 Binary files /dev/null and b/microservices-api-gateway/etc/microservices-api-gateway-sequence-diagram.png differ diff --git a/microservices-api-gateway/etc/microservices-api-gateway.urm.puml b/microservices-api-gateway/etc/microservices-api-gateway.urm.puml new file mode 100644 index 000000000000..02af47ddf261 --- /dev/null +++ b/microservices-api-gateway/etc/microservices-api-gateway.urm.puml @@ -0,0 +1,2 @@ +@startuml +@enduml \ No newline at end of file diff --git a/api-gateway/image-microservice/etc/image-microservice.png b/microservices-api-gateway/image-microservice/etc/image-microservice.png similarity index 100% rename from api-gateway/image-microservice/etc/image-microservice.png rename to microservices-api-gateway/image-microservice/etc/image-microservice.png diff --git a/api-gateway/image-microservice/etc/image-microservice.ucls b/microservices-api-gateway/image-microservice/etc/image-microservice.ucls similarity index 100% rename from api-gateway/image-microservice/etc/image-microservice.ucls rename to microservices-api-gateway/image-microservice/etc/image-microservice.ucls diff --git a/microservices-api-gateway/image-microservice/etc/image-microservice.urm.puml b/microservices-api-gateway/image-microservice/etc/image-microservice.urm.puml new file mode 100644 index 000000000000..130dac9de383 --- /dev/null +++ b/microservices-api-gateway/image-microservice/etc/image-microservice.urm.puml @@ -0,0 +1,12 @@ +@startuml +package com.iluwatar.image.microservice { + class ImageApplication { + + ImageApplication() + + main(args : String[]) {static} + } + class ImageController { + + ImageController() + + getImagePath() : String + } +} +@enduml \ No newline at end of file diff --git a/microservices-api-gateway/image-microservice/pom.xml b/microservices-api-gateway/image-microservice/pom.xml new file mode 100644 index 000000000000..7c08fe2ec0e1 --- /dev/null +++ b/microservices-api-gateway/image-microservice/pom.xml @@ -0,0 +1,72 @@ + + + + + microservices-api-gateway + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + image-microservice + jar + + + org.springframework + spring-webmvc + 6.2.5 + + + org.springframework.boot + spring-boot-starter-web + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.image.microservice.ImageApplication + + + + + + + + + diff --git a/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageApplication.java b/microservices-api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageApplication.java similarity index 82% rename from api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageApplication.java rename to microservices-api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageApplication.java index c4c75c0f0c29..97abcb5041bc 100644 --- a/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageApplication.java +++ b/microservices-api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageApplication.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -26,16 +28,16 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; /** - * ImageApplication starts up Spring Boot, exposing endpoints for the Image microservice through - * the {@link ImageController}. + * ImageApplication starts up Spring Boot, exposing endpoints for the Image microservice through the + * {@link ImageController}. */ @SpringBootApplication public class ImageApplication { /** - * Microservice entry point - * @param args - * command line args + * Microservice entry point. + * + * @param args command line args */ public static void main(String[] args) { SpringApplication.run(ImageApplication.class, args); diff --git a/microservices-api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java b/microservices-api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java new file mode 100644 index 000000000000..a737f0b8ddd1 --- /dev/null +++ b/microservices-api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.image.microservice; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +/** Exposes the Image microservice's endpoints. */ +@Slf4j +@RestController +public class ImageController { + + /** + * An endpoint for a user to retrieve an image path. + * + * @return An image path + */ + @GetMapping("/image-path") + public String getImagePath() { + LOGGER.info("Successfully found image path"); + return "/product-image.png"; + } +} diff --git a/microservices-api-gateway/image-microservice/src/main/resources/application.properties b/microservices-api-gateway/image-microservice/src/main/resources/application.properties new file mode 100644 index 000000000000..057678c690c7 --- /dev/null +++ b/microservices-api-gateway/image-microservice/src/main/resources/application.properties @@ -0,0 +1,24 @@ +# +# The MIT License +# Copyright © 2014-2021 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. +# + +server.port=50005 \ No newline at end of file diff --git a/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java b/microservices-api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java similarity index 77% rename from api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java rename to microservices-api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java index df9b479aedb4..f2ff0c747ec4 100644 --- a/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java +++ b/microservices-api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,17 @@ */ package com.iluwatar.image.microservice; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test for Image Rest Controller - */ -public class ImageControllerTest { - @Test - public void testGetImagePath() { - ImageController imageController = new ImageController(); +import org.junit.jupiter.api.Test; - String imagePath = imageController.getImagePath(); +/** Test for Image Rest Controller */ +class ImageControllerTest { + @Test + void testGetImagePath() { + var imageController = new ImageController(); + var imagePath = imageController.getImagePath(); assertEquals("/product-image.png", imagePath); } } diff --git a/microservices-api-gateway/pom.xml b/microservices-api-gateway/pom.xml new file mode 100644 index 000000000000..18022d957ed2 --- /dev/null +++ b/microservices-api-gateway/pom.xml @@ -0,0 +1,42 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + microservices-api-gateway + pom + + image-microservice + price-microservice + api-gateway-service + + diff --git a/api-gateway/price-microservice/etc/price-microservice.png b/microservices-api-gateway/price-microservice/etc/price-microservice.png similarity index 100% rename from api-gateway/price-microservice/etc/price-microservice.png rename to microservices-api-gateway/price-microservice/etc/price-microservice.png diff --git a/api-gateway/price-microservice/etc/price-microservice.ucls b/microservices-api-gateway/price-microservice/etc/price-microservice.ucls similarity index 100% rename from api-gateway/price-microservice/etc/price-microservice.ucls rename to microservices-api-gateway/price-microservice/etc/price-microservice.ucls diff --git a/microservices-api-gateway/price-microservice/etc/price-microservice.urm.puml b/microservices-api-gateway/price-microservice/etc/price-microservice.urm.puml new file mode 100644 index 000000000000..9893c9c601d1 --- /dev/null +++ b/microservices-api-gateway/price-microservice/etc/price-microservice.urm.puml @@ -0,0 +1,12 @@ +@startuml +package com.iluwatar.price.microservice { + class PriceApplication { + + PriceApplication() + + main(args : String[]) {static} + } + class PriceController { + + PriceController() + + getPrice() : String + } +} +@enduml \ No newline at end of file diff --git a/microservices-api-gateway/price-microservice/pom.xml b/microservices-api-gateway/price-microservice/pom.xml new file mode 100644 index 000000000000..8e95948aff6e --- /dev/null +++ b/microservices-api-gateway/price-microservice/pom.xml @@ -0,0 +1,72 @@ + + + + + microservices-api-gateway + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + price-microservice + jar + + + org.springframework + spring-webmvc + 6.2.5 + + + org.springframework.boot + spring-boot-starter-web + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.price.microservices.PriceApplication + + + + + + + + + diff --git a/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceApplication.java b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceApplication.java similarity index 82% rename from api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceApplication.java rename to microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceApplication.java index b12082328bcd..1745307f3566 100644 --- a/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceApplication.java +++ b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceApplication.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -26,16 +28,16 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; /** - * PriceApplication starts up Spring Boot, exposing endpoints for the Price microservice through - * the {@link PriceController}. + * PriceApplication starts up Spring Boot, exposing endpoints for the Price microservice through the + * {@link PriceController}. */ @SpringBootApplication public class PriceApplication { /** - * Microservice entry point - * @param args - * command line args + * Microservice entry point. + * + * @param args command line args */ public static void main(String[] args) { SpringApplication.run(PriceApplication.class, args); diff --git a/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java new file mode 100644 index 000000000000..695d3aadb34e --- /dev/null +++ b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java @@ -0,0 +1,47 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.price.microservice; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +/** Exposes the Price microservice's endpoints. */ +@RestController +@RequiredArgsConstructor +public class PriceController { + + private final PriceService priceService; + + /** + * An endpoint for a user to retrieve a product's price. + * + * @return A product's price + */ + @GetMapping("/price") + public String getPrice() { + return priceService.getPrice(); + } +} diff --git a/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceService.java b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceService.java new file mode 100644 index 000000000000..253bab4e5f81 --- /dev/null +++ b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceService.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.price.microservice; + +/** Service to get a product's price. */ +public interface PriceService { + + /** + * Getting the price of a product. + * + * @return A product's price + */ + String getPrice(); +} diff --git a/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceServiceImpl.java b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceServiceImpl.java new file mode 100644 index 000000000000..1338313fe2de --- /dev/null +++ b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceServiceImpl.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.price.microservice; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +/** {@inheritDoc} */ +@Service +@Slf4j +public class PriceServiceImpl implements PriceService { + + /** {@inheritDoc} */ + @Override + public String getPrice() { + LOGGER.info("Successfully found price info"); + return "20"; + } +} diff --git a/microservices-api-gateway/price-microservice/src/main/resources/application.properties b/microservices-api-gateway/price-microservice/src/main/resources/application.properties new file mode 100644 index 000000000000..ea5b5871a170 --- /dev/null +++ b/microservices-api-gateway/price-microservice/src/main/resources/application.properties @@ -0,0 +1,24 @@ +# +# The MIT License +# Copyright © 2014-2021 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. +# + +server.port=50006 \ No newline at end of file diff --git a/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java b/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java similarity index 76% rename from api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java rename to microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java index 679fb601b772..eeaa0c28d377 100644 --- a/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java +++ b/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,17 @@ */ package com.iluwatar.price.microservice; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test for Price Rest Controller - */ -public class PriceControllerTest { - @Test - public void testgetPrice() { - PriceController priceController = new PriceController(); +import org.junit.jupiter.api.Test; - String price = priceController.getPrice(); +/** Test for Price Rest Controller */ +class PriceControllerTest { + @Test + void getPriceTest() { + var priceController = new PriceController(new PriceServiceImpl()); + var price = priceController.getPrice(); assertEquals("20", price); } } diff --git a/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceServiceTest.java b/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceServiceTest.java new file mode 100644 index 000000000000..830ac7d18423 --- /dev/null +++ b/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceServiceTest.java @@ -0,0 +1,40 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.price.microservice; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +/** Test for Price Service */ +class PriceServiceTest { + + @Test + void getPriceTest() { + var priceService = new PriceServiceImpl(); + var price = priceService.getPrice(); + assertEquals("20", price); + } +} diff --git a/microservices-client-side-ui-composition/README.md b/microservices-client-side-ui-composition/README.md new file mode 100644 index 000000000000..d2b1ae7fd158 --- /dev/null +++ b/microservices-client-side-ui-composition/README.md @@ -0,0 +1,146 @@ +--- +title: "Microservices Client-Side UI Composition Pattern In Java: Assembling Modular UIs in Microservices Architecture" +shortTitle: Microservices Client-Side UI Composition +description: "Learn how the Client-Side UI Composition pattern allows the assembly of modular UIs on the client side, enabling independent teams to develop, deploy, and scale UI components in a microservices architecture. Discover the benefits, implementation examples, and best practices." +category: Architectural +language: en +tag: + - Client-server + - Cloud distributed + - Composition + - Decoupling + - Integration + - Microservices + - Modularity + - Scalability + - Web development +--- + +## Intent of Client-Side UI Composition Design Pattern + +Compose user interface from independently deployable microservices on the client side for greater flexibility and decoupling. + +## Also Known As + +* UI Aggregator +* Frontend-Driven Composition + +## Detailed Explanation of Client-Side UI Composition Pattern with Real-World Examples + +Real-world Example + +> In a SaaS dashboard, a client-side composition pattern enables various independent modules like “Billing,” “Reports,” and “Account Settings” to be developed and deployed by separate teams. These modules are composed into a unified interface for the user, with each module independently fetching data from its respective microservice. + +In Plain Words + +> The Client-Side UI Composition pattern breaks down the user interface into smaller, independent parts that can be developed, maintained, and scaled separately by different teams. + +Wikipedia says + +> UI composition refers to the practice of building a user interface from modular components, each responsible for fetching its own data and rendering its own content. This approach enables faster development cycles, easier maintenance, and better scalability in large systems. + +Sequence diagram + +![Client-Side UI Composition sequence diagram](./etc/microservices-client-side-ui-composition-sequence-diagram.png) + +## Programmatic Example of Client-Side UI Composition in Java + +This example composes an e-commerce frontend by integrating three independent modules. Each module is served by a microservice and fetched on the client side through an API Gateway. + +### `ApiGateway` Implementation + +```java +public class ApiGateway { + + private final Map routes = new HashMap<>(); + + public void registerRoute(String path, FrontendComponent component) { + routes.put(path, component); + } + + public String handleRequest(String path, Map params) { + if (routes.containsKey(path)) { + return routes.get(path).fetchData(params); + } else { + return "404 Not Found"; + } + } +} + +``` + +### `FrontendComponent` Interface + +```java +public interface FrontendComponent { + String fetchData(Map params); +} +``` + +### Example Components + +```java +public class ProductComponent implements FrontendComponent { + @Override + public String fetchData(Map params) { + return "Displaying Products: " + params.getOrDefault("category", "all"); + } +} + +public class CartComponent implements FrontendComponent { + @Override + public String fetchData(Map params) { + return "Displaying Cart for User: " + params.getOrDefault("userId", "unknown"); + } +} +``` + +This approach dynamically assembles UI components based on the route in the client-side request. Each component fetches its data asynchronously and renders it within the main interface. + +## When to Use the Client-Side UI Composition Pattern + +* When each microservice must present its own UI components +* When frequent independent deployments of UI features are required +* When teams own end-to-end functionality, including front-end modules +* When Java-based backends provide separate APIs for direct UI consumption + +## Client-Side UI Composition Pattern Tutorials + +- [Micro Frontends in Action (O'Reilly)](https://www.oreilly.com/library/view/micro-frontends-in/9781617296873/) +- [Micro Frontends with React (ThoughtWorks)](https://www.thoughtworks.com/insights/articles/building-micro-frontends-using-react) +- [API Gateway in Microservices (Spring Cloud)](https://spring.io/guides/gs/gateway/) + +## Real-World Applications of Client-Side UI Composition Pattern in Java + +* Large-scale e-commerce portals with microservices powering modular pages +* SaaS platforms requiring rapid iteration of front-end features +* Java-based microservice architectures using frameworks like Spring Boot for modular UI components + +## Benefits and Trade-offs of Client-Side UI Composition Pattern + +Benefits: + +* Facilitates independent deployment cycles for UI features +* Reduces overall coupling and fosters autonomy among teams +* Enables polyglot front-end development + +Trade-offs: + +* Increases client complexity for rendering and data aggregation +* Can cause performance challenges with multiple service calls +* Demands consistent UX guidelines across diverse microservices + +## Related Design Patterns + +* Backend for Frontend (BFF): Provides custom endpoints for specific UIs +* Micro Frontends: Splits the front-end into smaller, individually deployable fragments +* [Microservices API Gateway Pattern](https://java-design-patterns.com/patterns/microservices-api-gateway/): API Gateway serves as a routing mechanism for client-side UI requests. + +## References and Credits + +* [Building Microservices](https://amzn.to/3UACtrU) +* [Building Microservices with Micro Frontends (Martin Fowler)](https://martinfowler.com/articles/micro-frontends.html) +* [Client-Side UI Composition (Microservices.io)](https://microservices.io/patterns/client-side-ui-composition.html) +* [Cloud Native Java: Designing Resilient Systems with Spring Boot, Spring Cloud, and Cloud Foundry](https://amzn.to/44vDTat) +* [Micro Frontends Architecture (Microfrontends.org)](https://micro-frontends.org/) +* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O) diff --git a/microservices-client-side-ui-composition/etc/client-side-ui-composition.urm.puml b/microservices-client-side-ui-composition/etc/client-side-ui-composition.urm.puml new file mode 100644 index 000000000000..ef88e9c22ac7 --- /dev/null +++ b/microservices-client-side-ui-composition/etc/client-side-ui-composition.urm.puml @@ -0,0 +1,31 @@ +@startuml client_side_ui_composition_updated +skinparam classAttributeIconSize 0 + +class ApiGateway { + +registerRoute(path: String, component: FrontendComponent) + +handleRequest(path: String, params: Map): String +} + +class FrontendComponent { + +fetchData(params: Map): String + #getData(params: Map): String +} + +class ProductFrontend { + +getData(params: Map): String +} + +class CartFrontend { + +getData(params: Map): String +} + +class ClientSideIntegrator { + +composeUI(path: String, params: Map) +} + +ApiGateway --> FrontendComponent +FrontendComponent <|-- ProductFrontend +FrontendComponent <|-- CartFrontend +ClientSideIntegrator --> ApiGateway + +@enduml diff --git a/microservices-client-side-ui-composition/etc/microservices-client-side-ui-composition-sequence-diagram.png b/microservices-client-side-ui-composition/etc/microservices-client-side-ui-composition-sequence-diagram.png new file mode 100644 index 000000000000..cb0dd57ae2f5 Binary files /dev/null and b/microservices-client-side-ui-composition/etc/microservices-client-side-ui-composition-sequence-diagram.png differ diff --git a/microservices-client-side-ui-composition/etc/microservices-client-side-ui-composition.urm.puml b/microservices-client-side-ui-composition/etc/microservices-client-side-ui-composition.urm.puml new file mode 100644 index 000000000000..0820d3e45a17 --- /dev/null +++ b/microservices-client-side-ui-composition/etc/microservices-client-side-ui-composition.urm.puml @@ -0,0 +1,33 @@ +@startuml +package com.iluwatar.clientsideuicomposition { + class ApiGateway { + - routes : Map + + ApiGateway() + + handleRequest(path : String, params : Map) : String + + registerRoute(path : String, component : FrontendComponent) + } + class CartFrontend { + + CartFrontend() + # getData(params : Map) : String + } + class ClientSideIntegrator { + - LOGGER : Logger {static} + - apiGateway : ApiGateway + + ClientSideIntegrator(apiGateway : ApiGateway) + + composeUi(path : String, params : Map) + } + abstract class FrontendComponent { + + random : Random {static} + + FrontendComponent() + + fetchData(params : Map) : String + # getData(Map) : String {abstract} + } + class ProductFrontend { + + ProductFrontend() + # getData(params : Map) : String + } +} +ClientSideIntegrator --> "-apiGateway" ApiGateway +CartFrontend --|> FrontendComponent +ProductFrontend --|> FrontendComponent +@enduml \ No newline at end of file diff --git a/microservices-client-side-ui-composition/pom.xml b/microservices-client-side-ui-composition/pom.xml new file mode 100644 index 000000000000..2d5644a14633 --- /dev/null +++ b/microservices-client-side-ui-composition/pom.xml @@ -0,0 +1,58 @@ + + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + microservices-client-side-ui-composition + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + \ No newline at end of file diff --git a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ApiGateway.java b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ApiGateway.java new file mode 100644 index 000000000000..6fc1cc643a4f --- /dev/null +++ b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ApiGateway.java @@ -0,0 +1,73 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.clientsideuicomposition; + +import java.util.HashMap; +import java.util.Map; + +/** + * ApiGateway class acts as a dynamic routing mechanism that forwards client requests to the + * appropriate frontend components based on dynamically registered routes. + * + *

    This allows for flexible, runtime-defined routing without hardcoding specific paths. + */ +public class ApiGateway { + + // A map to store routes dynamically, where the key is the path and the value + // is the associated FrontendComponent + private final Map routes = new HashMap<>(); + + /** + * Registers a route dynamically at runtime. + * + * @param path the path to access the component (e.g., "/products") + * @param component the frontend component to be accessed at the given path + */ + public void registerRoute(String path, FrontendComponent component) { + routes.put(path, component); + } + + /** + * Handles a client request by routing it to the appropriate frontend component. + * + *

    This method dynamically handles parameters passed with the request, which allows the + * frontend components to respond based on those parameters. + * + * @param path the path for which the request is made (e.g., "/products", "/cart") + * @param params a map of parameters that might influence the data fetching logic (e.g., filters, + * userId, categories, etc.) + * @return the data fetched from the appropriate component or "404 Not Found" if the path is not + * registered + */ + public String handleRequest(String path, Map params) { + if (routes.containsKey(path)) { + // Fetch data dynamically based on the provided parameters + return routes.get(path).fetchData(params); + } else { + // Return a 404 error if the path is not registered + return "404 Not Found"; + } + } +} diff --git a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/CartFrontend.java b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/CartFrontend.java new file mode 100644 index 000000000000..d2916408babd --- /dev/null +++ b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/CartFrontend.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.clientsideuicomposition; + +import java.util.Map; + +/** + * CartFrontend is a concrete implementation of FrontendComponent that simulates fetching shopping + * cart data based on the user. + */ +public class CartFrontend extends FrontendComponent { + + /** + * Fetches the current state of the shopping cart based on dynamic parameters like user ID. + * + * @param params parameters that influence the cart data, e.g., "userId" + * @return a string representing the items in the shopping cart for a given user + */ + @Override + protected String getData(Map params) { + String userId = params.getOrDefault("userId", "anonymous"); + return "Shopping Cart for user '" + userId + "': [Item 1, Item 2]"; + } +} diff --git a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ClientSideIntegrator.java b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ClientSideIntegrator.java new file mode 100644 index 000000000000..ca99747a7ddf --- /dev/null +++ b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ClientSideIntegrator.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.clientsideuicomposition; + +import java.util.Map; +import lombok.extern.slf4j.Slf4j; + +/** + * ClientSideIntegrator class simulates the client-side integration layer that dynamically assembles + * various frontend components into a cohesive user interface. + */ +@Slf4j +public class ClientSideIntegrator { + + private final ApiGateway apiGateway; + + /** + * Constructor that accepts an instance of ApiGateway to handle dynamic routing. + * + * @param apiGateway the gateway that routes requests to different frontend components + */ + public ClientSideIntegrator(ApiGateway apiGateway) { + this.apiGateway = apiGateway; + } + + /** + * Composes the user interface dynamically by fetching data from different frontend components + * based on provided parameters. + * + * @param path the route of the frontend component + * @param params a map of dynamic parameters to influence the data fetching + */ + public void composeUi(String path, Map params) { + // Fetch data dynamically based on the route and parameters + String data = apiGateway.handleRequest(path, params); + LOGGER.info("Composed UI Component for path '" + path + "':"); + LOGGER.info(data); + } +} diff --git a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/FrontendComponent.java b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/FrontendComponent.java new file mode 100644 index 000000000000..70399c31854f --- /dev/null +++ b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/FrontendComponent.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.clientsideuicomposition; + +import java.util.Map; +import java.util.Random; + +/** + * FrontendComponent is an abstract class representing an independent frontend component that + * fetches data dynamically based on the provided parameters. + */ +public abstract class FrontendComponent { + + public static final Random random = new Random(); + + /** + * Simulates asynchronous data fetching by introducing a random delay and then fetching the data + * based on dynamic input. + * + * @param params a map of parameters that may affect the data fetching logic + * @return the data fetched by the frontend component + */ + public String fetchData(Map params) { + try { + // Simulate delay in fetching data (e.g., network latency) + Thread.sleep(random.nextInt(1000)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + // Fetch and return the data based on the given parameters + return getData(params); + } + + /** + * Abstract method to be implemented by subclasses to return data based on parameters. + * + * @param params a map of parameters that may affect the data fetching logic + * @return the data for this specific component + */ + protected abstract String getData(Map params); +} diff --git a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ProductFrontend.java b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ProductFrontend.java new file mode 100644 index 000000000000..157f2aef3fd6 --- /dev/null +++ b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ProductFrontend.java @@ -0,0 +1,46 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.clientsideuicomposition; + +import java.util.Map; + +/** + * ProductFrontend is a concrete implementation of FrontendComponent that simulates fetching dynamic + * product data. + */ +public class ProductFrontend extends FrontendComponent { + + /** + * Fetches a list of products based on dynamic parameters such as category. + * + * @param params parameters that influence the data fetched, e.g., "category" + * @return a string representing a filtered list of products + */ + @Override + protected String getData(Map params) { + String category = params.getOrDefault("category", "all"); + return "Product List for category '" + category + "': [Product 1, Product 2, Product 3]"; + } +} diff --git a/microservices-client-side-ui-composition/src/test/java/com/iluwatar/clientsideuicomposition/ClientSideCompositionTest.java b/microservices-client-side-ui-composition/src/test/java/com/iluwatar/clientsideuicomposition/ClientSideCompositionTest.java new file mode 100644 index 000000000000..be5aef2f7aaf --- /dev/null +++ b/microservices-client-side-ui-composition/src/test/java/com/iluwatar/clientsideuicomposition/ClientSideCompositionTest.java @@ -0,0 +1,68 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.clientsideuicomposition; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** + * ClientSideCompositionTest contains unit tests to validate dynamic route registration and UI + * composition. + */ +class ClientSideCompositionTest { + + /** Tests dynamic registration of frontend components and dynamic composition of UI. */ + @Test + void testClientSideUIComposition() { + // Create API Gateway and dynamically register frontend components + ApiGateway apiGateway = new ApiGateway(); + apiGateway.registerRoute("/products", new ProductFrontend()); + apiGateway.registerRoute("/cart", new CartFrontend()); + + // Create the Client-Side Integrator + ClientSideIntegrator integrator = new ClientSideIntegrator(apiGateway); + + // Dynamically pass parameters for data fetching + Map productParams = new HashMap<>(); + productParams.put("category", "electronics"); + + // Compose UI for products and cart with dynamic params + integrator.composeUi("/products", productParams); + + Map cartParams = new HashMap<>(); + cartParams.put("userId", "user123"); + integrator.composeUi("/cart", cartParams); + + // Validate the dynamically fetched data + String productData = apiGateway.handleRequest("/products", productParams); + String cartData = apiGateway.handleRequest("/cart", cartParams); + + assertTrue(productData.contains("Product List for category 'electronics'")); + assertTrue(cartData.contains("Shopping Cart for user 'user123'")); + } +} diff --git a/microservices-distributed-tracing/README.md b/microservices-distributed-tracing/README.md new file mode 100644 index 000000000000..4fc271a68824 --- /dev/null +++ b/microservices-distributed-tracing/README.md @@ -0,0 +1,208 @@ +--- +title: "Microservices Distributed Tracing Pattern In Java: Enhancing Visibility in Service Communication" +shortTitle: Microservices Distributed Tracing +description: "Learn how the Distributed Tracing pattern enhances visibility into service communication across microservices. Discover its benefits, implementation examples, and best practices." +category: Architectural +language: en +tag: + - Cloud distributed + - Microservices + - Resilience + - Observability + - Scalability + - System health +--- + +## Intent of Microservices Distributed Tracing Design Pattern + +Provide a mechanism to trace and correlate requests as they traverse multiple microservices in a distributed system, enabling end-to-end visibility and easier troubleshooting. + +## Also known as + +* Distributed Request Tracing +* End-to-End Microservice Tracing + +## Detailed Explanation of Microservices Distributed Tracing Pattern with Real-World Examples + +Real-world example + +> Imagine an online food delivery platform where one microservice handles user orders, another manages restaurant menus, and yet another coordinates courier assignments. When a user places an order, the request travels through all three services in sequence. By implementing distributed tracing, each service attaches a trace identifier to its logs. This allows the operations team to follow the journey of a single order across the entire pipeline, identify any delays along the way, and quickly pinpoint which service is causing the bottleneck or experiencing an error. + +In plain words + +> Distributed tracing allows you to follow a request's journey through all the services it interacts with, providing insights into system performance and aiding in debugging. + +Wikipedia says + +> Tracing in software engineering refers to the process of capturing and recording information about the execution of a software program. This information is typically used by programmers for debugging purposes, and additionally, depending on the type and detail of information contained in a trace log, by experienced system administrators or technical-support personnel and by software monitoring tools to diagnose common problems with software. + +Sequence diagram + +![Microservices Distributed Tracing Sequence Diagram](./etc/microservices-distributed-tracing-sequence-diagram.png) + +## Programmatic Example of Microservices Distributed Tracing in Java + +This implementation shows how an e-commerce platform's `OrderService` interacts with both `PaymentService` and `ProductService`. When a customer places an order, the `OrderService` calls the `PaymentService` to process the payment and the `ProductService` to check the product inventory. By adding distributed trace instrumentation (usually via libraries like Spring Cloud Sleuth or OpenTelemetry), each service attaches trace context to outgoing requests and logs. These logs can then be viewed in the Zipkin interface (or other tracing tools, such as Jaeger) to observe the entire flow of the request and quickly identify any performance bottlenecks or failures across multiple services. + +Here's the `Order microservice` implementation. + +```java +@Slf4j +@RestController +public class OrderController { + + private final OrderService orderService; + + public OrderController(final OrderService orderService) { + this.orderService = orderService; + } + + @PostMapping("/order") + public ResponseEntity processOrder(@RequestBody(required = false) String request) { + LOGGER.info("Received order request: {}", request); + var result = orderService.processOrder(); + LOGGER.info("Order processed result: {}", result); + return ResponseEntity.ok(result); + } +} +``` +```java +@Slf4j +@Service +public class OrderService { + + private final RestTemplateBuilder restTemplateBuilder; + + public OrderService(final RestTemplateBuilder restTemplateBuilder) { + this.restTemplateBuilder = restTemplateBuilder; + } + + public String processOrder() { + if (validateProduct() && processPayment()) { + return "Order processed successfully"; + } + return "Order processing failed"; + } + + Boolean validateProduct() { + try { + ResponseEntity productValidationResult = restTemplateBuilder + .build() + .postForEntity("http://localhost:30302/product/validate", "validating product", + Boolean.class); + LOGGER.info("Product validation result: {}", productValidationResult.getBody()); + return productValidationResult.getBody(); + } catch (ResourceAccessException | HttpClientErrorException e) { + LOGGER.error("Error communicating with product service: {}", e.getMessage()); + return false; + } + } + + Boolean processPayment() { + try { + ResponseEntity paymentProcessResult = restTemplateBuilder + .build() + .postForEntity("http://localhost:30301/payment/process", "processing payment", + Boolean.class); + LOGGER.info("Payment processing result: {}", paymentProcessResult.getBody()); + return paymentProcessResult.getBody(); + } catch (ResourceAccessException | HttpClientErrorException e) { + LOGGER.error("Error communicating with payment service: {}", e.getMessage()); + return false; + } + } +} +``` + +Here's the `Payment microservice` implementation. + +```java + +@Slf4j +@RestController +public class PaymentController { + + @PostMapping("/payment/process") + public ResponseEntity payment(@RequestBody(required = false) String request) { + LOGGER.info("Received payment request: {}", request); + boolean result = true; + LOGGER.info("Payment result: {}", result); + return ResponseEntity.ok(result); + } +} +``` + +Here's the `Product microservice` implementation. + +```java +/** + * Controller for handling product validation requests. + */ +@Slf4j +@RestController +public class ProductController { + + /** + * Validates the product based on the request. + * + * @param request the request body containing product information (can be null) + * @return ResponseEntity containing the validation result (true) + */ + @PostMapping("/product/validate") + public ResponseEntity validateProduct(@RequestBody(required = false) String request) { + LOGGER.info("Received product validation request: {}", request); + boolean result = true; + LOGGER.info("Product validation result: {}", result); + return ResponseEntity.ok(result); + } +} +``` + +In this example, each microservice would typically be configured with tracing libraries (like Sleuth or OpenTelemetry). The trace context is propagated via HTTP headers, enabling the logs and metrics for each service call to be grouped together and visualized in Zipkin or another compatible tool. This ensures complete end-to-end visibility into each request’s journey. + +## When to Use the Microservices Distributed Tracing Pattern in Java + +* When multiple services form a single user request path and debugging failures requires visibility across service boundaries. +* When monitoring or diagnosing performance bottlenecks is critical in a multi-service environment. +* When correlation of logs and metrics from independent services is needed to understand overall system health. + +## Microservices Distributed Tracing Pattern Java Tutorials + +* [Spring Boot - Tracing (Spring)](https://docs.spring.io/spring-boot/reference/actuator/tracing.html) +* [Reactive Observability (Spring Academy)](https://spring.academy/guides/microservices-observability-reactive-spring-boot-3) +* [Spring Cloud – Tracing Services with Zipkin (Baeldung)](https://dzone.com/articles/getting-started-with-spring-cloud-gateway) + +## Real-World Applications of Microservices Distributed Tracing Pattern in Java + +* OpenTelemetry for tracing instrumentation in Java services. +* Spring Cloud Sleuth for automatic tracing in Spring Boot microservices. +* Jaeger and Zipkin for collecting and visualizing distributed traces in Java-based systems. + +## Benefits and Trade-offs of Microservices Distributed Tracing Pattern + +Benefits: + +* Centralized insight into request paths across services, reducing time to diagnose issues. +* Improved observability enables proactive identification of system bottlenecks. +* Aids in debugging and troubleshooting complex systems. + +Trade-offs: + +* Adds overhead to each request due to tracing data. +* Requires additional infrastructure (e.g., Zipkin, Jaeger) for collecting and visualizing traces. +* Can become complex to manage in large-scale systems. + +## Related Java Design Patterns + +* [API Gateway Microservice](https://java-design-patterns.com/patterns/microservices-api-gateway/): Acts as an entry point to microservices and can propagate trace information to downstream services. +* [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Distributed tracing can be used alongside the Circuit Breaker pattern to monitor and handle failures gracefully, preventing cascading failures in microservices. +* [Log Aggregation Microservice](https://java-design-patterns.com/patterns/microservices-log-aggregation/): Distributed tracing works well in conjunction with log aggregation to provide comprehensive observability and troubleshooting capabilities. +* [Saga](https://java-design-patterns.com/patterns/saga/): Orchestrates distributed transactions, which benefit from trace identifiers to correlate steps across services. + +## References and Credits + +* [Building Microservices](https://amzn.to/3UACtrU) +* [Distributed tracing (microservices.io)](https://microservices.io/patterns/observability/distributed-tracing.html) +* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O) +* [OpenTelemetry Documentation](https://opentelemetry.io/docs/) +* [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3Uul4kF) diff --git a/microservices-distributed-tracing/etc/microservices-distributed-tracing-sequence-diagram.png b/microservices-distributed-tracing/etc/microservices-distributed-tracing-sequence-diagram.png new file mode 100644 index 000000000000..7840697100da Binary files /dev/null and b/microservices-distributed-tracing/etc/microservices-distributed-tracing-sequence-diagram.png differ diff --git a/microservices-distributed-tracing/etc/microservices-distributed-tracing.png b/microservices-distributed-tracing/etc/microservices-distributed-tracing.png new file mode 100644 index 000000000000..00f06108b60a Binary files /dev/null and b/microservices-distributed-tracing/etc/microservices-distributed-tracing.png differ diff --git a/microservices-distributed-tracing/etc/microservices-distributed-tracing.puml b/microservices-distributed-tracing/etc/microservices-distributed-tracing.puml new file mode 100644 index 000000000000..9c303f0dc1fa --- /dev/null +++ b/microservices-distributed-tracing/etc/microservices-distributed-tracing.puml @@ -0,0 +1,31 @@ +@startuml +!theme vibrant +package com.iluwatar.microservices-distributed-tracing { +package "Order Microservice" { + class OrderController { + +processOrder() + } + + class OrderService { + +validateProduct() + +processPayment() + } +} + +package "Payment Microservice" { + class PaymentController { + +processPayment() + } +} + +package "Product Microservice" { + class ProductController { + +validateProduct() + } +} + +OrderController --> OrderService +OrderService --> PaymentController : processPayment() +OrderService --> ProductController : validateProduct() +} +@enduml \ No newline at end of file diff --git a/microservices-distributed-tracing/etc/microservices-distributed-tracing.urm.puml b/microservices-distributed-tracing/etc/microservices-distributed-tracing.urm.puml new file mode 100644 index 000000000000..9c303f0dc1fa --- /dev/null +++ b/microservices-distributed-tracing/etc/microservices-distributed-tracing.urm.puml @@ -0,0 +1,31 @@ +@startuml +!theme vibrant +package com.iluwatar.microservices-distributed-tracing { +package "Order Microservice" { + class OrderController { + +processOrder() + } + + class OrderService { + +validateProduct() + +processPayment() + } +} + +package "Payment Microservice" { + class PaymentController { + +processPayment() + } +} + +package "Product Microservice" { + class ProductController { + +validateProduct() + } +} + +OrderController --> OrderService +OrderService --> PaymentController : processPayment() +OrderService --> ProductController : validateProduct() +} +@enduml \ No newline at end of file diff --git a/microservices-distributed-tracing/order-microservice/etc/order-microservice.png b/microservices-distributed-tracing/order-microservice/etc/order-microservice.png new file mode 100644 index 000000000000..d2951e1ad8db Binary files /dev/null and b/microservices-distributed-tracing/order-microservice/etc/order-microservice.png differ diff --git a/microservices-distributed-tracing/order-microservice/etc/order-microservice.puml b/microservices-distributed-tracing/order-microservice/etc/order-microservice.puml new file mode 100644 index 000000000000..013138441aca --- /dev/null +++ b/microservices-distributed-tracing/order-microservice/etc/order-microservice.puml @@ -0,0 +1,15 @@ +@startuml +!theme vibrant +package com.iluwatar.microservices-distributed-tracing { +package "Order Microservice" { + class OrderController { + +processOrder() + } + + class OrderService { + +validateProduct() + +processPayment() + } +} +} +@enduml \ No newline at end of file diff --git a/microservices-distributed-tracing/order-microservice/etc/order-microservice.urm.puml b/microservices-distributed-tracing/order-microservice/etc/order-microservice.urm.puml new file mode 100644 index 000000000000..013138441aca --- /dev/null +++ b/microservices-distributed-tracing/order-microservice/etc/order-microservice.urm.puml @@ -0,0 +1,15 @@ +@startuml +!theme vibrant +package com.iluwatar.microservices-distributed-tracing { +package "Order Microservice" { + class OrderController { + +processOrder() + } + + class OrderService { + +validateProduct() + +processPayment() + } +} +} +@enduml \ No newline at end of file diff --git a/microservices-distributed-tracing/order-microservice/pom.xml b/microservices-distributed-tracing/order-microservice/pom.xml new file mode 100644 index 000000000000..f55c175b921a --- /dev/null +++ b/microservices-distributed-tracing/order-microservice/pom.xml @@ -0,0 +1,63 @@ + + + + + microservices-distributed-tracing + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + order-microservice + jar + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.order.microservice.com.iluwatar.product.microservice.Main + + + + + + + + + + + central + Maven Central Repository + https://repo.maven.apache.org/maven2 + + + diff --git a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java new file mode 100644 index 000000000000..b6b6da79faae --- /dev/null +++ b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java @@ -0,0 +1,78 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.order.microservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * With the Microservices pattern, a request often travels through multiple different microservices. + * Tracking the entire request flow across these services can be challenging, especially when trying + * to diagnose performance issues or failures. Distributed tracing addresses this challenge by + * providing end-to-end visibility into the lifecycle of a request as it passes through various + * microservices. + * + *

    The intent of the Distributed Tracing pattern is to trace a request across different + * microservices, collecting detailed timing data and logs that help in understanding the flow, + * performance bottlenecks, and failure points in a distributed system. Each microservice involved + * in the request contributes to the tracing data, creating a comprehensive view of the request's + * journey. + * + *

    This implementation demonstrates distributed tracing in a microservices architecture for an + * e-commerce platform. When a customer places an order, the {@link OrderService} interacts with + * both the payment-microservice to process the payment and the product-microservice to check the + * product inventory. Tracing logs are generated for each interaction, and these logs can be + * visualized using Zipkin. + * + *

    To run Zipkin and view the tracing logs, you can use the following Docker command: + * + *

    + * {@code docker run -d -p 9411:9411 --name zipkin openzipkin/zipkin }
    + * 
    + * + *

    Start Zipkin with the command above. Once Zipkin is running, you can access the Zipkin UI at + * `...` to view the tracing logs and analyze the request flows + * across your microservices. + * + *

    To place an order and generate tracing data, you can use the following curl command: + * + *

    + * {@code curl -X POST http://localhost:30300/order -H "Content-Type: application/json" -d '{"orderId": "123"}' }
    + * 
    + * + *

    This command sends a POST request to create an order, which will trigger interactions with the + * payment and product microservices, generating tracing logs that can be viewed in Zipkin. + */ +@SpringBootApplication +public class Main { + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + SpringApplication.run(Main.class, args); + } +} diff --git a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderController.java b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderController.java new file mode 100644 index 000000000000..a7c67868c49a --- /dev/null +++ b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderController.java @@ -0,0 +1,62 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.order.microservice; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +/** This controller handles order processing by calling necessary microservices. */ +@Slf4j +@RestController +public class OrderController { + + private final OrderService orderService; + + /** + * Constructor to inject OrderService. + * + * @param orderService the service to process orders + */ + public OrderController(final OrderService orderService) { + this.orderService = orderService; + } + + /** + * Endpoint to process an order. + * + * @param request the order request body (can be null) + * @return ResponseEntity with a status message + */ + @PostMapping("/order") + public ResponseEntity processOrder(@RequestBody(required = false) String request) { + LOGGER.info("Received order request: {}", request); + var result = orderService.processOrder(); + LOGGER.info("Order processed result: {}", result); + return ResponseEntity.ok(result); + } +} diff --git a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderService.java b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderService.java new file mode 100644 index 000000000000..b4be09309d26 --- /dev/null +++ b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderService.java @@ -0,0 +1,102 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.order.microservice; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.ResourceAccessException; + +/** Service to handle order processing logic. */ +@Slf4j +@Service +public class OrderService { + + private final RestTemplateBuilder restTemplateBuilder; + + /** + * Constructor to inject RestTemplateBuilder. + * + * @param restTemplateBuilder the RestTemplateBuilder to build RestTemplate instances + */ + public OrderService(final RestTemplateBuilder restTemplateBuilder) { + this.restTemplateBuilder = restTemplateBuilder; + } + + /** + * Processes an order by calling {@link OrderService#validateProduct()} and {@link + * OrderService#processPayment()}. + * + * @return A string indicating whether the order was processed successfully or failed. + */ + public String processOrder() { + if (validateProduct() && processPayment()) { + return "Order processed successfully"; + } + return "Order processing failed"; + } + + /** + * Validates the product by calling the respective microservice. + * + * @return true if the product is valid, false otherwise. + */ + Boolean validateProduct() { + try { + ResponseEntity productValidationResult = + restTemplateBuilder + .build() + .postForEntity( + "http://localhost:30302/product/validate", "validating product", Boolean.class); + LOGGER.info("Product validation result: {}", productValidationResult.getBody()); + return productValidationResult.getBody(); + } catch (ResourceAccessException | HttpClientErrorException e) { + LOGGER.error("Error communicating with product service: {}", e.getMessage()); + return false; + } + } + + /** + * Validates the product by calling the respective microservice. + * + * @return true if the product is valid, false otherwise. + */ + Boolean processPayment() { + try { + ResponseEntity paymentProcessResult = + restTemplateBuilder + .build() + .postForEntity( + "http://localhost:30301/payment/process", "processing payment", Boolean.class); + LOGGER.info("Payment processing result: {}", paymentProcessResult.getBody()); + return paymentProcessResult.getBody(); + } catch (ResourceAccessException | HttpClientErrorException e) { + LOGGER.error("Error communicating with payment service: {}", e.getMessage()); + return false; + } + } +} diff --git a/microservices-distributed-tracing/order-microservice/src/main/resources/application.properties b/microservices-distributed-tracing/order-microservice/src/main/resources/application.properties new file mode 100644 index 000000000000..fd183251dfd6 --- /dev/null +++ b/microservices-distributed-tracing/order-microservice/src/main/resources/application.properties @@ -0,0 +1,33 @@ +# +# The MIT License +# Copyright © 2014-2021 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. +# + +spring.application.name=order-microservice +server.port=30300 + +management.tracing.sampling.probability=1 +logging.pattern.level=%5p [${spring.zipkin.service.name:${spring.application.name:}},%X{traceId:-},%X{spanId:-}] +management.tracing.propagation.type=w3c +management.tracing.baggage.enabled=true +management.tracing.enabled=true +management.zipkin.tracing.endpoint=http://localhost:9411/api/v2/spans + diff --git a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java new file mode 100644 index 000000000000..97f9295ff0c1 --- /dev/null +++ b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.order.microservice; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application test */ +class MainTest { + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> Main.main(new String[] {})); + } +} diff --git a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderControllerTest.java b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderControllerTest.java new file mode 100644 index 000000000000..05ecc03df0d7 --- /dev/null +++ b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderControllerTest.java @@ -0,0 +1,93 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.order.microservice; /* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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 org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.http.ResponseEntity; + +/** OrderControllerTest class to test the OrderController. */ +class OrderControllerTest { + + @InjectMocks private OrderController orderController; + + @Mock private OrderService orderService; + + @BeforeEach + void setup() { + MockitoAnnotations.openMocks(this); + } + + /** Test to process the order successfully. */ + @Test + void processOrderShouldReturnSuccessStatus() { + // Arrange + when(orderService.processOrder()).thenReturn("Order processed successfully"); + // Act + ResponseEntity response = orderController.processOrder("test order"); + // Assert + assertEquals("Order processed successfully", response.getBody()); + } + + /** Test to process the order with failure. */ + @Test + void ProcessOrderShouldReturnFailureStatusWhen() { + // Arrange + when(orderService.processOrder()).thenReturn("Order processing failed"); + // Act + ResponseEntity response = orderController.processOrder("test order"); + // Assert + assertEquals("Order processing failed", response.getBody()); + } +} diff --git a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderServiceTest.java b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderServiceTest.java new file mode 100644 index 000000000000..10a3fcacb670 --- /dev/null +++ b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderServiceTest.java @@ -0,0 +1,184 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.order.microservice; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; + +/** OrderServiceTest class to test the OrderService. */ +class OrderServiceTest { + + @InjectMocks private OrderService orderService; + + @Mock private RestTemplateBuilder restTemplateBuilder; + + @Mock private RestTemplate restTemplate; + + @BeforeEach + void setup() { + MockitoAnnotations.openMocks(this); + when(restTemplateBuilder.build()).thenReturn(restTemplate); + } + + /** Test to process the order successfully. */ + @Test + void testProcessOrder_Success() { + // Arrange + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + .thenReturn(ResponseEntity.ok(true)); + when(restTemplate.postForEntity( + eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) + .thenReturn(ResponseEntity.ok(true)); + // Act + String result = orderService.processOrder(); + // Assert + assertEquals("Order processed successfully", result); + } + + /** Test to process the order with failure caused by product validation failure. */ + @Test + void testProcessOrder_FailureWithProductValidationFailure() { + // Arrange + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + .thenReturn(ResponseEntity.ok(false)); + // Act + String result = orderService.processOrder(); + // Assert + assertEquals("Order processing failed", result); + } + + /** Test to process the order with failure caused by payment processing failure. */ + @Test + void testProcessOrder_FailureWithPaymentProcessingFailure() { + // Arrange + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + .thenReturn(ResponseEntity.ok(true)); + when(restTemplate.postForEntity( + eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) + .thenReturn(ResponseEntity.ok(false)); + // Act + String result = orderService.processOrder(); + // Assert + assertEquals("Order processing failed", result); + } + + /** Test to validate the product. */ + @Test + void testValidateProduct() { + // Arrange + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + .thenReturn(ResponseEntity.ok(true)); + // Act + Boolean result = orderService.validateProduct(); + // Assert + assertEquals(true, result); + } + + /** Test to process the payment. */ + @Test + void testProcessPayment() { + // Arrange + when(restTemplate.postForEntity( + eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) + .thenReturn(ResponseEntity.ok(true)); + // Act + Boolean result = orderService.processPayment(); + // Assert + assertEquals(true, result); + } + + /** Test to validate the product with ResourceAccessException. */ + @Test + void testValidateProduct_ResourceAccessException() { + // Arrange + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + .thenThrow(new ResourceAccessException("Service unavailable")); + // Act + Boolean result = orderService.validateProduct(); + // Assert + assertEquals(false, result); + } + + /** Test to validate the product with HttpClientErrorException. */ + @Test + void testValidateProduct_HttpClientErrorException() { + // Arrange + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + .thenThrow( + new HttpClientErrorException( + org.springframework.http.HttpStatus.BAD_REQUEST, "Bad request")); + // Act + Boolean result = orderService.validateProduct(); + // Assert + assertEquals(false, result); + } + + /** Test to process the payment with ResourceAccessException. */ + @Test + void testProcessPayment_ResourceAccessException() { + // Arrange + when(restTemplate.postForEntity( + eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) + .thenThrow(new ResourceAccessException("Service unavailable")); + // Act + Boolean result = orderService.processPayment(); + // Assert + assertEquals(false, result); + } + + /** Test to process the payment with HttpClientErrorException. */ + @Test + void testProcessPayment_HttpClientErrorException() { + // Arrange + when(restTemplate.postForEntity( + eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) + .thenThrow( + new HttpClientErrorException( + org.springframework.http.HttpStatus.BAD_REQUEST, "Bad request")); + // Act + Boolean result = orderService.processPayment(); + // Assert + assertEquals(false, result); + } +} diff --git a/microservices-distributed-tracing/payment-microservice/etc/payment-microservice.png b/microservices-distributed-tracing/payment-microservice/etc/payment-microservice.png new file mode 100644 index 000000000000..991fcf462e46 Binary files /dev/null and b/microservices-distributed-tracing/payment-microservice/etc/payment-microservice.png differ diff --git a/microservices-distributed-tracing/payment-microservice/etc/payment-microservice.puml b/microservices-distributed-tracing/payment-microservice/etc/payment-microservice.puml new file mode 100644 index 000000000000..06030c7e7eb9 --- /dev/null +++ b/microservices-distributed-tracing/payment-microservice/etc/payment-microservice.puml @@ -0,0 +1,11 @@ +@startuml +!theme vibrant +package com.iluwatar.microservices-distributed-tracing { + +package "Payment Microservice" { + class PaymentController { + +processPayment() + } +} +} +@enduml \ No newline at end of file diff --git a/microservices-distributed-tracing/payment-microservice/etc/payment-microservice.urm.puml b/microservices-distributed-tracing/payment-microservice/etc/payment-microservice.urm.puml new file mode 100644 index 000000000000..06030c7e7eb9 --- /dev/null +++ b/microservices-distributed-tracing/payment-microservice/etc/payment-microservice.urm.puml @@ -0,0 +1,11 @@ +@startuml +!theme vibrant +package com.iluwatar.microservices-distributed-tracing { + +package "Payment Microservice" { + class PaymentController { + +processPayment() + } +} +} +@enduml \ No newline at end of file diff --git a/microservices-distributed-tracing/payment-microservice/pom.xml b/microservices-distributed-tracing/payment-microservice/pom.xml new file mode 100644 index 000000000000..5dd45b1086ef --- /dev/null +++ b/microservices-distributed-tracing/payment-microservice/pom.xml @@ -0,0 +1,56 @@ + + + + + microservices-distributed-tracing + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + payment-microservice + jar + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.payment.microservice.com.iluwatar.product.microservice.Main + + + + + + + + + diff --git a/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java b/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java new file mode 100644 index 000000000000..506096f4e909 --- /dev/null +++ b/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java @@ -0,0 +1,77 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.payment.microservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * With the Microservices pattern, a request often travels through multiple different microservices. + * Tracking the entire request flow across these services can be challenging, especially when trying + * to diagnose performance issues or failures. Distributed tracing addresses this challenge by + * providing end-to-end visibility into the lifecycle of a request as it passes through various + * microservices. + * + *

    The intent of the Distributed Tracing pattern is to trace a request across different + * microservices, collecting detailed timing data and logs that help in understanding the flow, + * performance bottlenecks, and failure points in a distributed system. Each microservice involved + * in the request contributes to the tracing data, creating a comprehensive view of the request's + * journey. + * + *

    This implementation demonstrates distributed tracing in a microservices architecture for an + * e-commerce platform. When a customer places an order, the OrderService interacts with both the + * PaymentService to process the payment and the ProductService to check the product inventory. + * Tracing logs are generated for each interaction, and these logs can be visualized using Zipkin. + * + *

    To run Zipkin and view the tracing logs, you can use the following Docker command: + * + *

    + * {@code docker run -d -p 9411:9411 --name zipkin openzipkin/zipkin }
    + * 
    + * + *

    Start Zipkin with the command above. Once Zipkin is running, you can access the Zipkin UI at + * http://localhost:9411 to view the tracing logs and analyze + * the request flows across your microservices. + * + *

    To place an order and generate tracing data, you can use the following curl command: + * + *

    + * {@code curl -X POST http://localhost:30300/order -H "Content-Type: application/json" -d '{"orderId": "123"}' }
    + * 
    + * + *

    This command sends a POST request to create an order, which will trigger interactions with the + * payment and product microservices, generating tracing logs that can be viewed in Zipkin. + */ +@SpringBootApplication +public class Main { + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + SpringApplication.run(Main.class, args); + } +} diff --git a/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/PaymentController.java b/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/PaymentController.java new file mode 100644 index 000000000000..834c88c07942 --- /dev/null +++ b/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/PaymentController.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.payment.microservice; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +/** Controller for handling payment processing requests. */ +@Slf4j +@RestController +public class PaymentController { + + /** + * Processes the payment based on the request. + * + * @param request the request body containing payment information (can be null) + * @return ResponseEntity containing the payment processing result (true) + */ + @PostMapping("/payment/process") + public ResponseEntity payment(@RequestBody(required = false) String request) { + LOGGER.info("Received payment request: {}", request); + boolean result = true; + LOGGER.info("Payment result: {}", result); + return ResponseEntity.ok(result); + } +} diff --git a/microservices-distributed-tracing/payment-microservice/src/main/resources/application.properties b/microservices-distributed-tracing/payment-microservice/src/main/resources/application.properties new file mode 100644 index 000000000000..5f24f5b603a4 --- /dev/null +++ b/microservices-distributed-tracing/payment-microservice/src/main/resources/application.properties @@ -0,0 +1,32 @@ +# +# The MIT License +# Copyright © 2014-2021 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. +# + +spring.application.name=payment-microservice +server.port=30301 + +management.tracing.sampling.probability=1 +logging.pattern.level=%5p [${spring.zipkin.service.name:${spring.application.name:}},%X{traceId:-},%X{spanId:-}] +management.tracing.propagation.type=w3c +management.tracing.baggage.enabled=true +management.tracing.enabled=true +management.zipkin.tracing.endpoint=http://localhost:9411/api/v2/spans diff --git a/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java b/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java new file mode 100644 index 000000000000..2b500440ebc0 --- /dev/null +++ b/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.payment.microservice; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application Context loads test */ +class MainTest { + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> Main.main(new String[] {})); + } +} diff --git a/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/ProductControllerTest.java b/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/ProductControllerTest.java new file mode 100644 index 000000000000..7fbbf2c1a7b8 --- /dev/null +++ b/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/ProductControllerTest.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.payment.microservice; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.ResponseEntity; + +/** Payment controller test. */ +class ProductControllerTest { + + private PaymentController paymentController; + + @BeforeEach + void setUp() { + paymentController = new PaymentController(); + } + + /** Test to process the payment. */ + @Test + void testValidateProduct() { + // Arrange + String request = "Sample payment process request"; + // Act + ResponseEntity response = paymentController.payment(request); + // Assert + assertEquals(ResponseEntity.ok(true), response); + } + + /** Test to process the payment with null request. */ + @Test + void testValidateProductWithNullRequest() { + // Arrange + // Act + ResponseEntity response = paymentController.payment(null); + // Assert + assertEquals(ResponseEntity.ok(true), response); + } +} diff --git a/microservices-distributed-tracing/pom.xml b/microservices-distributed-tracing/pom.xml new file mode 100644 index 000000000000..c7dddf0fa0b6 --- /dev/null +++ b/microservices-distributed-tracing/pom.xml @@ -0,0 +1,73 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + microservices-distributed-tracing + pom + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + io.micrometer + micrometer-tracing-bridge-brave + 1.4.5 + compile + + + io.zipkin.reporter2 + zipkin-reporter-brave + 3.5.0 + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + order-microservice + payment-microservice + product-microservice + + diff --git a/microservices-distributed-tracing/product-microservice/etc/product-microservice.png b/microservices-distributed-tracing/product-microservice/etc/product-microservice.png new file mode 100644 index 000000000000..23410f3cd571 Binary files /dev/null and b/microservices-distributed-tracing/product-microservice/etc/product-microservice.png differ diff --git a/microservices-distributed-tracing/product-microservice/etc/product-microservice.puml b/microservices-distributed-tracing/product-microservice/etc/product-microservice.puml new file mode 100644 index 000000000000..25a1805ff4b4 --- /dev/null +++ b/microservices-distributed-tracing/product-microservice/etc/product-microservice.puml @@ -0,0 +1,10 @@ +@startuml +!theme vibrant +package com.iluwatar.microservices-distributed-tracing { +package "Product Microservice" { + class ProductController { + +validateProduct() + } +} +} +@enduml \ No newline at end of file diff --git a/microservices-distributed-tracing/product-microservice/etc/product-microservice.urm.puml b/microservices-distributed-tracing/product-microservice/etc/product-microservice.urm.puml new file mode 100644 index 000000000000..25a1805ff4b4 --- /dev/null +++ b/microservices-distributed-tracing/product-microservice/etc/product-microservice.urm.puml @@ -0,0 +1,10 @@ +@startuml +!theme vibrant +package com.iluwatar.microservices-distributed-tracing { +package "Product Microservice" { + class ProductController { + +validateProduct() + } +} +} +@enduml \ No newline at end of file diff --git a/microservices-distributed-tracing/product-microservice/pom.xml b/microservices-distributed-tracing/product-microservice/pom.xml new file mode 100644 index 000000000000..987e0fca8a74 --- /dev/null +++ b/microservices-distributed-tracing/product-microservice/pom.xml @@ -0,0 +1,56 @@ + + + + + microservices-distributed-tracing + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + product-microservice + jar + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.product.com.iluwatar.product.microservice.microservice.Main + + + + + + + + + diff --git a/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java b/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java new file mode 100644 index 000000000000..91e41631c190 --- /dev/null +++ b/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java @@ -0,0 +1,77 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.product.microservice.microservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * With the Microservices pattern, a request often travels through multiple different microservices. + * Tracking the entire request flow across these services can be challenging, especially when trying + * to diagnose performance issues or failures. Distributed tracing addresses this challenge by + * providing end-to-end visibility into the lifecycle of a request as it passes through various + * microservices. + * + *

    The intent of the Distributed Tracing pattern is to trace a request across different + * microservices, collecting detailed timing data and logs that help in understanding the flow, + * performance bottlenecks, and failure points in a distributed system. Each microservice involved + * in the request contributes to the tracing data, creating a comprehensive view of the request's + * journey. + * + *

    This implementation demonstrates distributed tracing in a microservices architecture for an + * e-commerce platform. When a customer places an order, the OrderService interacts with both the + * PaymentService to process the payment and the ProductService to check the product inventory. + * Tracing logs are generated for each interaction, and these logs can be visualized using Zipkin. + * + *

    To run Zipkin and view the tracing logs, you can use the following Docker command: + * + *

    + * {@code docker run -d -p 9411:9411 --name zipkin openzipkin/zipkin }
    + * 
    + * + *

    Start Zipkin with the command above. Once Zipkin is running, you can access the Zipkin UI at + * http://localhost:9411 to view the tracing logs and analyze + * the request flows across your microservices. + * + *

    To place an order and generate tracing data, you can use the following curl command: + * + *

    + * {@code curl -X POST http://localhost:30300/order -H "Content-Type: application/json" -d '{"orderId": "123"}' }
    + * 
    + * + *

    This command sends a POST request to create an order, which will trigger interactions with the + * payment and product microservices, generating tracing logs that can be viewed in Zipkin. + */ +@SpringBootApplication +public class Main { + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + SpringApplication.run(Main.class, args); + } +} diff --git a/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/ProductController.java b/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/ProductController.java new file mode 100644 index 000000000000..cc4b21475cc1 --- /dev/null +++ b/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/ProductController.java @@ -0,0 +1,51 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.product.microservice.microservice; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +/** Controller for handling product validation requests. */ +@Slf4j +@RestController +public class ProductController { + + /** + * Validates the product based on the request. + * + * @param request the request body containing product information (can be null) + * @return ResponseEntity containing the validation result (true) + */ + @PostMapping("/product/validate") + public ResponseEntity validateProduct(@RequestBody(required = false) String request) { + LOGGER.info("Received product validation request: {}", request); + boolean result = true; + LOGGER.info("Product validation result: {}", result); + return ResponseEntity.ok(result); + } +} diff --git a/microservices-distributed-tracing/product-microservice/src/main/resources/application.properties b/microservices-distributed-tracing/product-microservice/src/main/resources/application.properties new file mode 100644 index 000000000000..72c7b3ed2772 --- /dev/null +++ b/microservices-distributed-tracing/product-microservice/src/main/resources/application.properties @@ -0,0 +1,33 @@ +# +# The MIT License +# Copyright © 2014-2021 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. +# + +spring.application.name=product-microservice +server.port=30302 + +management.tracing.sampling.probability=1 +logging.pattern.level=%5p [${spring.zipkin.service.name:${spring.application.name:}},%X{traceId:-},%X{spanId:-}] +management.tracing.propagation.type=w3c +management.tracing.baggage.enabled=true +management.tracing.enabled=true +management.zipkin.tracing.endpoint=http://localhost:9411/api/v2/spans + diff --git a/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java b/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java new file mode 100644 index 000000000000..1534943abd02 --- /dev/null +++ b/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.product.microservice; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import com.iluwatar.product.microservice.microservice.Main; +import org.junit.jupiter.api.Test; + +/** Application test */ +class MainTest { + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> Main.main(new String[] {})); + } +} diff --git a/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/ProductControllerTest.java b/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/ProductControllerTest.java new file mode 100644 index 000000000000..b1053be8f137 --- /dev/null +++ b/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/ProductControllerTest.java @@ -0,0 +1,63 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.product.microservice; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.iluwatar.product.microservice.microservice.ProductController; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.ResponseEntity; + +class ProductControllerTest { + + private ProductController productController; + + @BeforeEach + void setUp() { + productController = new ProductController(); + } + + /** Test to validate the product. */ + @Test + void testValidateProduct() { + // Arrange + String request = "Sample product validation request"; + // Act + ResponseEntity response = productController.validateProduct(request); + // Assert + assertEquals(ResponseEntity.ok(true), response); + } + + /** Test to validate the product with null request. */ + @Test + void testValidateProductWithNullRequest() { + // Arrange + // Act + ResponseEntity response = productController.validateProduct(null); + // Assert + assertEquals(ResponseEntity.ok(true), response); + } +} diff --git a/microservices-idempotent-consumer/README.md b/microservices-idempotent-consumer/README.md new file mode 100644 index 000000000000..738bbcda5a3d --- /dev/null +++ b/microservices-idempotent-consumer/README.md @@ -0,0 +1,182 @@ +--- +title: "Microservices Idempotent Consumer Pattern in Java: Ensuring Reliable Message Processing" +shortTitle: Microservices Idempotent Consumer +description: "Learn about the Idempotent Consumer pattern in Java. Discover how it ensures reliable and consistent message processing, even in cases of duplicate messages." +category: Messaging +language: en +tag: + - Asynchronous + - Decoupling + - Event-driven + - Messaging + - Microservices + - Resilience + - Retry +--- + +## Also known as + +* Idempotent Subscriber +* Repeatable Message Consumer +* Safe Consumer + +## Intent of Idempotent Consumer Pattern + +Ensure that consuming the same message multiple times does not cause unintended side effects in a microservices-based architecture. + +## Detailed Explanation of Idempotent Consumer Pattern with Real-World Examples + +Real-world example + +> In a payment processing system, ensuring that payment messages are idempotent prevents duplicate transactions. For example, if a user’s payment message is accidentally processed twice, the system should recognize the second message as a duplicate and prevent it from executing a second time. By storing unique identifiers for each processed message, such as a transaction ID, the system can skip any duplicate messages. This ensures that a user is not charged twice for the same transaction, maintaining system integrity and customer satisfaction. + +In plain words + +> The Idempotent Consumer pattern prevents duplicate messages from causing unintended side effects by ensuring that processing the same message multiple times results in the same outcome. This makes message processing safe in distributed systems where duplicates may occur. + + +Wikipedia says + +> In computing, idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application. + +Flowchart + +![Microservices Idempotent Consumer flowchart](./etc/microservices-idempotent-consumer-flowchart.png) + +## Programmatic example of Idempotent Consumer Pattern + +In this Java example, we have an idempotent service that creates and updates orders. The `create` method is idempotent, meaning multiple calls with the same order ID return the same result without duplicates. For state changes (like starting or completing an order), the service checks whether the transition is valid and throws an exception if it’s not allowed. The `RequestStateMachine` ensures that order statuses move forward in a valid sequence (e.g., PENDING → STARTED → COMPLETED). + +### RequestService - Managing Idempotent Order Operations + +The `RequestService` class provides methods to create and transition an order. The `create` method returns an existing order if it already exists, making it idempotent. + +```java +public class RequestService { + // Idempotent: ensures that the same request is returned if it already exists + public Request create(UUID uuid) { + Optional optReq = requestRepository.findById(uuid); + if (!optReq.isEmpty()) { + return optReq.get(); // Return existing request + } + return requestRepository.save(new Request(uuid)); // Save and return new request + } + + public Request start(UUID uuid) { + Optional optReq = requestRepository.findById(uuid); + if (optReq.isEmpty()) { + throw new RequestNotFoundException(uuid); + } + return requestRepository.save(requestStateMachine.next(optReq.get(), Request.Status.STARTED)); + } + + public Request complete(UUID uuid) { + Optional optReq = requestRepository.findById(uuid); + if (optReq.isEmpty()) { + throw new RequestNotFoundException(uuid); + } + return requestRepository.save(requestStateMachine.next(optReq.get(), Request.Status.COMPLETED)); + } +} +``` + +### RequestStateMachine - Managing Order Transitions + +The `RequestStateMachine` enforces valid state changes. If a requested transition is not allowed based on the current status, an exception is thrown. + +```java +public class RequestStateMachine { + + public Request next(Request req, Request.Status nextStatus) { + String transitionStr = String.format("Transition: %s -> %s", req.getStatus(), nextStatus); + switch (nextStatus) { + case PENDING -> throw new InvalidNextStateException(transitionStr); + case STARTED -> { + if (Request.Status.PENDING.equals(req.getStatus())) { + return new Request(req.getUuid(), Request.Status.STARTED); // Valid transition + } + throw new InvalidNextStateException(transitionStr); // Invalid transition + } + case COMPLETED -> { + if (Request.Status.STARTED.equals(req.getStatus())) { + return new Request(req.getUuid(), Request.Status.COMPLETED); // Valid transition + } + throw new InvalidNextStateException(transitionStr); // Invalid transition + } + default -> throw new InvalidNextStateException(transitionStr); // Invalid status + } + } +} +``` + +### Main Application - Running the Idempotent Consumer Example + +Here, we demonstrate how `RequestService` can be called multiple times without creating duplicate orders. We also show how invalid transitions (like trying to start an order twice) result in exceptions, while valid transitions proceed normally. + +```java +Request req = requestService.create(UUID.randomUUID()); +// Try creating the same Request again with the same UUID (idempotent operation) +requestService.create(req.getUuid()); +// Again, try creating the same Request (idempotent operation, no new Request should be created) +requestService.create(req.getUuid()); +LOGGER.info("Nb of requests : {}", requestRepository.count()); // 1, processRequest is idempotent +// Attempt to start the Request (the first valid transition) +req = requestService.start(req.getUuid()); +// Try to start the Request again, which should throw an exception since it's already started +try { + req = requestService.start(req.getUuid()); +} catch (InvalidNextStateException ex) { + // Log an error message when trying to start a request twice + LOGGER.error("Cannot start request twice!"); +} +// Complete the Request (valid transition from STARTED to COMPLETED) +req = requestService.complete(req.getUuid()); +// Log the final status of the Request to confirm it's been completed +LOGGER.info("Request: {}", req); +``` + +Program output: + +``` +19:01:54.382 INFO [main] com.iluwatar.idempotentconsumer.App : Nb of requests : 1 +19:01:54.395 ERROR [main] com.iluwatar.idempotentconsumer.App : Cannot start request twice! +19:01:54.399 INFO [main] com.iluwatar.idempotentconsumer.App : Request: Request(uuid=2d5521ef-6b6b-4003-9ade-81e381fe9a63, status=COMPLETED) +``` + +## When to Use the Idempotent Consumer Pattern + +* When messages can arrive more than once due to network glitches or retries +* When microservices must guarantee consistent state changes regardless of duplicates +* When fault-tolerant event-driven communication is critical to system reliability +* When horizontal scaling requires stateless consumer operations + +## Real-World Applications of Idempotent Consumer Pattern + +* Payment processing systems that receive duplicate charge events +* E-commerce order services that handle duplicate purchase requests +* Notification services that retry failed message deliveries +* Distributed transaction systems where duplicated events are common + +## Benefits and Trade-offs of the Idempotent Consumer Pattern + +Benefits + +* Prevents duplicate side effects +* Increases reliability under repeated or delayed messages +* Simplifies error handling and retry logic + +Trade-offs + +* Requires careful design to track processed messages +* Can add overhead for maintaining idempotency tokens or state +* May require additional storage or database transactions + +## Related Patterns in Java + +* Outbox Pattern: Uses a dedicated table or storage to reliably publish events and handle deduplication at the source. + +## References and Credits + +* [Building Microservices](https://amzn.to/3UACtrU) +* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/4dznP2Y) +* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O) diff --git a/microservices-idempotent-consumer/etc/microservices-idempotent-consumer-flowchart.png b/microservices-idempotent-consumer/etc/microservices-idempotent-consumer-flowchart.png new file mode 100644 index 000000000000..e5bd5d83ac8b Binary files /dev/null and b/microservices-idempotent-consumer/etc/microservices-idempotent-consumer-flowchart.png differ diff --git a/microservices-idempotent-consumer/etc/microservices-idempotent-consumer.urm.puml b/microservices-idempotent-consumer/etc/microservices-idempotent-consumer.urm.puml new file mode 100644 index 000000000000..43fe77181375 --- /dev/null +++ b/microservices-idempotent-consumer/etc/microservices-idempotent-consumer.urm.puml @@ -0,0 +1,49 @@ +@startuml +package com.iluwatar.idempotentconsumer { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + + run(requestService : RequestService, requestRepository : RequestRepository) : CommandLineRunner + } + class Request { + - status : Status + - uuid : UUID + + Request() + + Request(uuid : UUID) + + Request(uuid : UUID, status : Status) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getStatus() : Status + + getUuid() : UUID + + hashCode() : int + + setStatus(status : Status) + + setUuid(uuid : UUID) + + toString() : String + } + ~enum Status { + + COMPLETED {static} + + PENDING {static} + + STARTED {static} + + valueOf(name : String) : Status {static} + + values() : Status[] {static} + } + interface RequestRepository { + } + class RequestService { + ~ requestRepository : RequestRepository + ~ requestStateMachine : RequestStateMachine + + RequestService(requestRepository : RequestRepository, requestStateMachine : RequestStateMachine) + + complete(uuid : UUID) : Request + + create(uuid : UUID) : Request + + start(uuid : UUID) : Request + } + class RequestStateMachine { + + RequestStateMachine() + + next(req : Request, nextStatus : Status) : Request + } +} +RequestService --> "-requestRepository" RequestRepository +Request --> "-status" Status +RequestService --> "-requestStateMachine" RequestStateMachine +@enduml \ No newline at end of file diff --git a/microservices-idempotent-consumer/pom.xml b/microservices-idempotent-consumer/pom.xml new file mode 100644 index 000000000000..665be3abef56 --- /dev/null +++ b/microservices-idempotent-consumer/pom.xml @@ -0,0 +1,116 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + microservices-idempotent-consumer + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + org.mockito + mockito-core + test + + + + + com.h2database + h2 + runtime + + + + org.hibernate + hibernate-core + 6.4.4.Final + + + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + + jar-with-dependencies + + + + + com.iluwatar.idempotentconsumer.App + + + + + + + + + + + + diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java new file mode 100644 index 000000000000..fe099eab415f --- /dev/null +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java @@ -0,0 +1,75 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.idempotentconsumer; + +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +/** + * The main entry point for the idempotent-consumer application. This application demonstrates the + * use of the Idempotent Consumer pattern which ensures that a message is processed exactly once in + * scenarios where the same message can be delivered multiple times. + * + * @see Idempotence (Wikipedia) + * @see Idempotent + * Consumer Pattern (Apache Camel) + */ +@SpringBootApplication +@Slf4j +public class App { + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } + + /** + * The starting point of the CommandLineRunner where the main program is run. + * + * @param requestService idempotent request service + * @param requestRepository request jpa repository + */ + @Bean + public CommandLineRunner run(RequestService requestService, RequestRepository requestRepository) { + return args -> { + Request req = requestService.create(UUID.randomUUID()); + requestService.create(req.getUuid()); + requestService.create(req.getUuid()); + LOGGER.info( + "Nb of requests : {}", requestRepository.count()); // 1, processRequest is idempotent + req = requestService.start(req.getUuid()); + try { + req = requestService.start(req.getUuid()); + } catch (InvalidNextStateException ex) { + LOGGER.error("Cannot start request twice!"); + } + req = requestService.complete(req.getUuid()); + LOGGER.info("Request: {}", req); + }; + } +} diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/InvalidNextStateException.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/InvalidNextStateException.java new file mode 100644 index 000000000000..e280d37a8a1f --- /dev/null +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/InvalidNextStateException.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.idempotentconsumer; + +/** + * This exception is thrown when an invalid transition is attempted in the Statemachine for the + * request status. This can occur when attempting to move to a state that is not valid from the + * current state. + */ +public class InvalidNextStateException extends RuntimeException { + public InvalidNextStateException(String s) { + super(s); + } +} diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/Request.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/Request.java new file mode 100644 index 000000000000..dfd68346bb7f --- /dev/null +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/Request.java @@ -0,0 +1,58 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.idempotentconsumer; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import java.util.UUID; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * The {@code Request} class represents a request with a unique UUID and a status. The status of a + * request can be one of four values: PENDING, STARTED, COMPLETED, or INERROR. + */ +@Entity +@NoArgsConstructor +@Data +public class Request { + enum Status { + PENDING, + STARTED, + COMPLETED + } + + @Id private UUID uuid; + private Status status; + + public Request(UUID uuid) { + this(uuid, Status.PENDING); + } + + public Request(UUID uuid, Status status) { + this.uuid = uuid; + this.status = status; + } +} diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestNotFoundException.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestNotFoundException.java new file mode 100644 index 000000000000..aedc94ef7517 --- /dev/null +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestNotFoundException.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.idempotentconsumer; + +import java.util.UUID; + +/** + * This class extends the RuntimeException class to handle scenarios where a Request is not found. + * It is intended to be used where you would like to have a custom exception that signals that a + * requested object or action was not found in the system, based on the UUID of the request. + */ +public class RequestNotFoundException extends RuntimeException { + RequestNotFoundException(UUID uuid) { + super(String.format("Request %s not found", uuid)); + } +} diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestRepository.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestRepository.java new file mode 100644 index 000000000000..e0b273e9fb5d --- /dev/null +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestRepository.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.idempotentconsumer; + +import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * This is a repository interface for the "Request" entity. It extends the JpaRepository interface + * from Spring Data JPA. JpaRepository comes with many operations out of the box, including standard + * CRUD operations. With JpaRepository, we are also able to leverage the power of Spring Data's + * query methods. The UUID parameter in JpaRepository refers to the type of the ID in the "Request" + * entity. + */ +@Repository +public interface RequestRepository extends JpaRepository {} diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestService.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestService.java new file mode 100644 index 000000000000..39d496120cc7 --- /dev/null +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestService.java @@ -0,0 +1,87 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.idempotentconsumer; + +import java.util.Optional; +import java.util.UUID; +import org.springframework.stereotype.Service; + +/** + * This service is responsible for handling request operations including creation, start, and + * completion of requests. + */ +@Service +public class RequestService { + RequestRepository requestRepository; + RequestStateMachine requestStateMachine; + + public RequestService( + RequestRepository requestRepository, RequestStateMachine requestStateMachine) { + this.requestRepository = requestRepository; + this.requestStateMachine = requestStateMachine; + } + + /** + * Creates a new Request or returns an existing one by its UUID. This operation is idempotent: + * performing it once or several times successively leads to an equivalent result. + * + * @param uuid The unique identifier for the Request. + * @return Return existing Request or save and return a new Request. + */ + public Request create(UUID uuid) { + Optional optReq = requestRepository.findById(uuid); + return optReq.orElseGet(() -> requestRepository.save(new Request(uuid))); + } + + /** + * Starts the Request assigned with the given UUID. + * + * @param uuid The unique identifier for the Request. + * @return The started Request. + * @throws RequestNotFoundException if a Request with the given UUID is not found. + */ + public Request start(UUID uuid) { + Optional optReq = requestRepository.findById(uuid); + if (optReq.isEmpty()) { + throw new RequestNotFoundException(uuid); + } + return requestRepository.save(requestStateMachine.next(optReq.get(), Request.Status.STARTED)); + } + + /** + * Complete the Request assigned with the given UUID. + * + * @param uuid The unique identifier for the Request. + * @return The completed Request. + * @throws RequestNotFoundException if a Request with the given UUID is not found. + */ + public Request complete(UUID uuid) { + Optional optReq = requestRepository.findById(uuid); + if (optReq.isEmpty()) { + throw new RequestNotFoundException(uuid); + } + return requestRepository.save(requestStateMachine.next(optReq.get(), Request.Status.COMPLETED)); + } +} diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestStateMachine.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestStateMachine.java new file mode 100644 index 000000000000..a67affdf1253 --- /dev/null +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestStateMachine.java @@ -0,0 +1,65 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.idempotentconsumer; + +import org.springframework.stereotype.Component; + +/** + * This class represents a state machine for managing request transitions. It supports transitions + * to the statuses: PENDING, STARTED, and COMPLETED. + */ +@Component +public class RequestStateMachine { + + /** + * Provides the next possible state of the request based on the current and next status. + * + * @param req The actual request object. This object MUST NOT be null and SHOULD have a valid + * status. + * @param nextStatus Represents the next status that the request could transition to. MUST NOT be + * null. + * @return A new Request object with updated status if the transition is valid. + * @throws InvalidNextStateException If an invalid state transition is attempted. + */ + public Request next(Request req, Request.Status nextStatus) { + String transitionStr = String.format("Transition: %s -> %s", req.getStatus(), nextStatus); + switch (nextStatus) { + case PENDING -> throw new InvalidNextStateException(transitionStr); + case STARTED -> { + if (Request.Status.PENDING.equals(req.getStatus())) { + return new Request(req.getUuid(), Request.Status.STARTED); + } + throw new InvalidNextStateException(transitionStr); + } + case COMPLETED -> { + if (Request.Status.STARTED.equals(req.getStatus())) { + return new Request(req.getUuid(), Request.Status.COMPLETED); + } + throw new InvalidNextStateException(transitionStr); + } + default -> throw new InvalidNextStateException(transitionStr); + } + } +} diff --git a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java new file mode 100644 index 000000000000..f6cd88e0f505 --- /dev/null +++ b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java @@ -0,0 +1,67 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.idempotentconsumer; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.boot.CommandLineRunner; + +/** Application test */ +class AppTest { + + @Test + void testMain() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } + + @Test + void testRun() throws Exception { + RequestService requestService = Mockito.mock(RequestService.class); + RequestRepository requestRepository = Mockito.mock(RequestRepository.class); + UUID uuid = UUID.randomUUID(); + Request requestPending = new Request(uuid); + Request requestStarted = new Request(uuid, Request.Status.STARTED); + Request requestCompleted = new Request(uuid, Request.Status.COMPLETED); + when(requestService.create(any())).thenReturn(requestPending); + when(requestService.start(any())).thenReturn(requestStarted); + when(requestService.complete(any())).thenReturn(requestCompleted); + + CommandLineRunner runner = new App().run(requestService, requestRepository); + + runner.run(); + + verify(requestService, times(3)).create(any()); + verify(requestService, times(2)).start(any()); + verify(requestService, times(1)).complete(any()); + verify(requestRepository, times(1)).count(); + } +} diff --git a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestServiceTests.java b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestServiceTests.java new file mode 100644 index 000000000000..20470d5151c7 --- /dev/null +++ b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestServiceTests.java @@ -0,0 +1,136 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.idempotentconsumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class RequestServiceTests { + private RequestService requestService; + @Mock private RequestRepository requestRepository; + + @BeforeEach + void setUp() { + RequestStateMachine requestStateMachine = new RequestStateMachine(); + requestService = new RequestService(requestRepository, requestStateMachine); + } + + @Test + void createRequest_whenNotExists() { + UUID uuid = UUID.randomUUID(); + Request request = new Request(uuid); + when(requestRepository.findById(any())).thenReturn(Optional.empty()); + when(requestRepository.save(request)).thenReturn(request); + assertEquals(request, requestService.create(uuid)); + verify(requestRepository, times(1)).findById(uuid); + verify(requestRepository, times(1)).save(any()); + } + + @Test + void createRequest_whenExists() { + UUID uuid = UUID.randomUUID(); + Request request = new Request(uuid); + when(requestRepository.findById(any())).thenReturn(Optional.of(request)); + assertEquals(request, requestService.create(uuid)); + verify(requestRepository, times(1)).findById(uuid); + verify(requestRepository, times(0)).save(any()); + } + + @Test + void startRequest_whenNotExists_shouldThrowError() { + UUID uuid = UUID.randomUUID(); + when(requestRepository.findById(any())).thenReturn(Optional.empty()); + assertThrows(RequestNotFoundException.class, () -> requestService.start(uuid)); + verify(requestRepository, times(1)).findById(uuid); + verify(requestRepository, times(0)).save(any()); + } + + @Test + void startRequest_whenIsPending() { + UUID uuid = UUID.randomUUID(); + Request request = new Request(uuid); + Request startedEntity = new Request(uuid, Request.Status.STARTED); + when(requestRepository.findById(any())).thenReturn(Optional.of(request)); + when(requestRepository.save(any())).thenReturn(startedEntity); + assertEquals(startedEntity, requestService.start(uuid)); + verify(requestRepository, times(1)).findById(uuid); + verify(requestRepository, times(1)).save(startedEntity); + } + + @Test + void startRequest_whenIsStarted_shouldThrowError() { + UUID uuid = UUID.randomUUID(); + Request requestStarted = new Request(uuid, Request.Status.STARTED); + when(requestRepository.findById(any())).thenReturn(Optional.of(requestStarted)); + assertThrows(InvalidNextStateException.class, () -> requestService.start(uuid)); + verify(requestRepository, times(1)).findById(uuid); + verify(requestRepository, times(0)).save(any()); + } + + @Test + void startRequest_whenIsCompleted_shouldThrowError() { + UUID uuid = UUID.randomUUID(); + Request requestStarted = new Request(uuid, Request.Status.COMPLETED); + when(requestRepository.findById(any())).thenReturn(Optional.of(requestStarted)); + assertThrows(InvalidNextStateException.class, () -> requestService.start(uuid)); + verify(requestRepository, times(1)).findById(uuid); + verify(requestRepository, times(0)).save(any()); + } + + @Test + void completeRequest_whenStarted() { + UUID uuid = UUID.randomUUID(); + Request request = new Request(uuid, Request.Status.STARTED); + Request completedEntity = new Request(uuid, Request.Status.COMPLETED); + when(requestRepository.findById(any())).thenReturn(Optional.of(request)); + when(requestRepository.save(any())).thenReturn(completedEntity); + assertEquals(completedEntity, requestService.complete(uuid)); + verify(requestRepository, times(1)).findById(uuid); + verify(requestRepository, times(1)).save(completedEntity); + } + + @Test + void completeRequest_whenNotInprogress() { + UUID uuid = UUID.randomUUID(); + Request request = new Request(uuid); + when(requestRepository.findById(any())).thenReturn(Optional.of(request)); + assertThrows(InvalidNextStateException.class, () -> requestService.complete(uuid)); + verify(requestRepository, times(1)).findById(uuid); + verify(requestRepository, times(0)).save(any()); + } +} diff --git a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestStateMachineTests.java b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestStateMachineTests.java new file mode 100644 index 000000000000..d160814a00ed --- /dev/null +++ b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestStateMachineTests.java @@ -0,0 +1,96 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.idempotentconsumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class RequestStateMachineTests { + private RequestStateMachine requestStateMachine; + + @BeforeEach + void setUp() { + requestStateMachine = new RequestStateMachine(); + } + + @Test + void transitionPendingToStarted() { + Request startedRequest = + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.PENDING), Request.Status.STARTED); + assertEquals(Request.Status.STARTED, startedRequest.getStatus()); + } + + @Test + void transitionAnyToPending_shouldThrowError() { + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.PENDING), Request.Status.PENDING)); + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.STARTED), Request.Status.PENDING)); + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.COMPLETED), Request.Status.PENDING)); + } + + @Test + void transitionCompletedToAny_shouldThrowError() { + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.COMPLETED), Request.Status.PENDING)); + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.COMPLETED), Request.Status.STARTED)); + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.COMPLETED), + Request.Status.COMPLETED)); + } + + @Test + void transitionStartedToCompleted() { + Request completedRequest = + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.STARTED), Request.Status.COMPLETED); + assertEquals(Request.Status.COMPLETED, completedRequest.getStatus()); + } +} diff --git a/microservices-log-aggregation/README.md b/microservices-log-aggregation/README.md new file mode 100644 index 000000000000..2fcef9b70cf2 --- /dev/null +++ b/microservices-log-aggregation/README.md @@ -0,0 +1,167 @@ +--- +title: "Microservices Log Aggregation Pattern in Java: Centralizing Logs for Enhanced Monitoring" +shortTitle: Microservices Log Aggregation +description: "Learn about the Microservices Log Aggregation pattern, a method for centralizing log collection and analysis to enhance monitoring, debugging, and operational intelligence in distributed systems." +category: Integration +language: en +tag: + - Data processing + - Decoupling + - Enterprise patterns + - Fault tolerance + - Messaging + - Microservices + - Performance + - Scalability +--- + +## Also known as + +* Centralized Logging +* Log Management + +## Intent of Microservices Log Aggregation Design Pattern + +Log Aggregation is a crucial microservices design pattern that centralizes the collection, storage, and analysis of logs from multiple sources, facilitating efficient monitoring, debugging, and operational intelligence. + +## Detailed Explanation of Microservices Log Aggregation Pattern with Real-World Examples + +Real-world example + +> Imagine an e-commerce platform using a microservices architecture, where each service generates logs. A log aggregation system, utilizing tools like the ELK Stack (Elasticsearch, Logstash, Kibana), centralizes these logs. This setup allows administrators to effectively monitor and analyze the entire platform's activity in real-time. By collecting logs from each microservice and centralizing them, the system provides a unified view, enabling quick troubleshooting and comprehensive analysis of user behavior and system performance. + +In plain words + +> The Log Aggregation design pattern centralizes the collection and analysis of log data from multiple applications or services to simplify monitoring and troubleshooting. + +Wikipedia says + +> You have applied the Microservice architecture pattern. The application consists of multiple services and service instances that are running on multiple machines. Requests often span multiple service instances. Each service instance generates writes information about what it is doing to a log file in a standardized format. The log file contains errors, warnings, information and debug messages. + +Flowchart + +![Microservices Log Aggregration flowchart](./etc/microservices-log-aggregation-flowchart.png) + +## Programmatic Example of Microservices Log Aggregation Pattern in Java + +Log Aggregation is a pattern that centralizes the collection, storage, and analysis of logs from multiple sources to facilitate monitoring, debugging, and operational intelligence. It is particularly useful in distributed systems where logs from various components need to be centralized for better management and analysis. + +In this example, we will demonstrate the Log Aggregation pattern using a simple Java application. The application consists of multiple services that generate logs. These logs are collected by a log aggregator and stored in a central log store. + +The `CentralLogStore` is responsible for storing the logs collected from various services. In this example, we are using an in-memory store for simplicity. + +```java +public class CentralLogStore { + + private final List logs = new ArrayList<>(); + + public void storeLog(LogEntry logEntry) { + logs.add(logEntry); + } + + public void displayLogs() { + logs.forEach(System.out::println); + } +} +``` + +The `LogAggregator` collects logs from various services and stores them in the `CentralLogStore`. It filters logs based on their log level. + +```java +public class LogAggregator { + + private final CentralLogStore centralLogStore; + private final LogLevel minimumLogLevel; + + public LogAggregator(CentralLogStore centralLogStore, LogLevel minimumLogLevel) { + this.centralLogStore = centralLogStore; + this.minimumLogLevel = minimumLogLevel; + } + + public void collectLog(LogEntry logEntry) { + if (logEntry.getLogLevel().compareTo(minimumLogLevel) >= 0) { + centralLogStore.storeLog(logEntry); + } + } +} +``` + +The `LogProducer` represents a service that generates logs. It sends the logs to the `LogAggregator`. + +```java +public class LogProducer { + + private final String serviceName; + private final LogAggregator logAggregator; + + public LogProducer(String serviceName, LogAggregator logAggregator) { + this.serviceName = serviceName; + this.logAggregator = logAggregator; + } + + public void generateLog(LogLevel logLevel, String message) { + LogEntry logEntry = new LogEntry(serviceName, logLevel, message, LocalDateTime.now()); + logAggregator.collectLog(logEntry); + } +} +``` + +The `main` application creates services, generates logs, aggregates, and finally displays the logs. + +```java +public class App { + + public static void main(String[] args) throws InterruptedException { + final CentralLogStore centralLogStore = new CentralLogStore(); + final LogAggregator aggregator = new LogAggregator(centralLogStore, LogLevel.INFO); + + final LogProducer serviceA = new LogProducer("ServiceA", aggregator); + final LogProducer serviceB = new LogProducer("ServiceB", aggregator); + + serviceA.generateLog(LogLevel.INFO, "This is an INFO log from ServiceA"); + serviceB.generateLog(LogLevel.ERROR, "This is an ERROR log from ServiceB"); + serviceA.generateLog(LogLevel.DEBUG, "This is a DEBUG log from ServiceA"); + + centralLogStore.displayLogs(); + } +} +``` + +In this example, the `LogProducer` services generate logs of different levels. The `LogAggregator` collects these logs and stores them in the `CentralLogStore` if they meet the minimum log level requirement. Finally, the logs are displayed by the `CentralLogStore`. + +## When to Use the Microservices Log Aggregation Pattern in Java + +* Microservices log aggregation is essential in distributed systems for better management and analysis of log data. +* Applicable in environments where compliance and auditing require consolidated log data. +* Beneficial in systems that require high availability and resilience, ensuring that log data is preserved and accessible despite individual component failures. + +## Real-World Applications of Microservices Log Aggregation Pattern in Java + +* ava applications using frameworks like Log4j2 or SLF4J with centralized log management tools such as the ELK stack or Splunk benefit from microservices log aggregation. +* Microservices architectures where each service outputs logs that are aggregated into a single system to provide a unified view of the system’s health and behavior. + +## Benefits and Trade-offs of Microservices Log Aggregation Pattern + +Benefits: + +* Centralizing logs in a microservices environment improves debuggability and traceability across multiple services. +* Enhances monitoring capabilities by providing a centralized platform for log analysis. +* Facilitates compliance with regulatory requirements for log retention and auditability. + +Trade-offs: + +* Introduces a potential single point of failure if the log aggregation system is not adequately resilient. +* Can lead to high data volumes requiring significant storage and processing resources. + +## Related Java Design Patterns + +* Messaging Patterns: Log Aggregation often utilizes messaging systems to transport log data, facilitating decoupling and asynchronous data processing. +* Microservices: Often employed in microservice architectures to handle logs from various services efficiently. +* Publish/Subscribe: Utilizes a pub/sub model for log data collection where components publish logs and the aggregation system subscribes to them. + +## References and Credits + +* [Cloud Native Java: Designing Resilient Systems with Spring Boot, Spring Cloud, and Cloud Foundry](https://amzn.to/44vDTat) +* [Logging in Action: With Fluentd, Kubernetes and more](https://amzn.to/3JQLzdT) +* [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3Uul4kF) +* [Pattern: Log aggregation (microservices.io)](https://microservices.io/patterns/observability/application-logging.html) diff --git a/microservices-log-aggregation/etc/log-aggregation.png b/microservices-log-aggregation/etc/log-aggregation.png new file mode 100644 index 000000000000..4ce56be7064f Binary files /dev/null and b/microservices-log-aggregation/etc/log-aggregation.png differ diff --git a/microservices-log-aggregation/etc/log-aggregation.puml b/microservices-log-aggregation/etc/log-aggregation.puml new file mode 100644 index 000000000000..b35873e17ad7 --- /dev/null +++ b/microservices-log-aggregation/etc/log-aggregation.puml @@ -0,0 +1,51 @@ +@startuml + +package com.iluwatar.logaggregation { + + class App { + + main(args: String[]) {static} + } + + class CentralLogStore { + - logs: ConcurrentLinkedQueue + + storeLog(logEntry: LogEntry) + + displayLogs() + } + + class LogAggregator { + - BUFFER_THRESHOLD: int {static} + - centralLogStore: CentralLogStore + - buffer: ConcurrentLinkedQueue + - minLogLevel: LogLevel + - executorService: ExecutorService + - logCount: AtomicInteger + + collectLog(logEntry: LogEntry) + + stop() + } + + class LogEntry { + - serviceName: String + - level: LogLevel + - message: String + - timestamp: LocalDateTime + } + + enum LogLevel { + DEBUG + INFO + ERROR + } + + class LogProducer { + - serviceName: String + - aggregator: LogAggregator + + generateLog(level: LogLevel, message: String) + } +} + +LogProducer --> "-aggregator" LogAggregator +LogAggregator --> "-centralLogStore" CentralLogStore +LogAggregator --> "-buffer" LogEntry +CentralLogStore --> "-logs" LogEntry + +@enduml diff --git a/microservices-log-aggregation/etc/log-aggregation.urm.puml b/microservices-log-aggregation/etc/log-aggregation.urm.puml new file mode 100644 index 000000000000..1d4551ed025f --- /dev/null +++ b/microservices-log-aggregation/etc/log-aggregation.urm.puml @@ -0,0 +1,68 @@ +@startuml +package com.iluwatar.logaggregation { + class App { + + App() + + main(args : String[]) {static} + } + class CentralLogStore { + - LOGGER : Logger {static} + - logs : ConcurrentLinkedQueue + + CentralLogStore() + + displayLogs() + + storeLog(logEntry : LogEntry) + } + class LogAggregator { + - BUFFER_THRESHOLD : int {static} + - LOGGER : Logger {static} + - buffer : ConcurrentLinkedQueue + - centralLogStore : CentralLogStore + - executorService : ExecutorService + - logCount : AtomicInteger + - minLogLevel : LogLevel + + LogAggregator(centralLogStore : CentralLogStore, minLogLevel : LogLevel) + + collectLog(logEntry : LogEntry) + - flushBuffer() + - startBufferFlusher() + + stop() + } + class LogEntry { + - level : LogLevel + - message : String + - serviceName : String + - timestamp : LocalDateTime + + LogEntry(serviceName : String, level : LogLevel, message : String, timestamp : LocalDateTime) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getLevel() : LogLevel + + getMessage() : String + + getServiceName() : String + + getTimestamp() : LocalDateTime + + hashCode() : int + + setLevel(level : LogLevel) + + setMessage(message : String) + + setServiceName(serviceName : String) + + setTimestamp(timestamp : LocalDateTime) + + toString() : String + } + enum LogLevel { + + DEBUG {static} + + ERROR {static} + + INFO {static} + + valueOf(name : String) : LogLevel {static} + + values() : LogLevel[] {static} + } + class LogProducer { + - LOGGER : Logger {static} + - aggregator : LogAggregator + - serviceName : String + + LogProducer(serviceName : String, aggregator : LogAggregator) + + generateLog(level : LogLevel, message : String) + } +} +LogAggregator --> "-centralLogStore" CentralLogStore +LogEntry --> "-level" LogLevel +CentralLogStore --> "-logs" LogEntry +LogAggregator --> "-buffer" LogEntry +LogAggregator --> "-minLogLevel" LogLevel +LogProducer --> "-aggregator" LogAggregator +@enduml \ No newline at end of file diff --git a/microservices-log-aggregation/etc/microservices-log-aggregation-flowchart.png b/microservices-log-aggregation/etc/microservices-log-aggregation-flowchart.png new file mode 100644 index 000000000000..a73f948dd855 Binary files /dev/null and b/microservices-log-aggregation/etc/microservices-log-aggregation-flowchart.png differ diff --git a/microservices-log-aggregation/etc/microservices-log-aggregation.urm.puml b/microservices-log-aggregation/etc/microservices-log-aggregation.urm.puml new file mode 100644 index 000000000000..1d4551ed025f --- /dev/null +++ b/microservices-log-aggregation/etc/microservices-log-aggregation.urm.puml @@ -0,0 +1,68 @@ +@startuml +package com.iluwatar.logaggregation { + class App { + + App() + + main(args : String[]) {static} + } + class CentralLogStore { + - LOGGER : Logger {static} + - logs : ConcurrentLinkedQueue + + CentralLogStore() + + displayLogs() + + storeLog(logEntry : LogEntry) + } + class LogAggregator { + - BUFFER_THRESHOLD : int {static} + - LOGGER : Logger {static} + - buffer : ConcurrentLinkedQueue + - centralLogStore : CentralLogStore + - executorService : ExecutorService + - logCount : AtomicInteger + - minLogLevel : LogLevel + + LogAggregator(centralLogStore : CentralLogStore, minLogLevel : LogLevel) + + collectLog(logEntry : LogEntry) + - flushBuffer() + - startBufferFlusher() + + stop() + } + class LogEntry { + - level : LogLevel + - message : String + - serviceName : String + - timestamp : LocalDateTime + + LogEntry(serviceName : String, level : LogLevel, message : String, timestamp : LocalDateTime) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getLevel() : LogLevel + + getMessage() : String + + getServiceName() : String + + getTimestamp() : LocalDateTime + + hashCode() : int + + setLevel(level : LogLevel) + + setMessage(message : String) + + setServiceName(serviceName : String) + + setTimestamp(timestamp : LocalDateTime) + + toString() : String + } + enum LogLevel { + + DEBUG {static} + + ERROR {static} + + INFO {static} + + valueOf(name : String) : LogLevel {static} + + values() : LogLevel[] {static} + } + class LogProducer { + - LOGGER : Logger {static} + - aggregator : LogAggregator + - serviceName : String + + LogProducer(serviceName : String, aggregator : LogAggregator) + + generateLog(level : LogLevel, message : String) + } +} +LogAggregator --> "-centralLogStore" CentralLogStore +LogEntry --> "-level" LogLevel +CentralLogStore --> "-logs" LogEntry +LogAggregator --> "-buffer" LogEntry +LogAggregator --> "-minLogLevel" LogLevel +LogProducer --> "-aggregator" LogAggregator +@enduml \ No newline at end of file diff --git a/microservices-log-aggregation/pom.xml b/microservices-log-aggregation/pom.xml new file mode 100644 index 000000000000..fd5548661d3d --- /dev/null +++ b/microservices-log-aggregation/pom.xml @@ -0,0 +1,80 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + + microservices-log-aggregation + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-junit-jupiter + 5.16.1 + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.logaggregation.App + + + + + + + + + diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/App.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/App.java new file mode 100644 index 000000000000..080dc6763136 --- /dev/null +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/App.java @@ -0,0 +1,53 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.logaggregation; + +/** + * The main application class responsible for demonstrating the log aggregation mechanism. Creates + * services, generates logs, aggregates, and finally displays the logs. + */ +public class App { + + /** + * The entry point of the application. + * + * @param args Command line arguments. + * @throws InterruptedException If any thread has interrupted the current thread. + */ + public static void main(String[] args) throws InterruptedException { + final CentralLogStore centralLogStore = new CentralLogStore(); + final LogAggregator aggregator = new LogAggregator(centralLogStore, LogLevel.INFO); + + final LogProducer serviceA = new LogProducer("ServiceA", aggregator); + final LogProducer serviceB = new LogProducer("ServiceB", aggregator); + + serviceA.generateLog(LogLevel.INFO, "This is an INFO log from ServiceA"); + serviceB.generateLog(LogLevel.ERROR, "This is an ERROR log from ServiceB"); + serviceA.generateLog(LogLevel.DEBUG, "This is a DEBUG log from ServiceA"); + + aggregator.stop(); + centralLogStore.displayLogs(); + } +} diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/CentralLogStore.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/CentralLogStore.java new file mode 100644 index 000000000000..3f525fa9e65f --- /dev/null +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/CentralLogStore.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.logaggregation; + +import java.util.concurrent.ConcurrentLinkedQueue; +import lombok.extern.slf4j.Slf4j; + +/** + * A centralized store for logs. It collects logs from various services and stores them. This class + * is thread-safe, ensuring that logs from different services are safely stored concurrently without + * data races. + */ +@Slf4j +public class CentralLogStore { + + private final ConcurrentLinkedQueue logs = new ConcurrentLinkedQueue<>(); + + /** + * Stores the given log entry into the central log store. + * + * @param logEntry The log entry to store. + */ + public void storeLog(LogEntry logEntry) { + if (logEntry == null) { + LOGGER.error("Received null log entry. Skipping."); + return; + } + logs.offer(logEntry); + } + + /** Displays all logs currently stored in the central log store. */ + public void displayLogs() { + LOGGER.info("----- Centralized Logs -----"); + for (LogEntry logEntry : logs) { + LOGGER.info( + logEntry.getTimestamp() + " [" + logEntry.getLevel() + "] " + logEntry.getMessage()); + } + } +} diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogAggregator.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogAggregator.java new file mode 100644 index 000000000000..0acdc9fedc62 --- /dev/null +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogAggregator.java @@ -0,0 +1,119 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.logaggregation; + +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.extern.slf4j.Slf4j; + +/** + * Responsible for collecting and buffering logs from different services. Once the logs reach a + * certain threshold or after a certain time interval, they are flushed to the central log store. + * This class ensures logs are collected and processed asynchronously and efficiently, providing + * both an immediate collection and periodic flushing. + */ +@Slf4j +public class LogAggregator { + + private static final int BUFFER_THRESHOLD = 3; + private final CentralLogStore centralLogStore; + private final ConcurrentLinkedQueue buffer = new ConcurrentLinkedQueue<>(); + private final LogLevel minLogLevel; + private final ExecutorService executorService = Executors.newSingleThreadExecutor(); + private final AtomicInteger logCount = new AtomicInteger(0); + + /** + * constructor of LogAggregator. + * + * @param centralLogStore central log store implement + * @param minLogLevel min log level to store log + */ + public LogAggregator(CentralLogStore centralLogStore, LogLevel minLogLevel) { + this.centralLogStore = centralLogStore; + this.minLogLevel = minLogLevel; + startBufferFlusher(); + } + + /** + * Collects a given log entry, and filters it by the defined log level. + * + * @param logEntry The log entry to collect. + */ + public void collectLog(LogEntry logEntry) { + if (logEntry.getLevel() == null || minLogLevel == null) { + LOGGER.warn("Log level or threshold level is null. Skipping."); + return; + } + + if (logEntry.getLevel().compareTo(minLogLevel) < 0) { + LOGGER.debug("Log level below threshold. Skipping."); + return; + } + + buffer.offer(logEntry); + + if (logCount.incrementAndGet() >= BUFFER_THRESHOLD) { + flushBuffer(); + } + } + + /** + * Stops the log aggregator service and flushes any remaining logs to the central log store. + * + * @throws InterruptedException If any thread has interrupted the current thread. + */ + public void stop() throws InterruptedException { + executorService.shutdownNow(); + if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) { + LOGGER.error("Log aggregator did not terminate."); + } + flushBuffer(); + } + + private void flushBuffer() { + LogEntry logEntry; + while ((logEntry = buffer.poll()) != null) { + centralLogStore.storeLog(logEntry); + logCount.decrementAndGet(); + } + } + + private void startBufferFlusher() { + executorService.execute( + () -> { + while (!Thread.currentThread().isInterrupted()) { + try { + Thread.sleep(5000); // Flush every 5 seconds. + flushBuffer(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }); + } +} diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogEntry.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogEntry.java new file mode 100644 index 000000000000..93fe30d7c246 --- /dev/null +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogEntry.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.logaggregation; + +import java.time.LocalDateTime; +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * Represents a single log entry, capturing essential details like the service name, log level, + * message, and the timestamp when the log was generated. + */ +@Data +@AllArgsConstructor +public class LogEntry { + private String serviceName; + private LogLevel level; + private String message; + private LocalDateTime timestamp; +} diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogLevel.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogLevel.java new file mode 100644 index 000000000000..da6c69afb179 --- /dev/null +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogLevel.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.logaggregation; + +/** + * Enum representing different log levels. Defines the severity of a log message, helping in + * filtering and prioritization. + * + *

      + *
    • DEBUG: Detailed information, typically of interest only when diagnosing problems. + *
    • INFO: Confirmation that things are working as expected. + *
    • ERROR: Indicates a problem that needs attention. + *
    + */ +public enum LogLevel { + DEBUG, + INFO, + ERROR +} diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogProducer.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogProducer.java new file mode 100644 index 000000000000..a1d3f4c71ad9 --- /dev/null +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogProducer.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.logaggregation; + +import java.time.LocalDateTime; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** + * Represents a service that produces logs. The logs are generated based on certain activities or + * events within the service. Once a log is generated, it's passed on to the aggregator for further + * processing. + */ +@AllArgsConstructor +@Slf4j +public class LogProducer { + + private String serviceName; + private LogAggregator aggregator; + + /** + * Generates a log entry with the given log level and message. + * + * @param level The level of the log. + * @param message The message of the log. + */ + public void generateLog(LogLevel level, String message) { + final LogEntry logEntry = new LogEntry(serviceName, level, message, LocalDateTime.now()); + LOGGER.info("Producing log: " + logEntry.getMessage()); + aggregator.collectLog(logEntry); + } +} diff --git a/microservices-log-aggregation/src/test/java/com/iluwatar/logaggregation/LogAggregatorTest.java b/microservices-log-aggregation/src/test/java/com/iluwatar/logaggregation/LogAggregatorTest.java new file mode 100644 index 000000000000..219bb4c48fad --- /dev/null +++ b/microservices-log-aggregation/src/test/java/com/iluwatar/logaggregation/LogAggregatorTest.java @@ -0,0 +1,79 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.logaggregation; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.time.LocalDateTime; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class LogAggregatorTest { + + @Mock private CentralLogStore centralLogStore; + private LogAggregator logAggregator; + + @BeforeEach + void setUp() { + logAggregator = new LogAggregator(centralLogStore, LogLevel.INFO); + } + + @Test + void whenThreeInfoLogsAreCollected_thenCentralLogStoreShouldStoreAllOfThem() { + logAggregator.collectLog(createLogEntry(LogLevel.INFO, "Sample log message 1")); + logAggregator.collectLog(createLogEntry(LogLevel.INFO, "Sample log message 2")); + + verifyNoInteractionsWithCentralLogStore(); + + logAggregator.collectLog(createLogEntry(LogLevel.INFO, "Sample log message 3")); + + verifyCentralLogStoreInvokedTimes(3); + } + + @Test + void whenDebugLogIsCollected_thenNoLogsShouldBeStored() { + logAggregator.collectLog(createLogEntry(LogLevel.DEBUG, "Sample debug log message")); + + verifyNoInteractionsWithCentralLogStore(); + } + + private static LogEntry createLogEntry(LogLevel logLevel, String message) { + return new LogEntry("ServiceA", logLevel, message, LocalDateTime.now()); + } + + private void verifyNoInteractionsWithCentralLogStore() { + verify(centralLogStore, times(0)).storeLog(any()); + } + + private void verifyCentralLogStoreInvokedTimes(int times) { + verify(centralLogStore, times(times)).storeLog(any()); + } +} diff --git a/model-view-controller/README.md b/model-view-controller/README.md index bc96f7ab1e01..536cb2ca4a2a 100644 --- a/model-view-controller/README.md +++ b/model-view-controller/README.md @@ -1,29 +1,166 @@ --- -layout: pattern -title: Model-View-Controller -folder: model-view-controller -permalink: /patterns/model-view-controller/ -categories: Presentation Tier -tags: - - Java - - Difficulty-Intermediate +title: "Model-View-Controller Pattern in Java: Streamlining Java Web Development" +shortTitle: Model-View-Controller (MVC) +description: "Learn about the Model-View-Controller (MVC) design pattern in Java, including its benefits, real-world examples, use cases, and how to implement it effectively in your applications." +category: Architectural +language: en +tag: + - Architecture + - Client-server + - Decoupling + - Layered architecture + - Presentation --- -## Intent -Separate the user interface into three interconnected components: -the model, the view and the controller. Let the model manage the data, the view -display the data and the controller mediate updating the data and redrawing the -display. +## Also known as -![alt text](./etc/model-view-controller.png "Model-View-Controller") +* MVC -## Applicability -Use the Model-View-Controller pattern when +## Intent of Model-View-Controller Design Pattern -* you want to clearly separate the domain data from its user interface representation +To separate an application into three interconnected components (Model, View, Controller), enabling modular development of each part independently, enhancing maintainability and scalability. Model-View-Controller (MVC) design pattern is widely used in Java applications for web development and user interface separation. -## Credits +## Detailed Explanation of Model-View-Controller Pattern with Real-World Examples -* [Trygve Reenskaug - Model-view-controller](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) -* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2) -* [Patterns of Enterprise Application Architecture](http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420) +Real-world example + +> Consider ICU room in a hospital displaying patient health information on devices taking input from sensors. The display shows data received from the controller, which updates from the sensor model. This exemplifies the MVC design pattern in a real-world Java application. + +In plain words + +> MVC separates the business logic from user interface by mediating Controller between Model & View. + +Wikipedia says + +> Model–view–controller (MVC) is commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted from the user. + +Architecture diagram + +![Model-View-Controller Architecture Diagram](./etc/mvc-architecture-diagram.png) + + +## Programmatic Example of Model-View-Controller Pattern in Java + +Consider following `GiantModel` model class that provides the health, fatigue & nourishment information. + +```java +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class GiantModel { + + private Health health; + private Fatigue fatigue; + private Nourishment nourishment; + + @Override + public String toString() { + return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment); + } +} +``` + +`GiantView` class to display received patient data. + +```java +public class GiantView { + + public void displayGiant(GiantModel giant) { + LOGGER.info(giant.toString()); + } +} +``` + +`GiantController` class takes updates from `GiantModel` and sends to `GiantView` for display. + +```java +public class GiantController { + + private final GiantModel giant; + private final GiantView view; + + public GiantController(GiantModel giant, GiantView view) { + this.giant = giant; + this.view = view; + } + + @SuppressWarnings("UnusedReturnValue") + public Health getHealth() { + return giant.getHealth(); + } + + public void setHealth(Health health) { + this.giant.setHealth(health); + } + + @SuppressWarnings("UnusedReturnValue") + public Fatigue getFatigue() { + return giant.getFatigue(); + } + + public void setFatigue(Fatigue fatigue) { + this.giant.setFatigue(fatigue); + } + + @SuppressWarnings("UnusedReturnValue") + public Nourishment getNourishment() { + return giant.getNourishment(); + } + + public void setNourishment(Nourishment nourishment) { + this.giant.setNourishment(nourishment); + } + + public void updateView() { + this.view.displayGiant(giant); + } +} +``` + +This example demonstrates how the MVC pattern separates concerns in a Java application, making it easier to manage and update components independently. + +## When to Use the Model-View-Controller Pattern in Java + +* Used in web applications to separate data model, user interface, and user input processing. +* Suitable for applications requiring a clear separation of concerns, ensuring that the business logic, user interface, and user input are loosely coupled and independently managed, following the MVC pattern. + +## Model-View-Controller Pattern Java Tutorials + +* [Spring Boot Model (ZetCode)](https://zetcode.com/springboot/model/) +* [Spring MVC Tutorial (Baeldung)](https://www.baeldung.com/spring-mvc-tutorial) + +## Real-World Applications of Model-View-Controller Pattern in Java + +* Frameworks like Spring MVC in Java for web applications. +* Desktop applications in Java, such as those using Swing or JavaFX. + +## Benefits and Trade-offs of Model-View-Controller Pattern + +Benefits: + +* Promotes organized code structure by separating concerns. +* Facilitates parallel development of components. +* Enhances testability due to decoupled nature. +* Easier to manage and update individual parts without affecting others. + +Trade-offs: + +* Increased complexity in initially setting up the architecture. +* Can lead to excessive boilerplate if not implemented correctly or for very small projects. + +## Related Java Design Patterns + +* [Observer](https://java-design-patterns.com/patterns/observer/): Often used in MVC where the view observes the model for changes; this is a fundamental relationship for updating the UI when the model state changes. +* [Strategy](https://java-design-patterns.com/patterns/strategy/): Controllers may use different strategies for handling user input, related through the ability to switch strategies for user input processing in Java MVC applications. +* [Composite](https://java-design-patterns.com/patterns/composite/): Views can be structured using the Composite Pattern to manage hierarchies of user interface components. + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) +* [Pro Spring 5: An In-Depth Guide to the Spring Framework and Its Tools](https://amzn.to/3y9Rrwp) +* [Model-view-controller (Wikipedia)](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) diff --git a/model-view-controller/etc/model-view-controller.urm.puml b/model-view-controller/etc/model-view-controller.urm.puml new file mode 100644 index 000000000000..92ec1e949d83 --- /dev/null +++ b/model-view-controller/etc/model-view-controller.urm.puml @@ -0,0 +1,70 @@ +@startuml +package com.iluwatar.model.view.controller { + class App { + + App() + + main(args : String[]) {static} + } + enum Fatigue { + + ALERT {static} + + SLEEPING {static} + + TIRED {static} + - title : String + + toString() : String + + valueOf(name : String) : Fatigue {static} + + values() : Fatigue[] {static} + } + class GiantController { + - giant : GiantModel + - view : GiantView + + GiantController(giant : GiantModel, view : GiantView) + + getFatigue() : Fatigue + + getHealth() : Health + + getNourishment() : Nourishment + + setFatigue(fatigue : Fatigue) + + setHealth(health : Health) + + setNourishment(nourishment : Nourishment) + + updateView() + } + class GiantModel { + - fatigue : Fatigue + - health : Health + - nourishment : Nourishment + ~ GiantModel(health : Health, fatigue : Fatigue, nourishment : Nourishment) + + getFatigue() : Fatigue + + getHealth() : Health + + getNourishment() : Nourishment + + setFatigue(fatigue : Fatigue) + + setHealth(health : Health) + + setNourishment(nourishment : Nourishment) + + toString() : String + } + class GiantView { + - LOGGER : Logger {static} + + GiantView() + + displayGiant(giant : GiantModel) + } + enum Health { + + DEAD {static} + + HEALTHY {static} + + WOUNDED {static} + - title : String + + toString() : String + + valueOf(name : String) : Health {static} + + values() : Health[] {static} + } + enum Nourishment { + + HUNGRY {static} + + SATURATED {static} + + STARVING {static} + - title : String + + toString() : String + + valueOf(name : String) : Nourishment {static} + + values() : Nourishment[] {static} + } +} +GiantModel --> "-nourishment" Nourishment +GiantController --> "-giant" GiantModel +GiantModel --> "-fatigue" Fatigue +GiantModel --> "-health" Health +GiantController --> "-view" GiantView +@enduml \ No newline at end of file diff --git a/model-view-controller/etc/mvc-architecture-diagram.png b/model-view-controller/etc/mvc-architecture-diagram.png new file mode 100644 index 000000000000..33371d41f22c Binary files /dev/null and b/model-view-controller/etc/mvc-architecture-diagram.png differ diff --git a/model-view-controller/pom.xml b/model-view-controller/pom.xml index 89f7bd825732..807596459140 100644 --- a/model-view-controller/pom.xml +++ b/model-view-controller/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT model-view-controller - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -49,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.model.view.controller.App + + + + + + + + diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java index a2f8d7a6ebde..b804af1b9d5a 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,34 +25,32 @@ package com.iluwatar.model.view.controller; /** - * * Model-View-Controller is a pattern for implementing user interfaces. It divides the application * into three interconnected parts namely the model, the view and the controller. - *

    - * The central component of MVC, the model, captures the behavior of the application in terms of its - * problem domain, independent of the user interface. The model directly manages the data, logic and - * rules of the application. A view can be any output representation of information, such as a chart - * or a diagram The third part, the controller, accepts input and converts it to commands for the - * model or view. - *

    - * In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and - * nourishment. {@link GiantView} can display the giant with its current status. - * {@link GiantController} receives input affecting the model and delegates redrawing the giant to - * the view. * + *

    The central component of MVC, the model, captures the behavior of the application in terms of + * its problem domain, independent of the user interface. The model directly manages the data, logic + * and rules of the application. A view can be any output representation of information, such as a + * chart or a diagram The third part, the controller, accepts input and converts it to commands for + * the model or view. + * + *

    In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and + * nourishment. {@link GiantView} can display the giant with its current status. {@link + * GiantController} receives input affecting the model and delegates redrawing the giant to the + * view. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { // create model, view and controller - GiantModel giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); - GiantView view = new GiantView(); - GiantController controller = new GiantController(giant, view); + var giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); + var view = new GiantView(); + var controller = new GiantController(giant, view); // initial display controller.updateView(); // controller receives some interactions that affect the giant diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java index 8c9ec44668d8..a4a3c69cbb4f 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,16 @@ */ package com.iluwatar.model.view.controller; -/** - * - * Fatigue enumeration - * - */ -public enum Fatigue { +import lombok.AllArgsConstructor; - ALERT("alert"), TIRED("tired"), SLEEPING("sleeping"); - - private String title; +/** Fatigue enumeration. */ +@AllArgsConstructor +public enum Fatigue { + ALERT("alert"), + TIRED("tired"), + SLEEPING("sleeping"); - Fatigue(String title) { - this.title = title; - } + private final String title; @Override public String toString() { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java index 2d2d7f311e82..5fb8f1acab14 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,21 +24,18 @@ */ package com.iluwatar.model.view.controller; -/** - * - * GiantController can update the giant data and redraw it using the view. - * - */ +/** GiantController can update the giant data and redraw it using the view. */ public class GiantController { - private GiantModel giant; - private GiantView view; + private final GiantModel giant; + private final GiantView view; public GiantController(GiantModel giant, GiantView view) { this.giant = giant; this.view = view; } + @SuppressWarnings("UnusedReturnValue") public Health getHealth() { return giant.getHealth(); } @@ -45,6 +44,7 @@ public void setHealth(Health health) { this.giant.setHealth(health); } + @SuppressWarnings("UnusedReturnValue") public Fatigue getFatigue() { return giant.getFatigue(); } @@ -53,6 +53,7 @@ public void setFatigue(Fatigue fatigue) { this.giant.setFatigue(fatigue); } + @SuppressWarnings("UnusedReturnValue") public Nourishment getNourishment() { return giant.getNourishment(); } diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java index 96ccfa233475..8be7e6e4e47c 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,47 +24,24 @@ */ package com.iluwatar.model.view.controller; -/** - * - * GiantModel contains the giant data - * - */ +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** GiantModel contains the giant data. */ +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor public class GiantModel { private Health health; private Fatigue fatigue; private Nourishment nourishment; - GiantModel(Health health, Fatigue fatigue, Nourishment nourishment) { - this.health = health; - this.fatigue = fatigue; - this.nourishment = nourishment; - } - - public Health getHealth() { - return health; - } - - public void setHealth(Health health) { - this.health = health; - } - - public Fatigue getFatigue() { - return fatigue; - } - - public void setFatigue(Fatigue fatigue) { - this.fatigue = fatigue; - } - - public Nourishment getNourishment() { - return nourishment; - } - - public void setNourishment(Nourishment nourishment) { - this.nourishment = nourishment; - } - @Override public String toString() { return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment); diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java index 36beadf709d2..a9696d898c78 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,12 @@ */ package com.iluwatar.model.view.controller; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; -/** - * - * GiantView displays the giant - * - */ +/** GiantView displays the giant. */ +@Slf4j public class GiantView { - private static final Logger LOGGER = LoggerFactory.getLogger(GiantView.class); - public void displayGiant(GiantModel giant) { LOGGER.info(giant.toString()); } diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java index 0adcaf99ba88..7fba2f54f43e 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,16 @@ */ package com.iluwatar.model.view.controller; -/** - * - * Health enumeration - * - */ -public enum Health { +import lombok.AllArgsConstructor; - HEALTHY("healthy"), WOUNDED("wounded"), DEAD("dead"); - - private String title; +/** Health enumeration. */ +@AllArgsConstructor +public enum Health { + HEALTHY("healthy"), + WOUNDED("wounded"), + DEAD("dead"); - Health(String title) { - this.title = title; - } + private final String title; @Override public String toString() { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java index 1f3e2a20fe74..d385588bbd2d 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,20 +24,16 @@ */ package com.iluwatar.model.view.controller; -/** - * - * Nourishment enumeration - * - */ -public enum Nourishment { +import lombok.AllArgsConstructor; - SATURATED("saturated"), HUNGRY("hungry"), STARVING("starving"); - - private String title; +/** Nourishment enumeration. */ +@AllArgsConstructor +public enum Nourishment { + SATURATED("saturated"), + HUNGRY("hungry"), + STARVING("starving"); - Nourishment(String title) { - this.title = title; - } + private final String title; @Override public String toString() { diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java index 1c4dc3dad1db..b435b393061d 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,18 +24,15 @@ */ package com.iluwatar.model.view.controller; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java index 73f3487702e6..9dc9f2807e74 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,101 +24,92 @@ */ package com.iluwatar.model.view.controller; -import org.junit.jupiter.api.Test; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; -/** - * Date: 12/20/15 - 2:19 PM - * - * @author Jeroen Meulemeester - */ -public class GiantControllerTest { +import org.junit.jupiter.api.Test; - /** - * Verify if the controller passes the health level through to the model and vice versa - */ +/** GiantControllerTest */ +class GiantControllerTest { + + /** Verify if the controller passes the health level through to the model and vice versa */ @Test - public void testSetHealth() { - final GiantModel model = mock(GiantModel.class); - final GiantView view = mock(GiantView.class); - final GiantController controller = new GiantController(model, view); + void testSetHealth() { + final var model = mock(GiantModel.class); + final var view = mock(GiantView.class); + final var controller = new GiantController(model, view); - verifyZeroInteractions(model, view); + verifyNoMoreInteractions(model, view); - for (final Health health : Health.values()) { + for (final var health : Health.values()) { controller.setHealth(health); verify(model).setHealth(health); - verifyZeroInteractions(view); + verifyNoMoreInteractions(view); } controller.getHealth(); + //noinspection ResultOfMethodCallIgnored verify(model).getHealth(); verifyNoMoreInteractions(model, view); } - /** - * Verify if the controller passes the fatigue level through to the model and vice versa - */ + /** Verify if the controller passes the fatigue level through to the model and vice versa */ @Test - public void testSetFatigue() { - final GiantModel model = mock(GiantModel.class); - final GiantView view = mock(GiantView.class); - final GiantController controller = new GiantController(model, view); + void testSetFatigue() { + final var model = mock(GiantModel.class); + final var view = mock(GiantView.class); + final var controller = new GiantController(model, view); - verifyZeroInteractions(model, view); + verifyNoMoreInteractions(model, view); - for (final Fatigue fatigue : Fatigue.values()) { + for (final var fatigue : Fatigue.values()) { controller.setFatigue(fatigue); verify(model).setFatigue(fatigue); - verifyZeroInteractions(view); + verifyNoMoreInteractions(view); } controller.getFatigue(); + //noinspection ResultOfMethodCallIgnored verify(model).getFatigue(); verifyNoMoreInteractions(model, view); } - /** - * Verify if the controller passes the nourishment level through to the model and vice versa - */ + /** Verify if the controller passes the nourishment level through to the model and vice versa */ @Test - public void testSetNourishment() { - final GiantModel model = mock(GiantModel.class); - final GiantView view = mock(GiantView.class); - final GiantController controller = new GiantController(model, view); + void testSetNourishment() { + final var model = mock(GiantModel.class); + final var view = mock(GiantView.class); + final var controller = new GiantController(model, view); - verifyZeroInteractions(model, view); + verifyNoMoreInteractions(model, view); - for (final Nourishment nourishment : Nourishment.values()) { + for (final var nourishment : Nourishment.values()) { controller.setNourishment(nourishment); verify(model).setNourishment(nourishment); - verifyZeroInteractions(view); + verifyNoMoreInteractions(view); } controller.getNourishment(); + //noinspection ResultOfMethodCallIgnored verify(model).getNourishment(); verifyNoMoreInteractions(model, view); } @Test - public void testUpdateView() { - final GiantModel model = mock(GiantModel.class); - final GiantView view = mock(GiantView.class); - final GiantController controller = new GiantController(model, view); + void testUpdateView() { + final var model = mock(GiantModel.class); + final var view = mock(GiantView.class); + final var controller = new GiantController(model, view); - verifyZeroInteractions(model, view); + verifyNoMoreInteractions(model, view); controller.updateView(); verify(view).displayGiant(model); verifyNoMoreInteractions(model, view); } - -} \ No newline at end of file +} diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java index 339c170f4cf5..ed9eefc4ea62 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,57 +24,49 @@ */ package com.iluwatar.model.view.controller; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Date: 12/20/15 - 2:10 PM - * - * @author Jeroen Meulemeester - */ -public class GiantModelTest { +import org.junit.jupiter.api.Test; - /** - * Verify if the health value is set properly though the constructor and setter - */ +/** GiantModelTest */ +class GiantModelTest { + + /** Verify if the health value is set properly though the constructor and setter */ @Test - public void testSetHealth() { - final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); + void testSetHealth() { + final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Health.HEALTHY, model.getHealth()); - for (final Health health : Health.values()) { + var messageFormat = "The giant looks %s, alert and saturated."; + for (final var health : Health.values()) { model.setHealth(health); assertEquals(health, model.getHealth()); - assertEquals("The giant looks " + health.toString() + ", alert and saturated.", model.toString()); + assertEquals(String.format(messageFormat, health), model.toString()); } } - /** - * Verify if the fatigue level is set properly though the constructor and setter - */ + /** Verify if the fatigue level is set properly though the constructor and setter */ @Test - public void testSetFatigue() { - final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); + void testSetFatigue() { + final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Fatigue.ALERT, model.getFatigue()); - for (final Fatigue fatigue : Fatigue.values()) { + var messageFormat = "The giant looks healthy, %s and saturated."; + for (final var fatigue : Fatigue.values()) { model.setFatigue(fatigue); assertEquals(fatigue, model.getFatigue()); - assertEquals("The giant looks healthy, " + fatigue.toString() + " and saturated.", model.toString()); + assertEquals(String.format(messageFormat, fatigue), model.toString()); } } - /** - * Verify if the nourishment level is set properly though the constructor and setter - */ + /** Verify if the nourishment level is set properly though the constructor and setter */ @Test - public void testSetNourishment() { - final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); + void testSetNourishment() { + final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Nourishment.SATURATED, model.getNourishment()); - for (final Nourishment nourishment : Nourishment.values()) { + var messageFormat = "The giant looks healthy, alert and %s."; + for (final var nourishment : Nourishment.values()) { model.setNourishment(nourishment); assertEquals(nourishment, model.getNourishment()); - assertEquals("The giant looks healthy, alert and " + nourishment.toString() + ".", model.toString()); + assertEquals(String.format(messageFormat, nourishment), model.toString()); } } - } diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java index 855c976060d1..da2032b7fd94 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -30,28 +32,23 @@ import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * Date: 12/20/15 - 2:04 PM - * - * @author Jeroen Meulemeester - */ -public class GiantViewTest { +/** GiantViewTest */ +class GiantViewTest { private InMemoryAppender appender; @BeforeEach - public void setUp() { + void setUp() { appender = new InMemoryAppender(GiantView.class); } @AfterEach - public void tearDown() { + void tearDown() { appender.stop(); } @@ -60,23 +57,21 @@ public void tearDown() { * standard out stream, nothing more, nothing less. */ @Test - public void testDisplayGiant() { - final GiantView view = new GiantView(); + void testDisplayGiant() { + final var view = new GiantView(); - final GiantModel model = mock(GiantModel.class); + final var model = mock(GiantModel.class); view.displayGiant(model); assertEquals(model.toString(), appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - /** - * Logging Appender Implementation - */ - public class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); + /** Logging Appender Implementation */ + public static class InMemoryAppender extends AppenderBase { + private final List log = new LinkedList<>(); - public InMemoryAppender(Class clazz) { + public InMemoryAppender(Class clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } diff --git a/model-view-intent/README.md b/model-view-intent/README.md new file mode 100644 index 000000000000..1febe76b0327 --- /dev/null +++ b/model-view-intent/README.md @@ -0,0 +1,230 @@ +--- +title: "Model-View-Intent Pattern in Java: Building Robust and Scalable Java UIs with MVI" +shortTitle: Model-View-Intent (MVI) +description: "Discover the Model-View-Intent (MVI) pattern for Java applications. Learn how MVI enhances UI predictability, maintainability, and state management through unidirectional data flow. Explore real-world examples and implementation details." +category: Architectural +language: en +tags: + - Abstraction + - Decoupling + - Presentation + - Reactive + - State tracking +--- + +## Also known as + +* MVI + +## Intent of Model-View-Intent Design Pattern + +The Model-View-Intent (MVI) pattern for Java applications creates a unidirectional and cyclical data flow between the Model, View, and Intent components, enhancing UI predictability and state management. + +## Detailed Explanation of Model-View-Intent Pattern with Real-World Examples + +Real-world example + +> Consider a real-world analogy of the Model-View-Intent (MVI) pattern in Java using the scenario of ordering at a fast-food restaurant to understand its application in enhancing UI state management. +> +> In this analogy: +> - **Model:** It's like the kitchen of the restaurant, where the current state of your order is managed. As you choose items, the kitchen updates the order status and ingredients used. +> - **View:** This represents the menu and the digital display board where you see your current order summary. It reflects the current state of your order, showing what items you've added or removed. +> - **Intent:** Think of this as your decision-making process when you interact with the menu. Each choice you make (like adding a burger or removing a drink) sends a specific intention to the system (kitchen). +> +> When you decide to add an item to your order (Intent), the kitchen (Model) processes this request, updates the state of your order, and then the display (View) updates to show the latest status of your order. This cycle continues until you finalize your order, demonstrating the unidirectional and cyclical flow characteristic of MVI. This ensures that every change in the order is predictably and accurately reflected in the customer's view, similar to how UI components update in response to state changes in software using MVI. + +In plain words + +> The Model-View-Intent (MVI) pattern is a reactive architectural approach where user actions (Intent) modify the application state (Model), and the updated state is then reflected back in the user interface (View) in a unidirectional and cyclical data flow. + +Architecture diagram + +![Model-View-Intent Architecture Diagram](./etc/mvi-architecture-diagram.png) + + +## Programmatic Example of Model-View-Intent Pattern in Java + +The Model-View-Intent (MVI) pattern for Java is a modern approach to structuring your application's logic, ensuring a smooth, unidirectional flow of data and events. It's a variation of the Model-View-Presenter (MVP) and Model-View-ViewModel (MVVM) patterns, but with a more streamlined flow of data and events. + +In MVI, the View sends user events to the Intent. The Intent translates these events into a state change in the Model. The Model then pushes this new state to the View, which updates itself accordingly. This creates a unidirectional data flow, which can make your code easier to understand and debug. + +First, we have the `App` class, which serves as the entry point for the application. It creates the View and ViewModel, and then simulates a series of user interactions with the calculator. + +```java +public final class App { + private static final double RANDOM_VARIABLE = 10.0; + + public static void main(final String[] args) { + var view = new CalculatorView(new CalculatorViewModel()); + var variable1 = RANDOM_VARIABLE; + + view.setVariable(variable1); + view.add(); + view.displayTotal(); + + variable1 = 2.0; + view.setVariable(variable1); + view.subtract(); + view.divide(); + view.multiply(); + view.displayTotal(); + } + + private App() { + } +} +``` + +The `CalculatorView` class represents the View in MVI. It receives user events (in this case, simulated by the `App` class), and sends them to the ViewModel. It also updates its display when it receives a new state from the ViewModel. + +```java +public class CalculatorView { + private CalculatorViewModel viewModel; + + public CalculatorView(CalculatorViewModel viewModel) { + this.viewModel = viewModel; + } + + public void setVariable(double variable) { + viewModel.process(new SetVariableEvent(variable)); + } + + public void add() { + viewModel.process(new AddEvent()); + } + + public void subtract() { + viewModel.process(new SubtractEvent()); + } + + public void divide() { + viewModel.process(new DivideEvent()); + } + + public void multiply() { + viewModel.process(new MultiplyEvent()); + } + + public void displayTotal() { + System.out.println("Total: " + viewModel.getState().getTotal()); + } +} +``` + +The `CalculatorViewModel` class represents the ViewModel in MVI. It receives events from the View, updates the Model's state accordingly, and then pushes the new state to the View. + +```java +public class CalculatorViewModel { + private CalculatorModel model; + + public CalculatorViewModel() { + this.model = new CalculatorModel(); + } + + public void process(UserEvent event) { + event.apply(model); + } + + public CalculatorModel getState() { + return model; + } +} +``` + +The `CalculatorModel` class represents the Model in MVI. It holds the current state of the calculator, and provides methods for updating that state. + +```java +public class CalculatorModel { + private double total; + private double variable; + + public void setVariable(double variable) { + this.variable = variable; + } + + public void add() { + total += variable; + } + + public void subtract() { + total -= variable; + } + + public void divide() { + total /= variable; + } + + public void multiply() { + total *= variable; + } + + public double getTotal() { + return total; + } +} +``` + +Finally, the `UserEvent` interface and its implementations represent the different types of user events that can occur. Each event knows how to apply itself to the Model. + +```java +public interface UserEvent { + void apply(CalculatorModel model); +} + +public class SetVariableEvent implements UserEvent { + private double variable; + + public SetVariableEvent(double variable) { + this.variable = variable; + } + + @Override + public void apply(CalculatorModel model) { + model.setVariable(variable); + } +} + +// Similar classes would be created for AddEvent, SubtractEvent, DivideEvent, and MultiplyEvent ... +``` + +This example demonstrates the key aspects of the MVI pattern: unidirectional data flow, clear separation of concerns, and the use of events to drive changes in the Model's state. + +## When to Use the Model-View-Intent Pattern in Java + +* The MVI pattern is useful in Java applications with complex user interfaces that require a clear separation of concerns, predictable state management, and enhanced maintainability. +* Often applied in reactive programming environments to ensure a smooth data flow and state consistency. + +## Model-View-Intent Pattern Java Tutorials + +* [Model View Intent: a new Android Architecture Pattern (Apium Academy)](https://apiumacademy.com/blog/model-view-intent-pattern/) +* [MVI Architecture for Android Tutorial: Getting Started (Kodeco)](https://www.kodeco.com/817602-mvi-architecture-for-android-tutorial-getting-started) + +## Real-World Applications of Model-View-Intent Pattern in Java + +* Widely adopted in reactive and event-driven Java applications, particularly those using frameworks like RxJava or Project Reactor. +* Used in Android development, especially with libraries that support reactive programming such as RxJava and LiveData. + +## Benefits and Trade-offs of Model-View-Intent Pattern + +Benefits: + +* Enhances the predictability of the UI by establishing a clear and cyclical data flow. +* Improves testability due to well-defined separation between components. +* Supports better state management by centralizing the state within the Model. + +Trade-offs: + +* Increases complexity for simple UIs due to the structured and cyclical flow. +* Requires familiarity with reactive programming paradigms. +* Can lead to boilerplate code if not managed properly. + +## Related Java Design Patterns + +[Model-View-ViewModel (MVVM)](https://java-design-patterns.com/patterns/model-view-viewmodel/): Shares a similar goal of separating the view from the model but differs as MVI introduces a cyclical data flow. +[Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): MVI can be seen as an evolution of MVC, focusing more on reactive programming and unidirectional data flow. +[Observer](https://java-design-patterns.com/patterns/observer/): Essential in MVI to observe changes in the Model and update the View accordingly. + +## References and Credits + +* [Functional and Reactive Domain Modeling](https://amzn.to/4adghJ8) +* [Reactive Programming with RxJava: Creating Asynchronous, Event-Based Applications](https://amzn.to/4dxwawC) diff --git a/model-view-intent/etc/model-view-intent.png b/model-view-intent/etc/model-view-intent.png new file mode 100644 index 000000000000..0c1648ff4b3d Binary files /dev/null and b/model-view-intent/etc/model-view-intent.png differ diff --git a/model-view-intent/etc/model-view-intent.urm.puml b/model-view-intent/etc/model-view-intent.urm.puml new file mode 100644 index 000000000000..8b1f7c31406d --- /dev/null +++ b/model-view-intent/etc/model-view-intent.urm.puml @@ -0,0 +1,74 @@ +@startuml +package com.iluwatar.model.view.intent.actions { + class AdditionCalculatorAction { + + TAG : String {static} + + AdditionCalculatorAction() + + tag() : String + } + interface CalculatorAction { + + tag() : String {abstract} + } + class DivisionCalculatorAction { + + TAG : String {static} + + DivisionCalculatorAction() + + tag() : String + } + class MultiplicationCalculatorAction { + + TAG : String {static} + + MultiplicationCalculatorAction() + + tag() : String + } + class SetVariableCalculatorAction { + + TAG : String {static} + + variable : Double + + SetVariableCalculatorAction(variable : Double) + + tag() : String + } + class SubtractionCalculatorAction { + + TAG : String {static} + + SubtractionCalculatorAction() + + tag() : String + } +} +package com.iluwatar.model.view.intent { + class App { + + App() + + main(args : String[]) {static} + } + class CalculatorModel { + + output : Double + + variable : Double + + CalculatorModel(output : Double, variable : Double) + + copy(output : Double, variable : Double) : CalculatorModel + } + class CalculatorView { + - LOGGER : Logger {static} + ~ viewModel : CalculatorViewModel + + CalculatorView() + ~ add() + ~ displayTotal() + ~ divide() + ~ multiply() + ~ setVariable(value : Double) + ~ subtract() + } + class CalculatorViewModel { + - model : CalculatorModel + + CalculatorViewModel() + - add() + - divide() + + getCalculatorModel() : CalculatorModel + ~ handleAction(action : CalculatorAction) + - multiply() + - setVariable(variable : Double) + - subtract() + } +} +CalculatorView --> "-viewModel" CalculatorViewModel +CalculatorViewModel --> "-model" CalculatorModel +AdditionCalculatorAction ..|> CalculatorAction +DivisionCalculatorAction ..|> CalculatorAction +MultiplicationCalculatorAction ..|> CalculatorAction +SetVariableCalculatorAction ..|> CalculatorAction +SubtractionCalculatorAction ..|> CalculatorAction +@enduml \ No newline at end of file diff --git a/model-view-intent/etc/mvi-architecture-diagram.png b/model-view-intent/etc/mvi-architecture-diagram.png new file mode 100644 index 000000000000..a0672ddc051f Binary files /dev/null and b/model-view-intent/etc/mvi-architecture-diagram.png differ diff --git a/model-view-intent/pom.xml b/model-view-intent/pom.xml new file mode 100644 index 000000000000..048acd19952f --- /dev/null +++ b/model-view-intent/pom.xml @@ -0,0 +1,75 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.26.0-SNAPSHOT + + model-view-intent + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.mockito + mockito-core + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.model.view.controller.App + + + + + + + + + diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/App.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/App.java new file mode 100644 index 000000000000..4bb699cf2834 --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/App.java @@ -0,0 +1,76 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent; + +/** + * Model-View-Intent is a pattern for implementing user interfaces. Its main advantage over MVVM + * which it closely mirrors is a minimal public api with which user events can be exposed to the + * ViewModel. In case of the MVI every event is exposed by using a single method with 1 argument + * which implements UserEvent interface. Specific parameters can be expressed as its parameters. In + * this case, we'll be using MVI to implement a simple calculator with +, -, /, * operations and the + * ability to set the variable. It's important to note, that every user action happens through the + * view, we never interact with the ViewModel directly. + */ +public final class App { + + /** To avoid magic value lint error. */ + private static final double RANDOM_VARIABLE = 10.0; + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(final String[] args) { + // create model, view and controller + + // initialize calculator view, output and variable = 0 + var view = new CalculatorView(new CalculatorViewModel()); + var variable1 = RANDOM_VARIABLE; + + // calculator variable = RANDOM_VARIABLE -> 10.0 + view.setVariable(variable1); + + // add calculator variable to output -> calculator output = 10.0 + view.add(); + view.displayTotal(); // display output + + variable1 = 2.0; + view.setVariable(variable1); // calculator variable = 2.0 + + // subtract calculator variable from output -> calculator output = 8 + view.subtract(); + + // divide calculator output by variable -> calculator output = 4.0 + view.divide(); + + // multiply calculator output by variable -> calculator output = 8.0 + view.multiply(); + view.displayTotal(); + } + + /** Avoid default constructor lint error. */ + private App() {} +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorModel.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorModel.java new file mode 100644 index 000000000000..3ef9c9934248 --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorModel.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent; + +import lombok.Data; +import lombok.Getter; + +/** Current state of calculator. */ +@Data +public class CalculatorModel { + + /** Current calculator variable used for operations. */ + @Getter private final Double variable; + + /** Current calculator output -> is affected by operations. */ + @Getter private final Double output; +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorView.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorView.java new file mode 100644 index 000000000000..a5ceb587db6e --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorView.java @@ -0,0 +1,81 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent; + +import com.iluwatar.model.view.intent.actions.AdditionCalculatorAction; +import com.iluwatar.model.view.intent.actions.DivisionCalculatorAction; +import com.iluwatar.model.view.intent.actions.MultiplicationCalculatorAction; +import com.iluwatar.model.view.intent.actions.SetVariableCalculatorAction; +import com.iluwatar.model.view.intent.actions.SubtractionCalculatorAction; +import lombok.Data; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +/** + * Exposes changes to the state of calculator to {@link CalculatorViewModel} through {@link + * com.iluwatar.model.view.intent.actions.CalculatorAction} and displays its updated {@link + * CalculatorModel}. + */ +@Slf4j +@Data +public class CalculatorView { + + /** View model param handling the operations. */ + @Getter private final CalculatorViewModel viewModel; + + /** Display current view model output with logger. */ + void displayTotal() { + LOGGER.info("Total value = {}", viewModel.getCalculatorModel().getOutput().toString()); + } + + /** Handle addition action. */ + void add() { + viewModel.handleAction(new AdditionCalculatorAction()); + } + + /** Handle subtraction action. */ + void subtract() { + viewModel.handleAction(new SubtractionCalculatorAction()); + } + + /** Handle multiplication action. */ + void multiply() { + viewModel.handleAction(new MultiplicationCalculatorAction()); + } + + /** Handle division action. */ + void divide() { + viewModel.handleAction(new DivisionCalculatorAction()); + } + + /** + * Handle setting new variable action. + * + * @param value -> new calculator variable. + */ + void setVariable(final Double value) { + viewModel.handleAction(new SetVariableCalculatorAction(value)); + } +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java new file mode 100644 index 000000000000..9c1fee801720 --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java @@ -0,0 +1,98 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent; + +import com.iluwatar.model.view.intent.actions.AdditionCalculatorAction; +import com.iluwatar.model.view.intent.actions.CalculatorAction; +import com.iluwatar.model.view.intent.actions.DivisionCalculatorAction; +import com.iluwatar.model.view.intent.actions.MultiplicationCalculatorAction; +import com.iluwatar.model.view.intent.actions.SetVariableCalculatorAction; +import com.iluwatar.model.view.intent.actions.SubtractionCalculatorAction; + +/** + * Handle transformations to {@link CalculatorModel} based on intercepted {@link CalculatorAction}. + */ +public final class CalculatorViewModel { + + /** Current calculator model (can be changed). */ + private CalculatorModel model = new CalculatorModel(0.0, 0.0); + + /** + * Handle calculator action. + * + * @param action -> transforms calculator model. + */ + void handleAction(final CalculatorAction action) { + switch (action.tag()) { + case AdditionCalculatorAction.ADDITION -> add(); + case SubtractionCalculatorAction.SUBTRACTION -> subtract(); + case MultiplicationCalculatorAction.MULTIPLICATION -> multiply(); + case DivisionCalculatorAction.DIVISION -> divide(); + case SetVariableCalculatorAction.SET_VARIABLE -> { + SetVariableCalculatorAction setVariableAction = (SetVariableCalculatorAction) action; + setVariable(setVariableAction.getVariable()); + } + default -> throw new IllegalArgumentException("Unknown tag"); + } + } + + /** + * Getter. + * + * @return current calculator model. + */ + public CalculatorModel getCalculatorModel() { + return model; + } + + /** + * Set new calculator model variable. + * + * @param variable -> value of new calculator model variable. + */ + private void setVariable(final Double variable) { + model = new CalculatorModel(variable, model.getOutput()); + } + + /** Add variable to model output. */ + private void add() { + model = new CalculatorModel(model.getVariable(), model.getOutput() + model.getVariable()); + } + + /** Subtract variable from model output. */ + private void subtract() { + model = new CalculatorModel(model.getVariable(), model.getOutput() - model.getVariable()); + } + + /** Multiply model output by variable. */ + private void multiply() { + model = new CalculatorModel(model.getVariable(), model.getOutput() * model.getVariable()); + } + + /** Divide model output by variable. */ + private void divide() { + model = new CalculatorModel(model.getVariable(), model.getOutput() / model.getVariable()); + } +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java new file mode 100644 index 000000000000..21aca2a54eed --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent.actions; + +/** Addition {@link CalculatorAction}. */ +public class AdditionCalculatorAction implements CalculatorAction { + /** Subclass tag. */ + public static final String ADDITION = "ADDITION"; + + /** Makes checking subclass type trivial. */ + @Override + public String tag() { + return ADDITION; + } +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/CalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/CalculatorAction.java new file mode 100644 index 000000000000..b9566dc53ff5 --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/CalculatorAction.java @@ -0,0 +1,36 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent.actions; + +/** Defines what outside interactions can be consumed by view model. */ +public interface CalculatorAction { + + /** + * Makes identifying action trivial. + * + * @return subclass tag. + */ + String tag(); +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java new file mode 100644 index 000000000000..28e2ad362cec --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent.actions; + +/** Division {@link CalculatorAction}. */ +public class DivisionCalculatorAction implements CalculatorAction { + /** Subclass tag. */ + public static final String DIVISION = "DIVISION"; + + /** Makes checking subclass type trivial. */ + @Override + public String tag() { + return DIVISION; + } +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java new file mode 100644 index 000000000000..9c5bcd044049 --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent.actions; + +/** Multiplication {@link CalculatorAction}. */ +public class MultiplicationCalculatorAction implements CalculatorAction { + /** Subclass tag. */ + public static final String MULTIPLICATION = "MULTIPLICATION"; + + /** Makes checking subclass type trivial. */ + @Override + public String tag() { + return MULTIPLICATION; + } +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java new file mode 100644 index 000000000000..ce438e22a5d1 --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent.actions; + +import lombok.Data; +import lombok.Getter; + +/** SetVariable {@link CalculatorAction}. */ +@Data +public final class SetVariableCalculatorAction implements CalculatorAction { + + /** Subclass tag. */ + public static final String SET_VARIABLE = "SET_VARIABLE"; + + /** Used by {@link com.iluwatar.model.view.intent.CalculatorViewModel}. */ + @Getter private final Double variable; + + /** Makes checking subclass type trivial. */ + @Override + public String tag() { + return SET_VARIABLE; + } +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java new file mode 100644 index 000000000000..4a20d32a1fe4 --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java @@ -0,0 +1,37 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent.actions; + +/** Subtraction {@link CalculatorAction}. */ +public class SubtractionCalculatorAction implements CalculatorAction { + /** Subclass tag. */ + public static final String SUBTRACTION = "SUBTRACTION"; + + /** Makes checking subclass type trivial. */ + @Override + public String tag() { + return SUBTRACTION; + } +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/package-info.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/package-info.java new file mode 100644 index 000000000000..062fc309dda2 --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/package-info.java @@ -0,0 +1,29 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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. + */ +/** + * Handle actions for {@link com.iluwatar.model.view.intent.CalculatorModel} defined by {@link + * com.iluwatar.model.view.intent.actions.CalculatorAction}. + */ +package com.iluwatar.model.view.intent.actions; diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/package-info.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/package-info.java new file mode 100644 index 000000000000..654eb228b704 --- /dev/null +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/package-info.java @@ -0,0 +1,26 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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. + */ +/** Define Model, View and ViewModel. Use them in {@link com.iluwatar.model.view.intent.App} */ +package com.iluwatar.model.view.intent; diff --git a/model-view-intent/src/test/java/com/iluwatar/model/view/intent/AppTest.java b/model-view-intent/src/test/java/com/iluwatar/model/view/intent/AppTest.java new file mode 100644 index 000000000000..b28ad3cabf31 --- /dev/null +++ b/model-view-intent/src/test/java/com/iluwatar/model/view/intent/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** Application test */ +class AppTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +} diff --git a/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java b/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java new file mode 100644 index 000000000000..492c965fe079 --- /dev/null +++ b/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java @@ -0,0 +1,112 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.intent; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.iluwatar.model.view.intent.actions.*; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class CalculatorViewModelTest { + + private CalculatorModel modelAfterExecutingActions(List actions) { + CalculatorViewModel viewModel = new CalculatorViewModel(); + for (CalculatorAction action : actions) { + viewModel.handleAction(action); + } + return viewModel.getCalculatorModel(); + } + + @Test + void testSetup() { + CalculatorModel model = modelAfterExecutingActions(new ArrayList<>()); + assertEquals(0, model.getVariable()); + assertEquals(0, model.getOutput()); + } + + @Test + void testSetVariable() { + List actions = List.of(new SetVariableCalculatorAction(10.0)); + CalculatorModel model = modelAfterExecutingActions(actions); + assertEquals(10.0, model.getVariable()); + assertEquals(0, model.getOutput()); + } + + @Test + void testAddition() { + List actions = + List.of( + new SetVariableCalculatorAction(2.0), + new AdditionCalculatorAction(), + new AdditionCalculatorAction(), + new SetVariableCalculatorAction(7.0), + new AdditionCalculatorAction()); + CalculatorModel model = modelAfterExecutingActions(actions); + assertEquals(7.0, model.getVariable()); + assertEquals(11.0, model.getOutput()); + } + + @Test + void testSubtraction() { + List actions = + List.of( + new SetVariableCalculatorAction(2.0), + new AdditionCalculatorAction(), + new AdditionCalculatorAction(), + new SubtractionCalculatorAction()); + CalculatorModel model = modelAfterExecutingActions(actions); + assertEquals(2.0, model.getVariable()); + assertEquals(2.0, model.getOutput()); + } + + @Test + void testMultiplication() { + List actions = + List.of( + new SetVariableCalculatorAction(2.0), + new AdditionCalculatorAction(), + new AdditionCalculatorAction(), + new MultiplicationCalculatorAction()); + CalculatorModel model = modelAfterExecutingActions(actions); + assertEquals(2.0, model.getVariable()); + assertEquals(8.0, model.getOutput()); + } + + @Test + void testDivision() { + List actions = + List.of( + new SetVariableCalculatorAction(2.0), + new AdditionCalculatorAction(), + new AdditionCalculatorAction(), + new SetVariableCalculatorAction(2.0), + new DivisionCalculatorAction()); + CalculatorModel model = modelAfterExecutingActions(actions); + assertEquals(2.0, model.getVariable()); + assertEquals(2.0, model.getOutput()); + } +} diff --git a/model-view-presenter/README.md b/model-view-presenter/README.md index a3b921ce4f04..58cafed55b43 100644 --- a/model-view-presenter/README.md +++ b/model-view-presenter/README.md @@ -1,27 +1,173 @@ --- -layout: pattern -title: Model-View-Presenter -folder: model-view-presenter -permalink: /patterns/model-view-presenter/ -categories: Presentation Tier -tags: - - Java - - Difficulty-Intermediate +title: "Model-View-Presenter Pattern in Java: Enhancing UI Logic Separation for Cleaner Code" +shortTitle: Model-View-Presenter (MVP) +description: "Discover the Model-View-Presenter (MVP) pattern in Java. Learn how it separates user interface, business logic, and data interaction to enhance testability and maintainability." +category: Architectural +language: en +tag: + - Architecture + - Client-server + - Decoupling + - Enterprise patterns + - Interface + - Presentation --- -## Intent -Apply a "Separation of Concerns" principle in a way that allows -developers to build and test user interfaces. +## Also known as -![alt text](./etc/model-view-presenter_1.png "Model-View-Presenter") +* MVP -## Applicability -Use the Model-View-Presenter in any of the following -situations +## Intent of Model-View-Presenter Design Pattern -* when you want to improve the "Separation of Concerns" principle in presentation logic -* when a user interface development and testing is necessary. +MVP aims to separate the user interface (UI) logic from the business logic and model in a software application, enabling easier testing and maintenance. -## Real world examples +## Detailed Explanation of Model-View-Presenter Pattern with Real-World Examples -* [MVP4J](https://github.com/amineoualialami/mvp4j) +Real-world example + +> Consider a real-world analogy of the Model-View-Presenter (MVP) pattern using a restaurant scenario: +> +> - **Model:** This is the kitchen in a restaurant, where all the cooking and preparation of dishes happens. It's responsible for managing the food ingredients, cooking processes, and ensuring that recipes are followed correctly. +> +> - **View:** This represents the dining area and the menu presented to the customers. It displays the available dishes, takes orders, and shows the final presentation of the food. However, it doesn't decide what's cooked or how it's prepared. +> +> - **Presenter:** Acting as the waiter, the presenter takes the customer's order (input) and communicates it to the kitchen (model). The waiter then brings the prepared food (output) back to the customer in the dining area (view). The waiter ensures that what the customer sees (the menu and food presentation) aligns with what the kitchen can provide, and also updates the view based on the kitchen's capabilities (e.g., out-of-stock items). +> +> In this analogy, the clear separation of roles allows the restaurant to operate efficiently: the kitchen focuses on food preparation, the dining area on customer interaction, and the waiter bridges the two, ensuring smooth operation and customer satisfaction. + +In plain words + +> The Model-View-Presenter (MVP) pattern separates the user interface, business logic, and data interaction in an application, with the presenter mediating between the view and the model to facilitate clear communication and updates. Java developers use MVP to improve application structure. + +Wikipedia says + +> Model–view–presenter (MVP) is a derivation of the model–view–controller (MVC) architectural pattern, and is used mostly for building user interfaces. In MVP, the presenter assumes the functionality of the "middle-man". In MVP, all presentation logic is pushed to the presenter. + +Architecture diagram + +![Model-View-Presenter Architecture Diagram](./etc/mvp-architecture-diagram.png) + + +## Programmatic Example of Model-View-Presenter Pattern in Java + +The Model-View-Presenter (MVP) design pattern is a derivative of the well-known Model-View-Controller (MVC) pattern. It aims to separate the application's logic (Model), GUIs (View), and the way that the user's actions update the application's logic (Presenter). This separation of concerns makes the application easier to manage, extend, and test. + +Let's break down the MVP pattern using the provided code: + +1. **Model**: The Model represents the application's logic. In our case, the `FileLoader` class is the Model. It's responsible for handling the file loading process. + +```java +@Getter +public class FileLoader implements Serializable { + //... + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public boolean fileExists() { + //... + } + + public String loadData() { + //... + } +} +``` + +2. **View**: The View is responsible for displaying the data provided by the Model. Here, the `FileSelectorView` interface and its implementation `FileSelectorJFrame` represent the View. They define how to display data and messages to the user. + +```java +public interface FileSelectorView { + //... + void setPresenter(FileSelectorPresenter presenter); + void open(); + void close(); + void showMessage(String message); + void displayData(String data); + String getFileName(); +} + +public class FileSelectorJFrame implements FileSelectorView { + //... + @Override + public void displayData(String data) { + this.dataDisplayed = true; + } +} +``` + +3. **Presenter**: The Presenter acts as a bridge between the Model and the View. It reacts to the user's actions and updates the View accordingly. In our example, the `FileSelectorPresenter` class is the Presenter. + +```java +public class FileSelectorPresenter implements Serializable { + //... + public void setLoader(FileLoader loader) { + this.loader = loader; + } + + public void start() { + view.setPresenter(this); + view.open(); + } + + public void fileNameChanged() { + loader.setFileName(view.getFileName()); + } + + public void confirmed() { + //... + } + + public void cancelled() { + view.close(); + } +} +``` + +Finally, we wire up the Presenter, the View, and the Model in the `App` class: + +```java +public class App { + public static void main(String[] args) { + var loader = new FileLoader(); + var frame = new FileSelectorJFrame(); + var presenter = new FileSelectorPresenter(frame); + presenter.setLoader(loader); + presenter.start(); + } +} +``` + +In this setup, the `App` class creates instances of the Model, View, and Presenter. It then connects these instances, forming the MVP triad. The Presenter is given a reference to the View, and the Model is set on the Presenter. Finally, the Presenter is started, which in turn opens the View. + +## When to Use the Model-View-Presenter Pattern in Java + +Use MVP in applications where a clear [separation of concerns](https://java-design-patterns.com/principles/#separation-of-concerns) is needed between the presentation layer and the underlying business logic. It's particularly useful in client-server applications and enterprise-level applications. + +## Real-World Applications of Model-View-Presenter Pattern in Java + +* Desktop applications like those built using Java Swing or JavaFX. +* Web applications with complex user interfaces and business logic. + +## Benefits and Trade-offs of Model-View-Presenter Pattern + +Benefits: + +* Enhances testability of UI logic by allowing the presenter to be tested separately from the view. +* Promotes a clean separation of concerns, making the application easier to manage and extend. +* Facilitates easier UI updates without affecting the business logic. + +Trade-offs: + +* Increases complexity with more classes and interfaces. +* Requires careful design to avoid over-coupling between the presenter and the view. + +## Related Java Design Patterns + +* [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): MVP is often considered a variant of MVC where the presenter takes over the controller's role in managing user input and updating the model. +* [Model-View-ViewModel (MVVM)](https://java-design-patterns.com/patterns/model-view-viewmodel/): Similar to MVP but adapted for frameworks like WPF or frameworks that support data binding, making the view update automatically when the model changes. + +## References and Credits + +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) +* [Pro JavaFX 8: A Definitive Guide to Building Desktop, Mobile, and Embedded Java Clients](https://amzn.to/4a8qcQ1) diff --git a/model-view-presenter/etc/data/test.txt b/model-view-presenter/etc/data/test.txt index 3f3607972b58..2f10a4d2c5c7 100644 --- a/model-view-presenter/etc/data/test.txt +++ b/model-view-presenter/etc/data/test.txt @@ -1,6 +1,8 @@ ==== + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + The MIT License - Copyright (c) 2014-2016 Ilkka Seppälä + Copyright © 2014-2022 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 diff --git a/model-view-presenter/etc/model-view-presenter.ucls b/model-view-presenter/etc/model-view-presenter.ucls index 70e905d3f537..0228d37626f3 100644 --- a/model-view-presenter/etc/model-view-presenter.ucls +++ b/model-view-presenter/etc/model-view-presenter.ucls @@ -1,9 +1,9 @@ - "-presenter" FileSelectorPresenter +FileSelectorStub --> "-presenter" FileSelectorPresenter +FileSelectorPresenter --> "-view" FileSelectorView +FileSelectorPresenter --> "-loader" FileLoader +FileSelectorJframe ..|> FileSelectorView +FileSelectorStub ..|> FileSelectorView +@enduml \ No newline at end of file diff --git a/model-view-presenter/etc/mvp-architecture-diagram.png b/model-view-presenter/etc/mvp-architecture-diagram.png new file mode 100644 index 000000000000..df324b0ab6b0 Binary files /dev/null and b/model-view-presenter/etc/mvp-architecture-diagram.png differ diff --git a/model-view-presenter/pom.xml b/model-view-presenter/pom.xml index d4db8a633e02..9dcd55f610e2 100644 --- a/model-view-presenter/pom.xml +++ b/model-view-presenter/pom.xml @@ -1,8 +1,10 @@ - + - + 4.0.0 com.iluwatar java-design-patterns - 1.20.0-SNAPSHOT + 1.26.0-SNAPSHOT model-view-presenter model-view-presenter http://maven.apache.org - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic org.junit.jupiter @@ -46,9 +50,28 @@ test - net.java.dev.swing-layout - swing-layout - 1.0.2 + net.java.dev.swing-layout + swing-layout + 1.0.2 + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.model.view.presenter.App + + + + + + + + diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java index 26f16bcec177..45f7725604b4 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -23,31 +25,29 @@ package com.iluwatar.model.view.presenter; /** - * - * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is called - * "The separation of concerns" principle. This is accomplished by separating the application's - * logic (Model), GUIs (View), and finally the way that the user's actions update the application's - * logic (Presenter). - *

    - * In the following example, The {@link FileLoader} class represents the app's logic, the - * {@link FileSelectorJFrame} is the GUI and the {@link FileSelectorPresenter} is responsible to - * respond to users' actions. - *

    - * Finally, please notice the wiring between the Presenter and the View and between the Presenter + * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is called "The + * separation of concerns" principle. This is accomplished by separating the application's logic + * (Model), GUIs (View), and finally the way that the user's actions update the application's logic + * (Presenter). + * + *

    In the following example, The {@link FileLoader} class represents the app's logic, the {@link + * FileSelectorJframe} is the GUI and the {@link FileSelectorPresenter} is responsible to respond to + * users' actions. + * + *

    Finally, please notice the wiring between the Presenter and the View and between the Presenter * and the Model. - * */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - FileLoader loader = new FileLoader(); - FileSelectorJFrame jFrame = new FileSelectorJFrame(); - FileSelectorPresenter presenter = new FileSelectorPresenter(jFrame); + var loader = new FileLoader(); + var frame = new FileSelectorJframe(); + var presenter = new FileSelectorPresenter(frame); presenter.setLoader(loader); presenter.start(); } 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 5952cf5f17bd..b2678c811a7e 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,52 +27,40 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; +import java.io.Serial; import java.io.Serializable; - +import java.util.stream.Collectors; +import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Every instance of this class represents the Model component in the Model-View-Presenter * architectural pattern. - *

    - * It is responsible for reading and loading the contents of a given file. + * + *

    It is responsible for reading and loading the contents of a given file. */ +@Getter public class FileLoader implements Serializable { - /** - * Generated serial version UID - */ - private static final long serialVersionUID = -4745803872902019069L; - + /** Generated serial version UID. */ + @Serial private static final long serialVersionUID = -4745803872902019069L; + private static final Logger LOGGER = LoggerFactory.getLogger(FileLoader.class); - /** - * Indicates if the file is loaded or not. - */ + /** Indicates if the file is loaded or not. */ private boolean loaded; - /** - * The name of the file that we want to load. - */ + /** The name of the file that we want to load. */ private String fileName; - /** - * Loads the data of the file specified. - */ + /** Loads the data of the file specified. */ public String loadData() { - String dataFileName = this.fileName; - try (BufferedReader br = new BufferedReader(new FileReader(new File(dataFileName)))) { - StringBuilder sb = new StringBuilder(); - String line; - - while ((line = br.readLine()) != null) { - sb.append(line).append('\n'); - } - + var dataFileName = this.fileName; + try (var br = new BufferedReader(new FileReader(dataFileName))) { + var result = br.lines().collect(Collectors.joining("\n")); this.loaded = true; - - return sb.toString(); + return result; } catch (Exception e) { LOGGER.error("File {} does not exist", dataFileName); } @@ -80,7 +70,7 @@ public String loadData() { /** * Sets the path of the file to be loaded, to the given value. - * + * * @param fileName The path of the file to be loaded. */ public void setFileName(String fileName) { @@ -88,23 +78,11 @@ public void setFileName(String fileName) { } /** - * @return fileName The path of the file to be loaded. - */ - public String getFileName() { - return this.fileName; - } - - /** + * Returns true if the given file exists. + * * @return True, if the file given exists, false otherwise. */ public boolean fileExists() { return new File(this.fileName).exists(); } - - /** - * @return True, if the file is loaded, false otherwise. - */ - public boolean isLoaded() { - return this.loaded; - } } diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java deleted file mode 100644 index b39db04a89a7..000000000000 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java +++ /dev/null @@ -1,218 +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.model.view.presenter; - -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; - -/** - * This class is the GUI implementation of the View component in the Model-View-Presenter pattern. - */ -public class FileSelectorJFrame extends JFrame implements FileSelectorView, ActionListener { - - /** - * Default serial version ID. - */ - private static final long serialVersionUID = 1L; - - /** - * The "OK" button for loading the file. - */ - private JButton ok; - - /** - * The cancel button. - */ - private JButton cancel; - - /** - * The information label. - */ - private JLabel info; - - /** - * The contents label. - */ - private JLabel contents; - - /** - * The text field for giving the name of the file that we want to open. - */ - private JTextField input; - - /** - * A text area that will keep the contents of the file opened. - */ - private JTextArea area; - - /** - * The panel that will hold our widgets. - */ - private JPanel panel; - - /** - * The Presenter component that the frame will interact with - */ - private FileSelectorPresenter presenter; - - /** - * The name of the file that we want to read it's contents. - */ - private String fileName; - - /** - * Constructor. - */ - public FileSelectorJFrame() { - super("File Loader"); - this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - this.setLayout(null); - this.setBounds(100, 100, 500, 200); - - /* - * Add the panel. - */ - this.panel = new JPanel(); - panel.setLayout(null); - this.add(panel); - panel.setBounds(0, 0, 500, 200); - panel.setBackground(Color.LIGHT_GRAY); - - /* - * Add the info label. - */ - this.info = new JLabel("File Name :"); - this.panel.add(info); - info.setBounds(30, 10, 100, 30); - - /* - * Add the contents label. - */ - this.contents = new JLabel("File contents :"); - this.panel.add(contents); - this.contents.setBounds(30, 100, 120, 30); - - /* - * Add the text field. - */ - this.input = new JTextField(100); - this.panel.add(input); - this.input.setBounds(150, 15, 200, 20); - - /* - * Add the text area. - */ - this.area = new JTextArea(100, 100); - JScrollPane pane = new JScrollPane(area); - pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - this.panel.add(pane); - this.area.setEditable(false); - pane.setBounds(150, 100, 250, 80); - - /* - * Add the OK button. - */ - this.ok = new JButton("OK"); - this.panel.add(ok); - this.ok.setBounds(250, 50, 100, 25); - this.ok.addActionListener(this); - - /* - * Add the cancel button. - */ - this.cancel = new JButton("Cancel"); - this.panel.add(this.cancel); - this.cancel.setBounds(380, 50, 100, 25); - this.cancel.addActionListener(this); - - this.presenter = null; - this.fileName = null; - } - - @Override - public void actionPerformed(ActionEvent e) { - if (this.ok.equals(e.getSource())) { - this.fileName = this.input.getText(); - presenter.fileNameChanged(); - presenter.confirmed(); - } else if (this.cancel.equals(e.getSource())) { - presenter.cancelled(); - } - } - - @Override - public void open() { - this.setVisible(true); - } - - @Override - public void close() { - this.dispose(); - } - - @Override - public boolean isOpened() { - return this.isVisible(); - } - - @Override - public void setPresenter(FileSelectorPresenter presenter) { - this.presenter = presenter; - } - - @Override - public FileSelectorPresenter getPresenter() { - return this.presenter; - } - - @Override - public void setFileName(String name) { - this.fileName = name; - } - - @Override - public String getFileName() { - return this.fileName; - } - - @Override - public void showMessage(String message) { - JOptionPane.showMessageDialog(null, message); - } - - @Override - public void displayData(String data) { - this.area.setText(data); - } -} diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJframe.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJframe.java new file mode 100644 index 000000000000..1680e5455a8f --- /dev/null +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJframe.java @@ -0,0 +1,192 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.presenter; + +import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; +import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; + +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.Serial; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; + +/** + * This class is the GUI implementation of the View component in the Model-View-Presenter pattern. + */ +public class FileSelectorJframe extends JFrame implements FileSelectorView, ActionListener { + + /** Default serial version ID. */ + @Serial private static final long serialVersionUID = 1L; + + /** The "OK" button for loading the file. */ + private final JButton ok; + + /** The cancel button. */ + private final JButton cancel; + + /** The text field for giving the name of the file that we want to open. */ + private final JTextField input; + + /** A text area that will keep the contents of the file opened. */ + private final JTextArea area; + + /** The Presenter component that the frame will interact with. */ + private FileSelectorPresenter presenter; + + /** The name of the file that we want to read it's contents. */ + private String fileName; + + /** Constructor. */ + public FileSelectorJframe() { + super("File Loader"); + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + this.setLayout(null); + this.setBounds(100, 100, 500, 200); + + /* + * Add the panel. + */ + var panel = new JPanel(); + panel.setLayout(null); + this.add(panel); + panel.setBounds(0, 0, 500, 200); + panel.setBackground(Color.LIGHT_GRAY); + + /* + * Add the info label. + */ + var info = new JLabel("File Name :"); + panel.add(info); + info.setBounds(30, 10, 100, 30); + + /* + * Add the contents label. + */ + var contents = new JLabel("File contents :"); + panel.add(contents); + contents.setBounds(30, 100, 120, 30); + + /* + * Add the text field. + */ + this.input = new JTextField(100); + panel.add(input); + this.input.setBounds(150, 15, 200, 20); + + /* + * Add the text area. + */ + this.area = new JTextArea(100, 100); + var pane = new JScrollPane(area); + pane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED); + pane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_AS_NEEDED); + panel.add(pane); + this.area.setEditable(false); + pane.setBounds(150, 100, 250, 80); + + /* + * Add the OK button. + */ + this.ok = new JButton("OK"); + panel.add(ok); + this.ok.setBounds(250, 50, 100, 25); + this.ok.addActionListener(this); + + /* + * Add the cancel button. + */ + this.cancel = new JButton("Cancel"); + panel.add(this.cancel); + this.cancel.setBounds(380, 50, 100, 25); + this.cancel.addActionListener(this); + + this.presenter = null; + this.fileName = null; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (this.ok.equals(e.getSource())) { + this.fileName = this.input.getText(); + presenter.fileNameChanged(); + presenter.confirmed(); + } else if (this.cancel.equals(e.getSource())) { + presenter.cancelled(); + } + } + + @Override + public void open() { + this.setVisible(true); + } + + @Override + public void close() { + this.dispose(); + } + + @Override + public boolean isOpened() { + return this.isVisible(); + } + + @Override + public void setPresenter(FileSelectorPresenter presenter) { + this.presenter = presenter; + } + + @Override + public FileSelectorPresenter getPresenter() { + return this.presenter; + } + + @Override + public void setFileName(String name) { + this.fileName = name; + } + + @Override + public String getFileName() { + return this.fileName; + } + + @Override + public void showMessage(String message) { + JOptionPane.showMessageDialog(null, message); + } + + @Override + public void displayData(String data) { + this.area.setText(data); + } +} 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 233b1dcf73c5..3c15408bddcf 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,34 +24,29 @@ */ package com.iluwatar.model.view.presenter; +import java.io.Serial; 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. + * + *

    It is responsible for reacting to the user's actions and update the View component. */ public class FileSelectorPresenter implements Serializable { - /** - * Generated serial version UID - */ - private static final long serialVersionUID = 1210314339075855074L; + /** Generated serial version UID. */ + @Serial private static final long serialVersionUID = 1210314339075855074L; - /** - * The View component that the presenter interacts with. - */ - private FileSelectorView view; + /** The View component that the presenter interacts with. */ + private final FileSelectorView view; - /** - * The Model component that the presenter interacts with. - */ + /** The Model component that the presenter interacts with. */ private FileLoader loader; /** - * Constructor - * + * Constructor. + * * @param view The view component that the presenter will interact with. */ public FileSelectorPresenter(FileSelectorView view) { @@ -58,48 +55,40 @@ public FileSelectorPresenter(FileSelectorView view) { /** * Sets the {@link FileLoader} object, to the value given as parameter. - * + * * @param loader The new {@link FileLoader} object(the Model component). */ public void setLoader(FileLoader loader) { this.loader = loader; } - /** - * Starts the presenter. - */ + /** Starts the presenter. */ public void start() { view.setPresenter(this); view.open(); } - /** - * An "event" that fires when the name of the file to be loaded changes. - */ + /** An "event" that fires when the name of the file to be loaded changes. */ public void fileNameChanged() { loader.setFileName(view.getFileName()); } - /** - * Ok button handler - */ + /** Ok button handler. */ public void confirmed() { - if (loader.getFileName() == null || loader.getFileName().equals("")) { + if (loader.getFileName() == null || loader.getFileName().isEmpty()) { view.showMessage("Please give the name of the file first!"); return; } if (loader.fileExists()) { - String data = loader.loadData(); + var data = loader.loadData(); view.displayData(data); } else { view.showMessage("The file specified does not exist."); } } - /** - * Cancels the file loading process. - */ + /** Cancels the file loading process. */ public void cancelled() { view.close(); } diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java index e4510eabee10..3eda80eb27c4 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -25,43 +27,31 @@ /** * Every instance of this class represents the Stub component in the Model-View-Presenter * architectural pattern. - *

    - * The stub implements the View interface and it is useful when we want the test the reaction to + * + *

    The stub implements the View interface and it is useful when we want the test the reaction to * user events, such as mouse clicks. - *

    - * Since we can not test the GUI directly, the MVP pattern provides this functionality through the - * View's dummy implementation, the Stub. + * + *

    Since we can not test the GUI directly, the MVP pattern provides this functionality through + * the View's dummy implementation, the Stub. */ public class FileSelectorStub implements FileSelectorView { - /** - * Indicates whether or not the view is opened. - */ + /** Indicates whether or not the view is opened. */ private boolean opened; - /** - * The presenter Component. - */ + /** The presenter Component. */ private FileSelectorPresenter presenter; - /** - * The current name of the file. - */ + /** The current name of the file. */ private String name; - /** - * Indicates the number of messages that were "displayed" to the user. - */ + /** Indicates the number of messages that were "displayed" to the user. */ private int numOfMessageSent; - /** - * Indicates if the data of the file where displayed or not. - */ + /** Indicates if the data of the file where displayed or not. */ private boolean dataDisplayed; - /** - * Constructor - */ + /** Constructor. */ public FileSelectorStub() { this.opened = false; this.presenter = null; @@ -115,14 +105,14 @@ public void displayData(String data) { this.dataDisplayed = true; } - /** - * Returns the number of messages that were displayed to the user. - */ + /** Returns the number of messages that were displayed to the user. */ public int getMessagesSent() { return this.numOfMessageSent; } /** + * Returns true, if the data were displayed. + * * @return True if the data where displayed, false otherwise. */ public boolean dataDisplayed() { 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 e6ab93f66bed..9a0b86a0b61a 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 @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -30,55 +32,57 @@ */ public interface FileSelectorView extends Serializable { - /** - * Opens the view. - */ + /** Opens the view. */ void open(); - /** - * Closes the view. - */ + /** Closes the view. */ void close(); /** + * Returns true if view is opened. + * * @return True, if the view is opened, false otherwise. */ boolean isOpened(); /** * Sets the presenter component, to the one given as parameter. - * + * * @param presenter The new presenter component. */ void setPresenter(FileSelectorPresenter presenter); /** + * Gets presenter component. + * * @return The presenter Component. */ FileSelectorPresenter getPresenter(); /** * Sets the file's name, to the value given as parameter. - * + * * @param name The new name of the file. */ void setFileName(String name); /** + * Gets the name of file. + * * @return The name of the file. */ String getFileName(); /** * Displays a message to the users. - * + * * @param message The message to be displayed. */ void showMessage(String message); /** * Displays the data to the view. - * + * * @param data The data to be written. */ void displayData(String data); diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java index c1b33cb30479..91c7e8dbda7b 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,19 +24,15 @@ */ package com.iluwatar.model.view.presenter; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; -/** - * - * Application test - * - */ -public class AppTest { +/** Application test */ +class AppTest { @Test - public void test() { - String[] args = {}; - App.main(args); + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java index 56bc3b8bdf20..b12877d35b63 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,22 +24,17 @@ */ package com.iluwatar.model.view.presenter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertNull; -/** - * Date: 12/21/15 - 12:12 PM - * - * @author Jeroen Meulemeester - */ -public class FileLoaderTest { +import org.junit.jupiter.api.Test; + +/** FileLoaderTest */ +class FileLoaderTest { @Test - public void testLoadData() throws Exception { - final FileLoader fileLoader = new FileLoader(); + void testLoadData() { + final var fileLoader = new FileLoader(); fileLoader.setFileName("non-existing-file"); assertNull(fileLoader.loadData()); } - -} \ No newline at end of file +} diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorJframeTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorJframeTest.java new file mode 100644 index 000000000000..47b10737db52 --- /dev/null +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorJframeTest.java @@ -0,0 +1,45 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 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.model.view.presenter; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import java.awt.event.ActionEvent; +import org.junit.jupiter.api.Test; + +/** FileSelectorJframeTest */ +class FileSelectorJframeTest { + + /** Tests if the jframe action event is triggered without any exception. */ + @Test + void testActionEvent() { + assertDoesNotThrow( + () -> { + FileSelectorJframe jFrame = new FileSelectorJframe(); + ActionEvent action = new ActionEvent("dummy", 1, "dummy"); + jFrame.actionPerformed(action); + }); + } +} diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java index ff68cef6e3be..dca646c20b87 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java @@ -1,6 +1,8 @@ -/** +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * Copyright © 2014-2022 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 @@ -22,63 +24,51 @@ */ package com.iluwatar.model.view.presenter; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + /** * This test case is responsible for testing our application by taking advantage of the * Model-View-Controller architectural pattern. */ -public class FileSelectorPresenterTest { +class FileSelectorPresenterTest { - /** - * The Presenter component. - */ + /** The Presenter component. */ private FileSelectorPresenter presenter; - /** - * The View component, implemented this time as a Stub!!! - */ + /** The View component, implemented this time as a Stub!!! */ private FileSelectorStub stub; - /** - * The Model component. - */ + /** The Model component. */ private FileLoader loader; - /** - * Initializes the components of the test case. - */ + /** Initializes the components of the test case. */ @BeforeEach - public void setUp() { + void setUp() { this.stub = new FileSelectorStub(); this.loader = new FileLoader(); presenter = new FileSelectorPresenter(this.stub); presenter.setLoader(loader); } - /** - * Tests if the Presenter was successfully connected with the View. - */ + /** Tests if the Presenter was successfully connected with the View. */ @Test - public void wiring() { + void wiring() { presenter.start(); assertNotNull(stub.getPresenter()); assertTrue(stub.isOpened()); } - /** - * Tests if the name of the file changes. - */ + /** Tests if the name of the file changes. */ @Test - public void updateFileNameToLoader() { - String expectedFile = "Stamatis"; + void updateFileNameToLoader() { + var expectedFile = "Stamatis"; stub.setFileName(expectedFile); presenter.start(); @@ -92,7 +82,7 @@ public void updateFileNameToLoader() { * empty string. */ @Test - public void fileConfirmationWhenNameIsNull() { + void fileConfirmationWhenNameIsNull() { stub.setFileName(null); presenter.start(); @@ -103,11 +93,9 @@ public void fileConfirmationWhenNameIsNull() { assertEquals(1, stub.getMessagesSent()); } - /** - * Tests if we receive a confirmation when we attempt to open a file that it doesn't exist. - */ + /** Tests if we receive a confirmation when we attempt to open a file that it doesn't exist. */ @Test - public void fileConfirmationWhenFileDoesNotExist() { + void fileConfirmationWhenFileDoesNotExist() { stub.setFileName("RandomName.txt"); presenter.start(); @@ -118,11 +106,9 @@ public void fileConfirmationWhenFileDoesNotExist() { assertEquals(1, stub.getMessagesSent()); } - /** - * Tests if we can open the file, when it exists. - */ + /** Tests if we can open the file, when it exists. */ @Test - public void fileConfirmationWhenFileExists() { + void fileConfirmationWhenFileExists() { stub.setFileName("etc/data/test.txt"); presenter.start(); presenter.fileNameChanged(); @@ -132,14 +118,23 @@ public void fileConfirmationWhenFileExists() { assertTrue(stub.dataDisplayed()); } - /** - * Tests if the view closes after cancellation. - */ + /** Tests if the view closes after cancellation. */ @Test - public void cancellation() { + void cancellation() { presenter.start(); presenter.cancelled(); assertFalse(stub.isOpened()); } + + @Test + void testNullFile() { + stub.setFileName(null); + presenter.start(); + presenter.fileNameChanged(); + presenter.confirmed(); + + assertFalse(loader.isLoaded()); + assertFalse(stub.dataDisplayed()); + } } diff --git a/model-view-viewmodel/README.md b/model-view-viewmodel/README.md new file mode 100644 index 000000000000..46597bedd9d8 --- /dev/null +++ b/model-view-viewmodel/README.md @@ -0,0 +1,169 @@ +--- +title: "Model-View-ViewModel Pattern in Java: Separating UI and Logic for Cleaner Code" +shortTitle: Model-View-ViewModel +description: "Learn about the Model-View-ViewModel (MVVM) design pattern in Java. Discover its benefits, real-world applications, and how it improves UI and business logic separation for scalable and maintainable code." +category: Architectural +language: en +tag: + - Architecture + - Data binding + - Decoupling + - Presentation + - Scalability +--- + +## Also known as + +* MVVM + +## Intent of Model-View-ViewModel Design Pattern + +The intent of the Model-View-ViewModel (MVVM) pattern in Java is to provide a clear [separation of concerns](https://java-design-patterns.com/principles/#separation-of-concerns) between the UI logic, the presentation logic, and the business logic by dividing the application into three interconnected components: Model, View, and ViewModel. + +## Detailed Explanation of Model-View-ViewModel Pattern with Real-World Examples + +Real-world example + +> Consider a real-world analogous example of the MVVM pattern similar to organizing a cooking show. In this scenario: +> +> - **Model:** Represents the recipe itself, which includes the ingredients and the steps needed to cook the dish. The model is purely about the data and rules for preparing the dish but does not concern itself with how this information is presented to the audience. +> +> - **View:** Is akin to the kitchen set where the cooking show is filmed, including all the visual elements like the layout of the kitchen, the placement of ingredients, and the cookware. The view is responsible for the visual presentation and how the audience sees the cooking process. +> +> - **ViewModel:** Acts like the script for the cooking show, where it interprets the recipe (model) and organizes the flow of the show. It tells the chef (view) what to display next, when to add ingredients, and how to respond to changes like substituting an ingredient. The ViewModel bridges the gap between the technical details of the recipe and the chef's presentation, ensuring the audience understands each step without delving into the complexities of the recipe itself. +> +> In this example, the ViewModel allows the chef to focus on cooking and interacting with the audience, while the underlying recipe remains unchanged, promoting a clear separation of concerns. + +In plain words + +> The MVVM design pattern separates an application into three distinct components: the Model, which holds the data and business logic; the View, which displays the user interface; and the ViewModel, which acts as an intermediary to bind data from the Model to the View. + +Wikipedia says + +> Model–view–viewmodel (MVVM) is a software architectural pattern that facilitates the separation of the development of the graphical user interface (the view) – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the model) so that the view is not dependent on any specific model platform. + +Architecture diagram + +![Model-View-ViewModel Architecture Diagram](./etc/mvvm-architecture-diagram.png) + + +## Programmatic Example of Model-View-ViewModel Pattern in Java + +ViewModel will hold the business logic and expose the data from model to View. + +```java +public class BookViewModel { + @WireVariable + private List bookList; + private Book selectedBook; + private BookService bookService = new BookServiceImpl(); + + public Book getSelectedBook() { + return selectedBook; + } + + @NotifyChange("selectedBook") + public void setSelectedBook(Book selectedBook) { + this.selectedBook = selectedBook; + } + + public List getBookList() { + return bookService.load(); + } + + /** Deleting a book. + */ + @Command + @NotifyChange({"selectedBook","bookList"}) + public void deleteBook() { + if (selectedBook != null) { + getBookList().remove(selectedBook); + selectedBook = null; + } +} +``` + +View will have no logic, only UI elements. + +```xml + + + + + + + + + + + + +