The factory model is divided into: Static Factory, factory method, abstract factory.
Factory model Benefits (I think of):
1, the object Unified management, re-use, easy to modify (change a place, many changes at the same time)
2. Separation of object generation and use (customer does not care about the details of the creation, only cares about how to use the "single chain of responsibility" principle)
I used to look at the static factory method most of the way (this is mainly not research Factory mode)
Public class factorydemo{ publicstatic person Createperson (String typeName) { If(typename.equals ("Student")) { return new student (); } Else if (Typename.equals ("Teacher")) { return new Teacher ();}} }
But I was thinking, if the person interface implementation class is very much, then this factory is not very bloated?
Factory mode There is a workaround (not much here), I just said some of my ideas, the arguments here are changed, I can pass the parameters of the variable come in?
Then I thought of the reflection, so I made the following changes:
public class personfactory{ public static person Createperson (Class demo) throws exception{ if (Person.class .isassignablefrom (demo) {person P = (person) demo.newinstance (); return P; else { throw new runtimeexception ("The factory cannot produce a non-person interface implementation Class" ); } } }
That way, the factory doesn't have to change.
If you want to get the Student object, you only need to call Personfactory.createperson (Student.class) to
If you want to get the Teacher object, you only need to call Personfactory.createperson (Teacher.class) to
Ideas about the factory model