The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used incomputer programming to encapsulate varying behavior for the same object based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to large monolithic conditional statements[1]:395 and thus improve maintainability.
The state interface and two implementations. The state’s method has a reference to the context object and is able to change its state.
interface Statelike { void writeName(StateContext context, String name); } class StateLowerCase implements Statelike { @Override public void writeName(final StateContext context, final String name) { System.out.println(name.toLowerCase()); context.setState(new StateMultipleUpperCase()); } } class StateMultipleUpperCase implements Statelike { /** Counter local to this state */ private int count = 0; @Override public void writeName(final StateContext context, final String name) { System.out.println(name.toUpperCase()); /* Change state after StateMultipleUpperCase's writeName() gets invoked twice */ if(++count > 1) { context.setState(new StateLowerCase()); } } }
The context class has a state variable that it instantiates in an initial state, in this case
StateLowerCase
. In its method, it uses the corresponding methods of the state object.class StateContext { private Statelike myState; StateContext() { setState(new StateLowerCase()); } /** * Setter method for the state. * Normally only called by classes implementing the State interface. * @param newState the new state of this context */ void setState(final Statelike newState) { myState = newState; } public void writeName(final String name) { myState.writeName(this, name); } }
The demonstration below shows the usage:
public class DemoOfClientState { public static void main(String[] args) { final StateContext sc = new StateContext(); sc.writeName("Monday"); sc.writeName("Tuesday"); sc.writeName("Wednesday"); sc.writeName("Thursday"); sc.writeName("Friday"); sc.writeName("Saturday"); sc.writeName("Sunday"); } }
With the above code, the output of
main()
from DemoOfClientState
should be:monday TUESDAY WEDNESDAY thursday FRIDAY SATURDAY sunday
More code examples here:
https://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/State
Strategy Pattern
http://en.wikipedia.org/wiki/Strategy_pattern
In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected at runtime. The strategy pattern
- defines a family of algorithms,
- encapsulates each algorithm, and
- makes the algorithms interchangeable within that family.
Strategy lets the algorithm vary independently from clients that use it.[1] Strategy is one of the patterns included in the influential book Design Patterns by Gamma et al. that popularized the concept of using patterns in software design.
For instance, a class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known for each case until run-time, and may require radically different validation to be performed. The validation strategies, encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.
The essential requirement in the programming language is the ability to store a reference to some code in a data structure and retrieve it. This can be achieved by mechanisms such as the native function pointer, the first-class function, classes or class instances in object-oriented programming languages, or accessing the language implementation's internal storage of code via reflection.
The following example is in Java.
package javaapplication8; import java.util.ArrayList; import java.util.List; // Sample Strategy design pattern public class JavaApplication8 { public static void main(String[] args){ Customer a = new Customer(); a.setStrategy(new NormalStrategy()); // Normal billing a.add(1.2,1); // Start Happy Hour a.setStrategy(new HappyHourStrategy()); a.add(1.2,2); // New Customer Customer b = new Customer(); b.setStrategy(new HappyHourStrategy()); b.add(0.8,1); // The Customer Pays a.printBill(); // End Happy Hour b.setStrategy(new NormalStrategy()); b.add(1.3,2); b.add(2.5,1); b.printBill(); } } class Customer{ private List<Double> drinks; private BillingStrategy strategy; public Customer() { this.drinks = new ArrayList<Double>(); } // Add items to tab public void add(double price, int quantity){ drinks.add(price*quantity); } // Payment of bill public void printBill(){ System.out.println("Total due: " + strategy.sum(drinks)); drinks.clear(); } // Set Strategy public void setStrategy(BillingStrategy strategy) { this.strategy = strategy; } } interface BillingStrategy{ // Return total price of drinks consumed public double sum(List<Double> drinks); } // Normal billing strategy (unchanged price) class NormalStrategy implements BillingStrategy{ public double sum(List<Double> drinks) { double sum = 0; for(Double i : drinks){ sum += i; } return sum; } } // Strategy for Happy hour (10% discount) class HappyHourStrategy implements BillingStrategy{ public double sum(List<Double> drinks) { double sum = 0; for(Double i : drinks){ sum += i; } return sum*0.9; } }
More code examples here:
https://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Strategy
No comments:
Post a Comment