[{"data":1,"prerenderedAt":931},["ShallowReactive",2],{"i-simple-icons:github":3,"i-simple-icons:x":8,"i-brand:linkedin":10,"i-simple-icons:medium":14,"i-lucide:mail":16,"i-lucide:sun":18,"pattern:\u002Flearn\u002Fdesign-patterns\u002Fstrategy":20,"pattern-group:\u002Flearn\u002Fdesign-patterns\u002Fstrategy":872,"i-lucide:lightbulb":909,"i-lucide:workflow":911,"i-lucide:link":913,"i-lucide:square-terminal":915,"i-lucide:list-ordered":917,"i-lucide:bell":919,"i-lucide:toggle-left":921,"i-lucide:shuffle":923,"i-lucide:layout-template":925,"i-lucide:footprints":927,"i-lucide:copy":929},{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":7},0,24,false,"\u003Cpath fill=\"currentColor\" d=\"M12 .297c-6.63 0-12 5.373-12 12c0 5.303 3.438 9.8 8.205 11.385c.6.113.82-.258.82-.577c0-.285-.01-1.04-.015-2.04c-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729c1.205.084 1.838 1.236 1.838 1.236c1.07 1.835 2.809 1.305 3.495.998c.108-.776.417-1.305.76-1.605c-2.665-.3-5.466-1.332-5.466-5.93c0-1.31.465-2.38 1.235-3.22c-.135-.303-.54-1.523.105-3.176c0 0 1.005-.322 3.3 1.23c.96-.267 1.98-.399 3-.405c1.02.006 2.04.138 3 .405c2.28-1.552 3.285-1.23 3.285-1.23c.645 1.653.24 2.873.12 3.176c.765.84 1.23 1.91 1.23 3.22c0 4.61-2.805 5.625-5.475 5.92c.42.36.81 1.096.81 2.22c0 1.606-.015 2.896-.015 3.286c0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":9},"\u003Cpath fill=\"currentColor\" d=\"M14.234 10.162L22.977 0h-2.072l-7.591 8.824L7.251 0H.258l9.168 13.343L.258 24H2.33l8.016-9.318L16.749 24h6.993zm-2.837 3.299l-.929-1.329L3.076 1.56h3.182l5.965 8.532l.929 1.329l7.754 11.09h-3.182z\"\u002F>",{"left":4,"top":11,"width":12,"height":12,"rotate":4,"vFlip":6,"hFlip":6,"body":13},32,448,"\u003Cpath fill=\"currentColor\" d=\"M416 32L31.9 32C14.3 32 0 46.5 0 64.3L0 447.7C0 465.5 14.3 480 31.9 480L416 480c17.6 0 32-14.5 32-32.3l0-383.4C448 46.5 433.6 32 416 32zM135.4 416l-66.4 0 0-213.8 66.5 0 0 213.8-.1 0zM102.2 96a38.5 38.5 0 1 1 0 77 38.5 38.5 0 1 1 0-77zM384.3 416l-66.4 0 0-104c0-24.8-.5-56.7-34.5-56.7-34.6 0-39.9 27-39.9 54.9l0 105.8-66.4 0 0-213.8 63.7 0 0 29.2 .9 0c8.9-16.8 30.6-34.5 62.9-34.5 67.2 0 79.7 44.3 79.7 101.9l0 117.2z\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":15},"\u003Cpath fill=\"currentColor\" d=\"M4.21 0A4.2 4.2 0 0 0 0 4.21v15.58A4.2 4.2 0 0 0 4.21 24h15.58A4.2 4.2 0 0 0 24 19.79v-1.093a5 5 0 0 1-.422.02c-2.577 0-4.027-2.146-4.09-4.832a8 8 0 0 1 .022-.708c.093-1.186.475-2.241 1.105-3.022a3.9 3.9 0 0 1 1.395-1.1c.468-.237 1.127-.367 1.664-.367h.023q.151 0 .303.01V4.211A4.2 4.2 0 0 0 19.79 0Zm.198 5.583h4.165l3.588 8.435l3.59-8.435h3.864v.146l-.019.004c-.705.16-1.063.397-1.063 1.254h-.003l.003 10.274c.06.676.424.885 1.063 1.03l.02.004v.145h-4.923v-.145l.019-.005c.639-.144.994-.353 1.054-1.03V7.267l-4.745 11.15h-.261L6.15 7.569v9.445c0 .857.358 1.094 1.063 1.253l.02.004v.147H4.405v-.147l.019-.004c.705-.16 1.065-.397 1.065-1.253V6.987c0-.857-.358-1.094-1.064-1.254l-.018-.004zm19.25 3.668c-1.086.023-1.733 1.323-1.813 3.124H24V9.298a1.4 1.4 0 0 0-.342-.047m-1.862 3.632c-.1 1.756.86 3.239 2.204 3.634v-3.634z\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":17},"\u003Cg fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\">\u003Cpath d=\"m22 7l-8.991 5.727a2 2 0 0 1-2.009 0L2 7\"\u002F>\u003Crect width=\"20\" height=\"16\" x=\"2\" y=\"4\" rx=\"2\"\u002F>\u003C\u002Fg>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":19},"\u003Cg fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\">\u003Ccircle cx=\"12\" cy=\"12\" r=\"4\"\u002F>\u003Cpath d=\"M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32l1.41 1.41M2 12h2m16 0h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41\"\u002F>\u003C\u002Fg>",{"id":21,"title":22,"body":23,"description":858,"example":859,"extension":860,"group":861,"icon":862,"meta":863,"navigation":273,"order":314,"path":864,"rawbody":865,"seo":866,"sitemap":867,"source":868,"stem":869,"summary":870,"__hash__":871},"patterns\u002Flearn\u002Fdesign-patterns\u002Fstrategy.md","Strategy",{"type":24,"value":25,"toc":848},"minimark",[26,31,44,47,50,54,73,77,82,93,97,111,115,122,183,187,246,354,435,669,830,836,844],[27,28,30],"h2",{"id":29},"the-idea","The idea",[32,33,34,35,39,40,43],"p",{},"There is often more than one way to do the same task. Logs can go to a file, the console or a database. A price can be worked out with or without a discount. If one class holds all the options behind an ",[36,37,38],"code",{},"if"," or a ",[36,41,42],{},"switch",", it grows with every new option, and changing one risks breaking the others.",[32,45,46],{},"The Strategy pattern puts each option, each strategy, in its own class behind a shared interface. The class that needs the work done, the context, holds a reference to a strategy and calls it through that interface. It doesn't know which strategy it has.",[32,48,49],{},"You pass a strategy in when you create the context, and can swap it later. A new option means a new class, not an edit to the context.",[27,51,53],{"id":52},"when-to-use-it","When to use it",[55,56,57,61,67,70],"ul",{},[58,59,60],"li",{},"You have several ways to do the same task and want to choose between them at runtime.",[58,62,63,64,66],{},"A class has a large ",[36,65,42],{}," that picks between versions of one algorithm.",[58,68,69],{},"You want to keep the details of an algorithm, and the data it uses, out of the class that uses it.",[58,71,72],{},"You want to test each version of the algorithm on its own.",[27,74,76],{"id":75},"pros-and-cons","Pros and cons",[78,79,81],"h3",{"id":80},"pros","Pros",[55,83,84,87,90],{},[58,85,86],{},"It is flexible and easy to extend: a new behaviour is a new class.",[58,88,89],{},"You can pick the right algorithm for the current situation, and change it at runtime.",[58,91,92],{},"It replaces conditionals with composition, so the context stays small.",[78,94,96],{"id":95},"cons","Cons",[55,98,99,102,105],{},[58,100,101],{},"It adds classes to the system: one for each strategy.",[58,103,104],{},"Clients must know that the strategies exist and choose between them.",[58,106,107,108,110],{},"If there are only two options and they rarely change, an ",[36,109,38],{}," is simpler.",[27,112,114],{"id":113},"the-example","The example",[32,116,117,118,121],{},"The example is a logger. The same ",[36,119,120],{},"Log"," object can write to a file or to the console, and the demo switches between the two while the program runs.",[55,123,124,137,154,175],{},[58,125,126,132,133,136],{},[127,128,129],"strong",{},[36,130,131],{},"Logger",": the strategy interface, with one ",[36,134,135],{},"log(message)"," method.",[58,138,139,144,145,150,151,153],{},[127,140,141],{},[36,142,143],{},"FileLogger"," and ",[127,146,147],{},[36,148,149],{},"ConsoleLogger",": concrete strategies. Both print to the console, with a prefix that shows where the message would go. A comment in ",[36,152,143],{}," marks where writing to a file belongs.",[58,155,156,160,161,163,164,144,167,170,171,174],{},[127,157,158],{},[36,159,120],{},": the context. It holds a ",[36,162,131],{},", offers ",[36,165,166],{},"info()",[36,168,169],{},"error()",", and adds the level to the message before passing it to the strategy. ",[36,172,173],{},"setLogger()"," swaps the strategy.",[58,176,177,182],{},[127,178,179],{},[36,180,181],{},"Demo",": logs two messages with the file logger, swaps in the console logger, and logs two more.",[27,184,186],{"id":185},"the-code","The code",[188,189,195],"pre",{"className":190,"code":191,"filename":192,"language":193,"meta":194,"style":194},"language-java shiki shiki-themes haytham-dark haytham-light","public interface Logger {\n    void log(String message);\n}\n","Logger.java","java","",[36,196,197,217,240],{"__ignoreMap":194},[198,199,202,206,209,213],"span",{"class":200,"line":201},"line",1,[198,203,205],{"class":204},"sVsk0","public",[198,207,208],{"class":204}," interface",[198,210,212],{"class":211},"sNwy7"," Logger",[198,214,216],{"class":215},"sVG6I"," {\n",[198,218,220,223,227,230,233,237],{"class":200,"line":219},2,[198,221,222],{"class":204},"    void",[198,224,226],{"class":225},"sVz7n"," log",[198,228,229],{"class":215},"(",[198,231,232],{"class":204},"String",[198,234,236],{"class":235},"sWFPS"," message",[198,238,239],{"class":215},");\n",[198,241,243],{"class":200,"line":242},3,[198,244,245],{"class":215},"}\n",[188,247,250],{"className":190,"code":248,"filename":249,"language":193,"meta":194,"style":194},"public class FileLogger implements Logger {\n\n    @Override\n    public void log(String message) {\n        \u002F\u002F Your implementation for logging to file.\n        System.out.println(\"[file]:\" + message);\n    }\n}\n","FileLogger.java",[36,251,252,269,275,283,305,312,343,349],{"__ignoreMap":194},[198,253,254,256,259,262,265,267],{"class":200,"line":201},[198,255,205],{"class":204},[198,257,258],{"class":204}," class",[198,260,261],{"class":211}," FileLogger",[198,263,264],{"class":204}," implements",[198,266,212],{"class":211},[198,268,216],{"class":215},[198,270,271],{"class":200,"line":219},[198,272,274],{"emptyLinePlaceholder":273},true,"\n",[198,276,277,280],{"class":200,"line":242},[198,278,279],{"class":215},"    @",[198,281,282],{"class":204},"Override\n",[198,284,286,289,292,294,296,298,300,303],{"class":200,"line":285},4,[198,287,288],{"class":204},"    public",[198,290,291],{"class":204}," void",[198,293,226],{"class":225},[198,295,229],{"class":215},[198,297,232],{"class":204},[198,299,236],{"class":235},[198,301,302],{"class":215},")",[198,304,216],{"class":215},[198,306,308],{"class":200,"line":307},5,[198,309,311],{"class":310},"sFjNZ","        \u002F\u002F Your implementation for logging to file.\n",[198,313,315,318,321,325,327,330,332,336,339,341],{"class":200,"line":314},6,[198,316,317],{"class":235},"        System",[198,319,320],{"class":215},".",[198,322,324],{"class":323},"s4Awn","out",[198,326,320],{"class":215},[198,328,329],{"class":225},"println",[198,331,229],{"class":215},[198,333,335],{"class":334},"sUOzB","\"[file]:\"",[198,337,338],{"class":215}," +",[198,340,236],{"class":235},[198,342,239],{"class":215},[198,344,346],{"class":200,"line":345},7,[198,347,348],{"class":215},"    }\n",[198,350,352],{"class":200,"line":351},8,[198,353,245],{"class":215},[188,355,358],{"className":190,"code":356,"filename":357,"language":193,"meta":194,"style":194},"public class ConsoleLogger implements Logger {\n    @Override\n    public void log(String message) {\n        \u002F\u002F Your implementation for logging to console.\n        System.out.println(\"[console]:\" + message);\n    }\n}\n","ConsoleLogger.java",[36,359,360,375,381,399,404,427,431],{"__ignoreMap":194},[198,361,362,364,366,369,371,373],{"class":200,"line":201},[198,363,205],{"class":204},[198,365,258],{"class":204},[198,367,368],{"class":211}," ConsoleLogger",[198,370,264],{"class":204},[198,372,212],{"class":211},[198,374,216],{"class":215},[198,376,377,379],{"class":200,"line":219},[198,378,279],{"class":215},[198,380,282],{"class":204},[198,382,383,385,387,389,391,393,395,397],{"class":200,"line":242},[198,384,288],{"class":204},[198,386,291],{"class":204},[198,388,226],{"class":225},[198,390,229],{"class":215},[198,392,232],{"class":204},[198,394,236],{"class":235},[198,396,302],{"class":215},[198,398,216],{"class":215},[198,400,401],{"class":200,"line":285},[198,402,403],{"class":310},"        \u002F\u002F Your implementation for logging to console.\n",[198,405,406,408,410,412,414,416,418,421,423,425],{"class":200,"line":307},[198,407,317],{"class":235},[198,409,320],{"class":215},[198,411,324],{"class":323},[198,413,320],{"class":215},[198,415,329],{"class":225},[198,417,229],{"class":215},[198,419,420],{"class":334},"\"[console]:\"",[198,422,338],{"class":215},[198,424,236],{"class":235},[198,426,239],{"class":215},[198,428,429],{"class":200,"line":314},[198,430,348],{"class":215},[198,432,433],{"class":200,"line":345},[198,434,245],{"class":215},[188,436,439],{"className":190,"code":437,"filename":438,"language":193,"meta":194,"style":194},"public class Log {\n\n    private Logger logger;\n\n    public Log(Logger logger) {\n        this.logger = logger;\n    }\n\n    public void setLogger(Logger logger) {\n        this.logger = logger;\n    }\n\n    public void info(String message) {\n        this.logger.log(\"[info]:\" + message);\n    }\n\n    public void error(String message) {\n        this.logger.log(\"[error]:\" + message);\n    }\n}\n","Log.java",[36,440,441,452,456,469,473,489,507,511,515,535,550,555,560,580,605,610,615,635,659,664],{"__ignoreMap":194},[198,442,443,445,447,450],{"class":200,"line":201},[198,444,205],{"class":204},[198,446,258],{"class":204},[198,448,449],{"class":211}," Log",[198,451,216],{"class":215},[198,453,454],{"class":200,"line":219},[198,455,274],{"emptyLinePlaceholder":273},[198,457,458,461,463,466],{"class":200,"line":242},[198,459,460],{"class":204},"    private",[198,462,212],{"class":204},[198,464,465],{"class":235}," logger",[198,467,468],{"class":215},";\n",[198,470,471],{"class":200,"line":285},[198,472,274],{"emptyLinePlaceholder":273},[198,474,475,477,479,481,483,485,487],{"class":200,"line":307},[198,476,288],{"class":204},[198,478,449],{"class":225},[198,480,229],{"class":215},[198,482,131],{"class":204},[198,484,465],{"class":235},[198,486,302],{"class":215},[198,488,216],{"class":215},[198,490,491,495,497,500,503,505],{"class":200,"line":314},[198,492,494],{"class":493},"sheII","        this",[198,496,320],{"class":215},[198,498,499],{"class":323},"logger",[198,501,502],{"class":215}," =",[198,504,465],{"class":235},[198,506,468],{"class":215},[198,508,509],{"class":200,"line":345},[198,510,348],{"class":215},[198,512,513],{"class":200,"line":351},[198,514,274],{"emptyLinePlaceholder":273},[198,516,518,520,522,525,527,529,531,533],{"class":200,"line":517},9,[198,519,288],{"class":204},[198,521,291],{"class":204},[198,523,524],{"class":225}," setLogger",[198,526,229],{"class":215},[198,528,131],{"class":204},[198,530,465],{"class":235},[198,532,302],{"class":215},[198,534,216],{"class":215},[198,536,538,540,542,544,546,548],{"class":200,"line":537},10,[198,539,494],{"class":493},[198,541,320],{"class":215},[198,543,499],{"class":323},[198,545,502],{"class":215},[198,547,465],{"class":235},[198,549,468],{"class":215},[198,551,553],{"class":200,"line":552},11,[198,554,348],{"class":215},[198,556,558],{"class":200,"line":557},12,[198,559,274],{"emptyLinePlaceholder":273},[198,561,563,565,567,570,572,574,576,578],{"class":200,"line":562},13,[198,564,288],{"class":204},[198,566,291],{"class":204},[198,568,569],{"class":225}," info",[198,571,229],{"class":215},[198,573,232],{"class":204},[198,575,236],{"class":235},[198,577,302],{"class":215},[198,579,216],{"class":215},[198,581,583,585,587,589,591,594,596,599,601,603],{"class":200,"line":582},14,[198,584,494],{"class":493},[198,586,320],{"class":215},[198,588,499],{"class":323},[198,590,320],{"class":215},[198,592,593],{"class":225},"log",[198,595,229],{"class":215},[198,597,598],{"class":334},"\"[info]:\"",[198,600,338],{"class":215},[198,602,236],{"class":235},[198,604,239],{"class":215},[198,606,608],{"class":200,"line":607},15,[198,609,348],{"class":215},[198,611,613],{"class":200,"line":612},16,[198,614,274],{"emptyLinePlaceholder":273},[198,616,618,620,622,625,627,629,631,633],{"class":200,"line":617},17,[198,619,288],{"class":204},[198,621,291],{"class":204},[198,623,624],{"class":225}," error",[198,626,229],{"class":215},[198,628,232],{"class":204},[198,630,236],{"class":235},[198,632,302],{"class":215},[198,634,216],{"class":215},[198,636,638,640,642,644,646,648,650,653,655,657],{"class":200,"line":637},18,[198,639,494],{"class":493},[198,641,320],{"class":215},[198,643,499],{"class":323},[198,645,320],{"class":215},[198,647,593],{"class":225},[198,649,229],{"class":215},[198,651,652],{"class":334},"\"[error]:\"",[198,654,338],{"class":215},[198,656,236],{"class":235},[198,658,239],{"class":215},[198,660,662],{"class":200,"line":661},19,[198,663,348],{"class":215},[198,665,667],{"class":200,"line":666},20,[198,668,245],{"class":215},[188,670,673],{"className":190,"code":671,"filename":672,"language":193,"meta":194,"style":194},"public class Demo {\n    public static void main(String[] args) {\n        Log log = new Log(new FileLogger());\n        log.error(\"tests log error file,Strategy Pattern.\");\n        log.info(\"tests log info file,Strategy Pattern.\");\n\n        log.setLogger(new ConsoleLogger());\n        log.error(\"tests log error console,Strategy Pattern.\");\n        log.info(\"tests log info console,Strategy Pattern.\");\n    }\n}\n","Demo.java",[36,674,675,686,712,738,755,771,775,792,807,822,826],{"__ignoreMap":194},[198,676,677,679,681,684],{"class":200,"line":201},[198,678,205],{"class":204},[198,680,258],{"class":204},[198,682,683],{"class":211}," Demo",[198,685,216],{"class":215},[198,687,688,690,693,695,698,700,702,705,708,710],{"class":200,"line":219},[198,689,288],{"class":204},[198,691,692],{"class":204}," static",[198,694,291],{"class":204},[198,696,697],{"class":225}," main",[198,699,229],{"class":215},[198,701,232],{"class":204},[198,703,704],{"class":215},"[]",[198,706,707],{"class":235}," args",[198,709,302],{"class":215},[198,711,216],{"class":215},[198,713,714,717,720,723,726,728,730,733,735],{"class":200,"line":242},[198,715,716],{"class":204},"        Log",[198,718,719],{"class":235}," log ",[198,721,722],{"class":215},"=",[198,724,725],{"class":204}," new",[198,727,449],{"class":225},[198,729,229],{"class":215},[198,731,732],{"class":204},"new",[198,734,261],{"class":225},[198,736,737],{"class":215},"());\n",[198,739,740,743,745,748,750,753],{"class":200,"line":285},[198,741,742],{"class":235},"        log",[198,744,320],{"class":215},[198,746,747],{"class":225},"error",[198,749,229],{"class":215},[198,751,752],{"class":334},"\"tests log error file,Strategy Pattern.\"",[198,754,239],{"class":215},[198,756,757,759,761,764,766,769],{"class":200,"line":307},[198,758,742],{"class":235},[198,760,320],{"class":215},[198,762,763],{"class":225},"info",[198,765,229],{"class":215},[198,767,768],{"class":334},"\"tests log info file,Strategy Pattern.\"",[198,770,239],{"class":215},[198,772,773],{"class":200,"line":314},[198,774,274],{"emptyLinePlaceholder":273},[198,776,777,779,781,784,786,788,790],{"class":200,"line":345},[198,778,742],{"class":235},[198,780,320],{"class":215},[198,782,783],{"class":225},"setLogger",[198,785,229],{"class":215},[198,787,732],{"class":204},[198,789,368],{"class":225},[198,791,737],{"class":215},[198,793,794,796,798,800,802,805],{"class":200,"line":351},[198,795,742],{"class":235},[198,797,320],{"class":215},[198,799,747],{"class":225},[198,801,229],{"class":215},[198,803,804],{"class":334},"\"tests log error console,Strategy Pattern.\"",[198,806,239],{"class":215},[198,808,809,811,813,815,817,820],{"class":200,"line":517},[198,810,742],{"class":235},[198,812,320],{"class":215},[198,814,763],{"class":225},[198,816,229],{"class":215},[198,818,819],{"class":334},"\"tests log info console,Strategy Pattern.\"",[198,821,239],{"class":215},[198,823,824],{"class":200,"line":537},[198,825,348],{"class":215},[198,827,828],{"class":200,"line":552},[198,829,245],{"class":215},[32,831,832,833,835],{},"Running ",[36,834,181],{}," prints:",[188,837,842],{"className":838,"code":840,"language":841,"meta":194},[839],"language-text","[file]:[error]:tests log error file,Strategy Pattern.\n[file]:[info]:tests log info file,Strategy Pattern.\n[console]:[error]:tests log error console,Strategy Pattern.\n[console]:[info]:tests log info console,Strategy Pattern.\n","text",[36,843,840],{"__ignoreMap":194},[845,846,847],"style",{},"html pre.shiki code .sVsk0, html code.shiki .sVsk0{--shiki-default:#9D9FFE;--shiki-light:#6762D3}html pre.shiki code .sNwy7, html code.shiki .sNwy7{--shiki-default:#D4D7FE;--shiki-light:#3F3B87}html pre.shiki code .sVG6I, html code.shiki .sVG6I{--shiki-default:#85858F;--shiki-light:#71717A}html pre.shiki code .sVz7n, html code.shiki .sVz7n{--shiki-default:#EDEDEF;--shiki-light:#0B0B0C}html pre.shiki code .sWFPS, html code.shiki .sWFPS{--shiki-default:#C4C4CC;--shiki-light:#3F3F46}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html pre.shiki code .sFjNZ, html code.shiki .sFjNZ{--shiki-default:#6B6B74;--shiki-default-font-style:italic;--shiki-light:#8B8B94;--shiki-light-font-style:italic}html pre.shiki code .s4Awn, html code.shiki .s4Awn{--shiki-default:#C5DDFE;--shiki-light:#534DAF}html pre.shiki code .sUOzB, html code.shiki .sUOzB{--shiki-default:#9EC7FE;--shiki-light:#2873D1}html pre.shiki code .sheII, html code.shiki .sheII{--shiki-default:#70ADFF;--shiki-light:#195CAE}",{"title":194,"searchDepth":219,"depth":219,"links":849},[850,851,852,856,857],{"id":29,"depth":219,"text":30},{"id":52,"depth":219,"text":53},{"id":75,"depth":219,"text":76,"children":853},[854,855],{"id":80,"depth":242,"text":81},{"id":95,"depth":242,"text":96},{"id":113,"depth":219,"text":114},{"id":185,"depth":219,"text":186},"The Strategy pattern puts each version of an algorithm in its own class, so you can swap them while the program runs. Explained with a worked Java example of a logger that writes to a file or the console.","A logger that writes to a file or the console","md","Behavioral","lucide:shuffle",{},"\u002Flearn\u002Fdesign-patterns\u002Fstrategy","---\ntitle: Strategy\ngroup: Behavioral\nicon: lucide:shuffle\nsummary: 'Put each way of doing a task in its own class, and choose which one to use while the program runs.'\ndescription: 'The Strategy pattern puts each version of an algorithm in its own class, so you can swap them while the program runs. Explained with a worked Java example of a logger that writes to a file or the console.'\nexample: 'A logger that writes to a file or the console'\norder: 6\nsource: https:\u002F\u002Fgithub.com\u002FHaythamasalama\u002FdesignPattern\u002Ftree\u002Fmaster\u002Fsrc\u002FBehavioral\u002FStrategy\n---\n\n## The idea\n\nThere is often more than one way to do the same task. Logs can go to a file, the console or a database. A price can be worked out with or without a discount. If one class holds all the options behind an `if` or a `switch`, it grows with every new option, and changing one risks breaking the others.\n\nThe Strategy pattern puts each option, each strategy, in its own class behind a shared interface. The class that needs the work done, the context, holds a reference to a strategy and calls it through that interface. It doesn't know which strategy it has.\n\nYou pass a strategy in when you create the context, and can swap it later. A new option means a new class, not an edit to the context.\n\n## When to use it\n\n- You have several ways to do the same task and want to choose between them at runtime.\n- A class has a large `switch` that picks between versions of one algorithm.\n- You want to keep the details of an algorithm, and the data it uses, out of the class that uses it.\n- You want to test each version of the algorithm on its own.\n\n## Pros and cons\n\n### Pros\n\n- It is flexible and easy to extend: a new behaviour is a new class.\n- You can pick the right algorithm for the current situation, and change it at runtime.\n- It replaces conditionals with composition, so the context stays small.\n\n### Cons\n\n- It adds classes to the system: one for each strategy.\n- Clients must know that the strategies exist and choose between them.\n- If there are only two options and they rarely change, an `if` is simpler.\n\n## The example\n\nThe example is a logger. The same `Log` object can write to a file or to the console, and the demo switches between the two while the program runs.\n\n- **`Logger`**: the strategy interface, with one `log(message)` method.\n- **`FileLogger`** and **`ConsoleLogger`**: concrete strategies. Both print to the console, with a prefix that shows where the message would go. A comment in `FileLogger` marks where writing to a file belongs.\n- **`Log`**: the context. It holds a `Logger`, offers `info()` and `error()`, and adds the level to the message before passing it to the strategy. `setLogger()` swaps the strategy.\n- **`Demo`**: logs two messages with the file logger, swaps in the console logger, and logs two more.\n\n## The code\n\n```java [Logger.java]\npublic interface Logger {\n    void log(String message);\n}\n```\n\n```java [FileLogger.java]\npublic class FileLogger implements Logger {\n\n    @Override\n    public void log(String message) {\n        \u002F\u002F Your implementation for logging to file.\n        System.out.println(\"[file]:\" + message);\n    }\n}\n```\n\n```java [ConsoleLogger.java]\npublic class ConsoleLogger implements Logger {\n    @Override\n    public void log(String message) {\n        \u002F\u002F Your implementation for logging to console.\n        System.out.println(\"[console]:\" + message);\n    }\n}\n```\n\n```java [Log.java]\npublic class Log {\n\n    private Logger logger;\n\n    public Log(Logger logger) {\n        this.logger = logger;\n    }\n\n    public void setLogger(Logger logger) {\n        this.logger = logger;\n    }\n\n    public void info(String message) {\n        this.logger.log(\"[info]:\" + message);\n    }\n\n    public void error(String message) {\n        this.logger.log(\"[error]:\" + message);\n    }\n}\n```\n\n```java [Demo.java]\npublic class Demo {\n    public static void main(String[] args) {\n        Log log = new Log(new FileLogger());\n        log.error(\"tests log error file,Strategy Pattern.\");\n        log.info(\"tests log info file,Strategy Pattern.\");\n\n        log.setLogger(new ConsoleLogger());\n        log.error(\"tests log error console,Strategy Pattern.\");\n        log.info(\"tests log info console,Strategy Pattern.\");\n    }\n}\n```\n\nRunning `Demo` prints:\n\n```text\n[file]:[error]:tests log error file,Strategy Pattern.\n[file]:[info]:tests log info file,Strategy Pattern.\n[console]:[error]:tests log error console,Strategy Pattern.\n[console]:[info]:tests log info console,Strategy Pattern.\n```\n",{"title":22,"description":858},{"loc":864},"https:\u002F\u002Fgithub.com\u002FHaythamasalama\u002FdesignPattern\u002Ftree\u002Fmaster\u002Fsrc\u002FBehavioral\u002FStrategy","learn\u002Fdesign-patterns\u002Fstrategy","Put each way of doing a task in its own class, and choose which one to use while the program runs.","DZq9b-r4D13XbAE8e5wAEWbosZ8IF2ihdy4PWHh6wOs",[873,878,883,888,893,898,899,904],{"path":874,"title":875,"icon":876,"summary":877,"order":201},"\u002Flearn\u002Fdesign-patterns\u002Fchain-of-responsibility","Chain of Responsibility","lucide:link","Pass a request along a chain of handlers, where each one can deal with it or hand it to the next.",{"path":879,"title":880,"icon":881,"summary":882,"order":219},"\u002Flearn\u002Fdesign-patterns\u002Fcommand","Command","lucide:square-terminal","Turn a request into an object, so it can be passed around, queued, logged or undone.",{"path":884,"title":885,"icon":886,"summary":887,"order":242},"\u002Flearn\u002Fdesign-patterns\u002Fiterator","Iterator","lucide:list-ordered","Walk through the items of a collection one by one, without knowing how the collection stores them.",{"path":889,"title":890,"icon":891,"summary":892,"order":285},"\u002Flearn\u002Fdesign-patterns\u002Fobserver","Observer","lucide:bell","One object announces a change, and every object that subscribed to it hears about it.",{"path":894,"title":895,"icon":896,"summary":897,"order":307},"\u002Flearn\u002Fdesign-patterns\u002Fstate","State","lucide:toggle-left","An object changes its behaviour when its internal state changes, as if it had changed its class.",{"path":864,"title":22,"icon":862,"summary":870,"order":314},{"path":900,"title":901,"icon":902,"summary":903,"order":345},"\u002Flearn\u002Fdesign-patterns\u002Ftemplate-method","Template Method","lucide:layout-template","A base class fixes the steps of a task, and subclasses fill in the steps that differ.",{"path":905,"title":906,"icon":907,"summary":908,"order":351},"\u002Flearn\u002Fdesign-patterns\u002Fvisitor","Visitor","lucide:footprints","Add new operations to a set of classes without changing them, by moving each operation into its own visitor.",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":910},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M15 14c.2-1 .7-1.7 1.5-2.5c1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5c.7.7 1.3 1.5 1.5 2.5m0 4h6m-5 4h4\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":912},"\u003Cg fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\">\u003Crect width=\"8\" height=\"8\" x=\"3\" y=\"3\" rx=\"2\"\u002F>\u003Cpath d=\"M7 11v4a2 2 0 0 0 2 2h4\"\u002F>\u003Crect width=\"8\" height=\"8\" x=\"13\" y=\"13\" rx=\"2\"\u002F>\u003C\u002Fg>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":914},"\u003Cg fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\">\u003Cpath d=\"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71\"\u002F>\u003Cpath d=\"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71\"\u002F>\u003C\u002Fg>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":916},"\u003Cg fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\">\u003Cpath d=\"m7 11l2-2l-2-2m4 6h4\"\u002F>\u003Crect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" ry=\"2\"\u002F>\u003C\u002Fg>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":918},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M11 5h10m-10 7h10m-10 7h10M4 4h1v5M4 9h2m.5 11H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":920},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M10.268 21a2 2 0 0 0 3.464 0m-10.47-5.674A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":922},"\u003Cg fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\">\u003Ccircle cx=\"9\" cy=\"12\" r=\"3\"\u002F>\u003Crect width=\"20\" height=\"14\" x=\"2\" y=\"5\" rx=\"7\"\u002F>\u003C\u002Fg>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":924},"\u003Cg fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\">\u003Cpath d=\"m18 14l4 4l-4 4m0-20l4 4l-4 4\"\u002F>\u003Cpath d=\"M2 18h1.973a4 4 0 0 0 3.3-1.7l5.454-8.6a4 4 0 0 1 3.3-1.7H22M2 6h1.972a4 4 0 0 1 3.6 2.2M22 18h-6.041a4 4 0 0 1-3.3-1.8l-.359-.45\"\u002F>\u003C\u002Fg>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":926},"\u003Cg fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\">\u003Crect width=\"18\" height=\"7\" x=\"3\" y=\"3\" rx=\"1\"\u002F>\u003Crect width=\"9\" height=\"7\" x=\"3\" y=\"14\" rx=\"1\"\u002F>\u003Crect width=\"5\" height=\"7\" x=\"16\" y=\"14\" rx=\"1\"\u002F>\u003C\u002Fg>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":928},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M4 16v-2.38C4 11.5 2.97 10.5 3 8c.03-2.72 1.49-6 4.5-6C9.37 2 10 3.8 10 5.5c0 3.11-2 5.66-2 8.68V16a2 2 0 1 1-4 0m16 4v-2.38c0-2.12 1.03-3.12 1-5.62c-.03-2.72-1.49-6-4.5-6C14.63 6 14 7.8 14 9.5c0 3.11 2 5.66 2 8.68V20a2 2 0 1 0 4 0m-4-3h4M4 13h4\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":930},"\u003Cg fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\">\u003Crect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" ry=\"2\"\u002F>\u003Cpath d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"\u002F>\u003C\u002Fg>",1793131416973]