Remember the three main features of object orientation? Encapsulation, inheritance, polymorphism, strategy pattern is a good embodiment of polymorphism.

Application of policy patterns

Once upon a time, I applied the strategy model twice as a code porter at my old employer (I can’t tell you).

First, in the sales system, customers are divided into different types, and the price of goods sold to customers is also different. According to different types of customers, the price of goods purchased by customers is determined.

Secondly, in the marketing system, the activities of merchants, such as full reduction, full discount, full gift, rebate and other preferential activities, through different preferential activities to meet the customer, calculate the actual price of the customer’s final purchase of goods.

Code example of policy pattern

Public interface Strategy {double discountPrice(double money); }Copy the code
Public class StrategyNormal Implement Strategy {@override public double discountPrice(double money) {return money; }}Copy the code
Public class StrategyReduce Implement Strategy {private double target; private double reduce; Public StrategyReduce(double target, double Reduce) {Assert. this.target = target; this.reduce = reduce; } @Override public double discountPrice(double money) { return (money >= target) ? (money - reduce) : money; }}Copy the code
Public class StrategyDiscount Implement Strategy {private double target; private double discount; Public StrategyDiscount(double target, double discount) {Assert. IsTrue (discount >= 0 && discount <=1); this.target = target; this.discount = discount; } @Override public double discountPrice(double money) { return (money >= target) ? (money * discount) : money; }}Copy the code
Public class Context {private Strategy Strategy; public Context(Strategy strategy) { this.strategy = strategy; } public double finalPrice(double money) { return strategy.discountPrice(money); }}Copy the code
Public static void main(String[] args) {Context Context = null; Scanner scanner = new Scanner(System.in); System.out.println(" Please enter policy type "); int strategy = scanner.next(); Switch (strategy) {case 1: system.out.println (" Please input target amount "); double target = scanner.next(); System.out.println(" Please enter the full amount "); double reduce = scanner.next(); context = new Context(new StrategyReduce(target, reduce)); break; Case 2: system.out.println (" Please input target amount "); double target = scanner.next(); System.out.println(" Please enter the full amount of the fold "); double discount = scanner.next(); context = new Context(new StrategyDiscount(target, discount)); break; Default: system.out. println(" Please enter the correct policy type 1/2"); break; } system.out. println(" Please input commodity amount "); double money = scanner.next(); double totalprice = context.finalPrice(money); System.out.println(" totalprice "+ totalprice); }Copy the code