Ideas about the factory model

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.