Summary of mobile development policy modes and Development Policy Modes
I. Concepts and Class Diagrams
In policy mode, a series of algorithms are defined and each algorithm is encapsulated so that they can be replaced with each other. Policy mode allows the algorithms to run independently of customers who use them, is an object behavior mode.
Strategy is an abstract policy class that defines public methods of algorithms.
ConcreteStrategyA and B are specific algorithm classes that encapsulate the specific implementation of algorithms.
Context indicates the environment class and maintains an instance of Strategy.
Ii. discounts for instance movie tickets
// Discount class: abstract policy class public interface Discount {public double calculate (double price );}
// Discount class for children: public class ChildrenDiscount implements Discount {@ Override public double calculate (double price) {return price-10 ;}}
// Student Discount class: specific policy class public class StudentDiscount implements Discount {@ Override public double calculate (double price) {return price * 0.8 ;}}
// Member Discount class: specific policy class public class VipDiscount implements Discount {@ Override public double calculate (double price) {System. out. println ("plus points"); return price * 0.5 ;}}
// Movie tickets: public class MovieTicket {private double price; private Discount discount; public MovieTicket (double price) {this. price = price;} public double getPrice () {return discount. calculate (this. price);} public void setDiscount (Discount discount) {this. discount = discount ;}}
// Client class public class Client {public static void main (String [] args) {MovieTicket movieTicket = new MovieTicket (50); double currentPrice; Discount discount; discount = new StudentDiscount (); movieTicket. setDiscount (discount); currentPrice = movieTicket. getPrice (); System. out. println ("Student Pass:" + currentPrice); System. out. println ("------------------------"); discount = new VipDiscount (); movieTicket. setDiscount (discount); currentPrice = movieTicket. getPrice (); System. out. println ("member Ticket:" + currentPrice );}}
Iii. Summary
1. Different algorithms can be encapsulated through the use of policy modes, so that the algorithms are independent of customers who use them.
2. In the basic policy mode, the role of the selected policy is assumed by the client. The client must know all the policy classes and decide which policy class to use on its own, that is to say, the client needs to know the difference between algorithms.
3. In order to reduce the client's responsibility for selecting specific policies, you can combine the simple factory mode and put the specific implementation of the selection into the Context Environment class, so that the client's responsibilities can be minimized.