Different from the Iterator described in the previous blog post, this article describes a Generator. There is a big difference between the two. Iterators are used to traverse elements in a container. The Java standard library has the Iterator interface and its implementation; but generators are used to create objects. The Java standard library does not provide the Generator interface and its implementation.
[Note: Pay attention to distinguish the generator Generator here from the generator mode (that is, the builder mode) in the design mode. The two are different]
Generator is a class specifically used to create objects
It is actually an application of the factory method pattern and a general A type applied to an interface
When using a generator to create a new object, the object can be created without any parameters—>This is also the difference from the factory method pattern. Factory methods generally Requires parameters
Generally, the generator only defines one method, which is specifically used to generate new objects
The Java standard library does not include the Generator interface, so the generator needs to be defined by itself.
[Generator]
/** - 生成器接口 - @author johnnie - @param <T> */ public interface Generator<T> { /** - 用以产生新对象 - @return */ public T next(); }
[Example code]
/** - Generator 的实现类 - @author johnnie * */ public class PersonGenerator implements Generator<Person> { private Class[] types = new Class[]{Person.class}; public PersonGenerator() { } @Override public Person next() { try { // 利用反射生成 Person 对象 return (Person) types[0].newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { PersonGenerator generator = new PersonGenerator(); Person person = generator.next(); person.setId(0); person.setName("johnnie"); person.setSex("Man"); System.out.println(person); } }
[Output]
Person [id=0, name=johnnie, sex=Man]
The above is the detailed content of Java Notes: How to use Generator. For more information, please follow other related articles on the PHP Chinese website!