What is a “design pattern”? , there is no class diagram, there is no code, some students say that they do not understand, today I bring you the strategy mode (there is a diagram, there is a code, there is the truth! .

League of Legends

Those of you who have played LOL know that LOL has hundreds of heroes. What if you design them with OO technology?

Xiaoming: Simple, first to a Superclass (Superclass), and then let all heroes inherit this Superclass, different methods rewrite the Superclass method can be. QWER skill is different for every hero, rewriting is ok, but summoner skill is fixed for every hero.

Xiaoming: That’s right. If all the summoner skills are rewritten by subclasses, then there will be multiple subclasses with duplicate code. What should I do?

Rule of design: Identify areas where your application might need to change, isolate them, and don’t mix them with code that doesn’t need to change.

Xiaoming: The change is the summoner skill, which can be extracted into an interface. All summoner skills need to implement this interface.

Design principle: Program for the interface, not the implementation.

Xiaoming: In this way, you can write all the fixed summoner skills first. When the player chooses summoner skills, they only need to set specific summoner skills. Even if a new summoner skill is implemented in the future, the implementation classes can be replaced with each other.

Design principle: use composition more than inheritance.

Xiaoming: If the idea is clear, go directly to the code.

Summoner skill interface

public interfaceSummoner skills{ 

public voidSkills (); }Copy the code

The specific implementation

public classhealingimplementsSummoner skills{

public voidSkills () {// Heal health for your hero and nearby Allies.
};

}Copy the code

The hero class

public classhero{

   public voidSummoner skills (Summoner skills){skill variables. Skills (); }}Copy the code

The client

public classThe client{ 
public static void main(String[] args) { 
// Select and create a policy object to useSummoner skill My healing =newHealing ();// Create environmentHero my Galen =newGalen ();// Use the policyMy Galen Summoner skill (my healer); }}Copy the code

This is called the “strategy pattern”, which defines the algorithms (summoner skill interface), encapsulates them (specific implementation classes: teleport, healing) and makes them interchangeable with each other, allowing the algorithm to change independently of the client using the algorithm.

The above code block is written in Chinese class name, variable name is to let you better understand, remember in the actual combat process to replace the corresponding English.

Giffy Diagrams Read: BRVAH’s Add Animation (Strategy Mode) Extended Read: How do Code Refactoring Work? Reference Book: Head First Design Patterns

Welcome to my Jane book and Github