Hello everyone, let me pull the rule mode this morning.
First of all, we all know that the fact that programmers hate most is that the demand has been changing !!! So it is necessary to write the easy-to-maintain, scalable code, right?
Let's look at the next background.
Suppose you want to write a human Class. It has a go () method, but it sometimes takes a bus, sometimes a bus, or sometimes a plane, sometimes riding a yacht .... how can we deal with all the situations? You said, "Write a bunch of code in the go method." How do you know all the situations? What if I want to add a new method?
Let's introduce the policy mode.
The rule mode is defined as follows:
The rule mode is the behavior mode of an object. It is intended to encapsulate each algorithm into a class with a public interface, so that they can be replaced with each other, the rule mode allows the algorithm to change without affecting your client.,
Look at the simple UML diagram
Understand the following concepts:
Context ): <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + kernel/kernel + kernel/WoaMKPHA + PC9wPgo8cD48YnI + c1_vcd4kpha + kernel/kernel + v7S/kernel = "http://www.2cto.com/uploadfile/Collfiles/20140408/20140408093535234.jpg" alt = "\">
Look at the Code:
package edu.fjnu.cs.hwb.strategy;public class People{private Vehicle v ;public void setVehicle(Vehicle v){this.v = v;}public void go(){v.go();}}Interface
package edu.fjnu.cs.hwb.strategy;public interface Vehicle { void go();}
Package edu. fjnu. cs. hwb. strategy; public class OnFoot implements Vehicle {public void go () {System. out. println ("I am walking ");}}
Package edu. fjnu. cs. hwb. strategy; public class ByBus implements Vehicle {public void go () {System. out. println ("I am riding ");}}
Package edu. fjnu. cs. hwb. strategy; public class ByPlane implements Vehicle {public void go () {System. out. println ("I am flying ");}}
package edu.fjnu.cs.hwb.strategy;public class Client { public static void main(String[] args) { People p = new People(); p.setVehicle(new OnFoot()); p.go(); p.setVehicle(new ByBus()); p.go(); p.setVehicle(new ByPlane()); p.go(); }}
Let's summarize the policy mode:
When a part of you changes frequently, you can separate this part and make it a rule model.
Advantages: scalability
Disadvantage: client programmers need to know all the algorithms! And if there are many algorithms, it will be a headache ..
Please make corrections!