Random object generation can be said to be an extension of random number generation, in actual use, we may want to generate not a simple number, but like numbers, uppercase and lowercase characters, Chinese characters, arithmetic expressions and so on.
Because of its relatively simple implementation, to take a variety of random objects of the source code on the Internet is also ubiquitous, so seemingly no one to do a generic, extensible random object generation.
Bo is not mainly because of idle egg pain is not expected to do this thing, OK, to the main. Analysis of random object generation, its main points are no more than three points:
1. Set the Random object set;
2. Get one or more random objects;
3. Get one or more non-repeating random objects;
In these three points, the latter two algorithms are fixed, only set the object set is different, so you can fully use template mode.
For the 1th, the general idea of setting up a set of random objects is to create a collection (array, List). ) to save all objects. But I'm also using this method. The specific reasons are as follows:
1. The number of elements may be very great;
2. The acquisition of an element may be obtained dynamically through an algorithm, which does not know what the element is or does not want to enumerate;
3. Set up a collection, which is already a concrete implementation, the template does not need to know these, the template only need to define a method-through an index to get the corresponding elements. Just like the following code:
<summary>///gets the object according to the actual index///</summary>///<param name= "Realindex" ></param>///<returns ></returns>protected abstract T elementat (int realindex);
Salted Egg Series A template mode construction random object Generation 2 ideas