Design Mode (11) Strategy Mode

Source: Internet
Author: User

Design Mode (11) Strategy Mode

I. Discounts

A website that sells books wants to build a settlement system. Part of the system is to calculate the price of books. The books on this website are basically discounted, and the discounts for different types of books are different, for example, a comic book may take off, or a novel may take off. Their initial design was like this.

Solution 1: Judge on the client

if(book is comic)    price*=0.9;else if(book is novel)    price*=0.6;

It seems that there is no problem, but the client code will look very bloated when there are many types of books, and every time we add a new book, we need to add an if-else statement. if this book is off the shelf, we need to delete the corresponding statement, which is very troublesome.

Solution 2:

We can define an abstract class of a Book. Each Book inherits from this class and each class implements its own price calculation method. This avoids the bloated client, however, this will link the algorithm with the implementation of the book. If we want to modify the discount range, we need to modify the class of the corresponding book, which does not comply with the "open-close" principle.

Solution 3:

Every price calculation method is encapsulated into a strategy class, which can be dynamically set on the client. which policy is used for this book? when there is a new discount method, we can add a new strategy class without having to modify the code of the book and completely separate the book from the algorithm, reducing the Coupling Degree and complying with the "open-close" principle.

Ii. Definition and structure of policy Modes

The third solution above is our strategy model. Policy mode encapsulates each algorithm and allows them to replace each other. The rule mode allows algorithms to change independently of customers who use it.

The rule mode involves three roles:

Environment (Context) Role: This is the class that uses the policy (algorithm) and holds a reference to the Strategy class.

Abstract policy role (Strategy): defines the interface that the policy class should have.

Specific policy role (Concrete): implements the relevant algorithms.

Iii. model Use Cases

Package com. designpattern. adapter. strategy;/*** abstract classes of various books * @ author 98583 **/public abstract class Book {/*** original price */protected double basePrice = 0.0; /*** policy reference */protected Strategy strategy; public Book (double basePrice) {this. basePrice = basePrice;}/*** set policy * @ param strategy */public void setStrategy (Strategy strategy) {this. strategy = strategy;}/*** obtain the book payable price using the unified interface of the policy * @ return */public double getPrice () {return strategy. getDiscount (basePrice);}/*** abstract display method. Each type of books has its own implementation method */public abstract void show ();}
package com.designpattern.adapter.strategy;public class Comic extends Book{    public Comic(double basePrice) {        super(basePrice);    }    public void show() {        System.out.println(The Comic Book is +getPrice());    }}
package com.designpattern.adapter.strategy;public abstract class Strategy {    public abstract double getDiscount(double basePrice);}
package com.designpattern.adapter.strategy;public class NovelStrategy extends Strategy{    public double getDiscount(double basePrice) {        return 0.6*basePrice;    }}
Package com. designpattern. adapter. strategy; public class Client {public static void main (String [] args) {Book book = new Comic (12.3); Strategy strategy = new ComicStrategy (); // set the policy book. setStrategy (strategy); book. show ();}}

The novel code is similar to the cartoon code and will not be pasted out. The source code will be appended.

Iv. Advantages and disadvantages of the Policy Model

Advantages:

The policy mode provides perfect support for the "Open/closed principle". You can select algorithms or actions without modifying the original system, or flexibly add new algorithms or actions. Policy mode provides methods for managing related algorithm families. The rule mode provides a way to replace the inheritance relationship. The policy mode avoids the use of multiple conditional transfer statements.

Disadvantages:

The client must know all the policy classes and decide which one to use. The policy mode will generate many policy classes. You can reduce the number of objects to a certain extent by using the enjoy mode.

V. usage of the Policy Mode

1. If there are many classes in a system, the difference between them is only their behavior, then the policy mode can dynamically allow an object to select a behavior among many behaviors.
A system must dynamically select one of several algorithms.
2. If an object has many behaviors and the appropriate mode is not used, these behaviors must be implemented using multiple conditional selection statements.
3. Do not want the client to know the complex and algorithm-related data structures, encapsulate algorithms and related data structures in specific policy classes, and improve the confidentiality and security of algorithms.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.