In the previous blog, I mentioned the following: "In fact, it is better to save a variable in the object to be polymorphism. The variable contains a program, if you run this program, take it out of eval. It is no better than creating several sub-classes ". Some readers asked me what this means and asked me to give an example. In fact, this is very simple, as long as you want to know that all the reactionary factions are paper tigers ...... Well, I mean, all operations are lambda. Then you can use the operation as data. Of course, it is built on the following: Your language support makes Lambda a first-class citizen conveniently.
Class Host
Def state = (state)
@ State = State
End
Def do_something
@ State (Self)
End
End
Host = host. New
Host. State = {| host | P Host}
Host. do_something
For example, this is a state Mode Implemented in Ruby (or a strategy mode, which is not very different ). Host saves a Lambda in @ State (the ruby black talk seems to be called closure). You can use this for whatever operations you want to do. The State/Strategy Mode is implemented in C #/Java. You are familiar with it and can understand what I mean by comparison.
I apologize for the previous article "C # looks too ugly". I didn't expect that a joke would cause a language war. I'm sorry, when I was stunned by the sun in Bangalore, let me talk about it. From this we can see that Chinese programmers (or some Chinese programmers) are very enlightened, and the string of class struggle is very tight ...... Although I like a language, I have nothing to say. If I am so confident in this language, can I jump up when I hear three complaints?
(Supplement: Lambda in the above example can be written more beautifully. do_something can be written as follows:
Def do_something
@ State
End
The imported Lambda can be written
Host. State = {P self}
This is a bit amazing: Lambda context is defined in it, rather than called, that is, Lambda self is not actually a host. However, there is a tricky method: caller can find the lambda caller, and then give the caller to Mixin into the self of the current context. After the call, Mixin will be returned ...... Thanks to Obie for his inspiration and Xu Ba x's implementation .)