Haven't updated the blog for a long time. Recently also busy charging, today this blog began, we come to understand the design pattern.
Design Patterns
So what is design mode? First, take a look at the concept I copied from the encyclopedia.
Design pattern/Software design pattern is a set of reusable, most known, categorized purposes, code design experience Summary. Design patterns are used in order to reuse code, make code easier to understand, and ensure code reliability.
Well. Probably means that in the code of the world by the Codebook summed up, can solve the problem of repetitive software design, by most people regardless of the design way, can also be said to be a coding rule.
Initial coding we always write the code according to our own routines. such as the Code of the project is huge, the need to change, and suddenly found that the change of the good, a lot of files to move, in order to adapt to the new requirements change this file may affect other business logic, change this file will not introduce a bug? A series of questions in front of us, headache, confusion, there is a kind of wood to write again once again impulse? Well, if you're in a situation like this. Design patterns may be part of your rescue.
But. There are a lot of people in the design pattern who are addicted to the design pattern, and every few lines of code you have to consider--is there a need for a pattern! Remember. Mode is a set of coding rules that is summed up in order to facilitate our solution to this problem. It is not that we do not need to design pattern code extensibility is necessarily poor. Choose whether to use the pattern or be cautious, in most cases it is necessary to rely on the needs of the scenario to consider the need for such a pattern, before deciding to use it must consider why to use such a pattern.
Policy mode
Okay, so much for the eggs, here's the beginning of the topic, let's start by introducing the strategy model. First look at the definition,
Define a series of algorithms that encapsulate each algorithm. and allow them to replace each other. The policy pattern makes the algorithm independent of the customers who use it.
Well. This definition seems to be able to do, not like some of the definition must be the whole person can not understand the definition, casually still good understanding. It's just that we're going to introduce a structure diagram to get a clearer picture of it.
To see this structure, perhaps it might come to an epiphany. This is not to let us program for the interface . Yes, almost the same. All of the design patterns are to follow the rules for interface programming , and we think about it, it also reflects the expansion of development, the change is closed (open and close principle) , suppose we want to add some rules, completely do not change the main business process. Just need to add a few strategies to OK, of course. These policies are governed by our interface specifications.
Code implementation
Let's start by showing the strategy pattern in the form of code, the code is very easy, we use a subtraction method to simulate.
First, we will see a strategy interface and a series of policies that do not rely on the implementation of high-level modules.
package strategy/** * 策略接口 */typeinterface { intint}
A very easy interface that defines a method Compute
. Accept two of the parameters. Returns a value of type int, very easy to understand. The strategy we are implementing will return the calculated value of two parameters.
Next, let's look at a strategy we've implemented,
package strategy Import "FMT" type Division struct {}func (P Division) Compute (NUM1, num2 int ) int {defer func () {if f: = recover< /span> (); F! = nil {fmt. Println (f) return }} () if num 2 == 0 {panic ()} return num1/num2}
Why should we take division as a representative? Because Division is special, the divisor cannot be 0, the other multiplication is basically a line of code, Division we need to infer whether dividend is 0, assuming that 0 throws an exception directly.
OK, the main strategy is well defined. We also need a factory method that returns different strategies based on the unused type. This type we are ready to enter from the command good.
func newstrategy (t string ) (Res strategier) {switch t {case "S" : //subtraction res = subtraction{} case< /span> "M" : //multiplication res = multiplication{} case "D" : //Division res = division{} case "a" : //add fallthrough default : res = addition{} } return }
This factory method returns different policy implementations based on the unused type. Of course. One day we need to add a new strategy, we just need to include the appropriate type inference in this function OK.
Now the strategy seems to have finished. Now let's look at the main process code. A computer,
PackageComputeImport("FMT"S".. /strategy ")typeComputerstruct{NUM1, Num2intStrate S.strategier}func(P *computer) Setstrategy (Strate s.strategier) {p.strate = Strate}func(P computer) Do ()int{defer func() {ifF: =Recover(); F! =Nil{FMT. Println (f)}} ()ifP.strate = =Nil{Panic("Strategier is null") }returnP.strate.compute (P.NUM1, P.NUM2)}
There are three parameters in this computer, Num1
and of Num2
course we have to manipulate them. Strate is the strategy that we are going to set up, probably the above Division
, or something else, in the main function we call the SetStrategy
method to set the policy to use, the Do
method runs the operation, and finally returns the result of the operation, and can see the Do
We entrust the computing function to the Strategier
.
It looks like everything is ready, so let's write the code for main.
PackageMainImport("FMT" "Flag"C"./computer"S"./strategy")varStra *string= Flag. String ("Type","a","Input the Strategy")varNUM1 *int= Flag. Int ("NUM1",1,"Input Num1")varNUM2 *int= Flag. Int ("Num2",1,"Input num2")funcInit () {flag. Parse ()}funcMain () {com: = c.computer{num1: *num1, Num2: *num2} strate: = S.newstrategy (*stra) com. Setstrategy (Strate) fmt. Println (COM. Do ())}
First we want to read the type of policy to use and the two operands from the command line. In the main function, we initialize the struct and assign the Computer
input operand to Computer
the Num1
and Num2
, next we call the function according to the policy type NewStrategy
to get a policy, and call Computer
the SetStrategy
method to Computer
Set the policy that you acquired above. The last Run Do
method evaluates the result and prints at the end.
It's that simple. Now we navigate to the folder where the command line is main.go
located. and run the command to compile the file
Go Build Main.go
Continue running command
Main-type D-NUM1 4-num2 2
To try the 4 and 2 of these two numbers using the addition strategy, to see what the results are,
The results are very correct. Try a different strategy. Let's get a multiplication, run the command.
Main-type M-NUM1 4-num2 2
The result is also correct.
Summarize
The strategy model is still relatively easy to understand. The core of the strategy pattern is to separate the easy-to-change code from the main logic, and to standardize their form through an interface. Entrust the task to the policy in the main logic. This reduces our likelihood of changes to the main logic code and also adds the scalability of the system.
Be sure to remember oh. Our code is going toward extension development, to change the design to close this piece of work in principle!
Finally, the example code for this article is downloaded: http://download.csdn.net/detail/qibin0506/9415084
Design pattern-Strategy mode (Go language description)