1, what is the strategy mode?
The strategy pattern, also called the algorithm cluster pattern, is the definition of different algorithm families, and can be replaced between each other, this mode allows the algorithm to change independently of the customer using the algorithm.
2. What are the benefits of the strategy model?
The advantage of the strategy pattern is that you can dynamically change the behavior of the object.
3, Design principles
The design principle is to extract the parts of a class that are often changed or may be changed in the future, as an interface (virtual class can be used in c++z), and then include an instance of the object in the class, so that the instance of the class can invoke the behavior of the class that implements the interface at run time. Here is an example.
The policy pattern belongs to the object behavior pattern, which is mainly for a set of algorithms, encapsulating each algorithm in a separate class with a common interface, so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client. Typically, a policy pattern is used when an application needs to implement a particular service or feature, and the program is implemented in a variety of ways.
4, there are three objects in the policy mode:
(1) Environment Object (context): a reference to an interface or abstract class defined in an abstract policy is implemented in this class.
(2) Abstract policy object (strategy): It can be implemented by an interface or an abstract class.
(3) specific policy object (Concretestrategy): It encapsulates different algorithms for implementing the same functionality.
Using the policy model to build the application, you can choose different algorithms to implement the functions of the application according to the user configuration and other content. The specific selection has the environment object to complete. This approach avoids the code clutter caused by the use of conditional statements, improving application flexibility and rationality.
5, the general steps to write the policy mode:
(1) Define a public interface to the policy object
(2) Write a specific policy class that implements the above interface
(3) Save a reference to a policy object in the class that uses the policy object (that is, the environment role)
(4) In the class that uses the policy object, implement the Set and Get methods (injections) for the policy object or use the construction method to complete the assignment
(5) The client makes the call
6, example
This example is to complete a simple shopping cart, two payment strategies to choose from, one for the credit card and the other for PayPal.
First create the policy interface, in the example in this article, the payment amount as an argument.
1 Public Interface paymentstrategy {23 Public void Pay (int amount); 4 }
Now implement entity classes that use credit cards and PayPal two algorithmic strategies.
1 Public classCreditcardstrategyImplementsPaymentstrategy {2 3 PrivateString name;4 PrivateString Cardnumber;5 PrivateString cvv;6 PrivateString Dateofexpiry;7 8 PublicCreditcardstrategy (string nm, String ccnum, String cvv, String expirydate) {9 This. name=nm;Ten This. cardnumber=Ccnum; One This. cvv=CVV; A This. dateofexpiry=expirydate; - } - @Override the Public voidPayintamount) { -System.out.println (amount + "paid with Credit/debit card"); - } - +}
1 Public classPaypalstrategyImplementsPaymentstrategy {2 3 PrivateString Emailid;4 PrivateString password;5 6 Publicpaypalstrategy (string email, pwd) {7 This. emailid=email;8 This. password=pwd;9 }Ten One @Override A Public voidPayintamount) { -System.out.println (amount + "paid using Paypal.")); - } the -}
Now that the algorithm strategy is ready, you need to implement the shopping cart and payment methods that can use the payment strategy.
1 Public classItem {2 3 PrivateString Upccode;4 Private intPrice ;5 6 PublicItem (String UPC,intCost ) {7 This. upccode=UPC;8 This. price=Cost ;9 }Ten One PublicString Getupccode () { A returnUpccode; - } - the Public intGetPrice () { - returnPrice ; - } - +}
1 Public classShoppingCart {2 3 //List of items4List<item>items;5 6 PublicShoppingCart () {7 This. items=NewArraylist<item>();8 }9 Ten Public voidAddItem (item item) { One This. Items.Add (item); A } - - Public voidRemoveItem (item item) { the This. Items.remove (item); - } - - Public intcalculatetotal () { + intsum = 0; - for(Item item:items) { +Sum + =Item.getprice (); A } at returnsum; - } - - Public voidPay (Paymentstrategy paymentmethod) { - intAmount =calculatetotal (); - Paymentmethod.pay (amount); in } -}
Note that the payment method of the shopping cart accepts the payment policy as a parameter, but does not save any instance variables within it.
A simple test program.
1 Public classShoppingcarttest {2 3 Public Static voidMain (string[] args) {4ShoppingCart cart =NewShoppingCart ();5 6Item item1 =NewItem ("1234", 10);7Item item2 =NewItem ("5678", 40);8 9 Cart.additem (item1);Ten Cart.additem (item2); One A //Pay by PayPal -Cart.pay (NewPaypalstrategy ("[Email protected]", "MyPwd")); - the //Pay by Credit card -Cart.pay (NewCreditcardstrategy ("Pankaj Kumar", "1234567890123456", "786", "12/15")); - } - +}
The output is as follows:
paid using Paypal. Paid with Credit/debit card
Policy Mode UML diagram
Important points:
* The entity variables for the policy can be built here, but this should be avoided as much as possible. This is similar to the Collection.sort () and Array.Sort () methods using comparator as arguments, because it is necessary to ensure that a specific algorithm strategy is appropriate for a particular task.
* Policy mode similar to state mode. The difference between the two is that the context (Environment object) in the state pattern contains the instance variables of the state, and the different tasks depend on the same state. Instead, in the policy mode, the policy is passed as a parameter into the method, and thecontext (Environment object) does not need and cannot store any variables.
* When a set of algorithms corresponds to a task, and the program can choose one of the algorithms flexibly at run time, the strategy mode is a good choice.
Reproduced from the Concurrent Programming network –ifeve.com link address: Java Policy Mode Example tutorial
The strategy mode of Java design pattern