Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Areas that come to mind:</p> <ul> <li>A resource allocator. In manual resource management, this might be minimizing the time it takes for the resource to allocate, or minimizing fragmentation. Each strategy here has an "Allocate" method that has the same interface, with the user making a decision about which strategy to use based on what they are trying to optimize.</li> <li>A method for connecting and sending network data. Maybe in some cases you would prefer to connect and send UDP datagrams, maybe in other situatinos where performance was less of a factor you would send using TCP/IP. </li> <li>Data formatting/serialization strategy. Allow the code to decide whether an object should be serialized with Json or with Xml. Maybe one for machines, and the other for human-readable situations. Both strategies have a "Serialize" method which takes an object. Each serializes differently.</li> </ul> <p>The theme is that the decision on whether to do something one way or another way is dependent on situational factors, and you or your code would choose the correct strategy based on the situation. </p> <p>Now why would this be more useful than something like:</p> <pre><code>void DoIt() { if (... situation1...) { DoA() } else { DoB(); } } </code></pre> <p>The reason is sometimes you want to just make the decision once and forget about it. The other important theme to strategy pattern is that you decouple the decision about which strategy to use from the code that needs to execute the strategy.</p> <pre><code>DoItStrategy MakeDoItStrategy() { if (... situation1...) { return new DoItStrategyA(); } else { return new DoItStrategyB(); } } </code></pre> <p>In the last example you can just just store the strategy, passing it as just another object that implements the strategy interface. For those executing the strategy, they simply have a way to perform an action. They don't know what the inner workings are under the hood, only that the interface will be satisfied. The users of the strategy shouldn't need to know why we made a decision. They just need to do an action. We make a decision once and passed the strategy to the classes that use the strategy.</p> <p>For example, consider the case where we make a program-wide decision, based on a given network configuration, to connect and send data to a remote hosts with UDP. Instead of each user of the network interface needing to know the logic to make the decision (the "DoIt" function above), we can create the UDP strategy upfront and pass it to everyone who needs to send network data. This strategy then implements a simple interface with the same end result - data gets from A to B.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload