Factory mode (think in Java design mode)

Source: Internet
Author: User

Factory mode: Factory mode is a design pattern that uses factory-class factory methods to create objects, which are designed to create objects, but many times we will consider many other factors, such as qualifying the input, qualifying the return value for some, such as making some judgments during the creation process, These things can be separated by different factory models.

 Packagecom.dhh.test;Importorg.junit.Test; Public classTest2 {@Test Public voidT ()throwsinstantiationexception, illegalaccessexception, classnotfoundexception{//Class A implements the C interface to returnA a= (a) Factory.builder ("a");        System.out.println (A.name); //B also implements a C interface that can be returned, but I tried to limit the type of the created class if B removes the C interface and cannot be returnedb b= (b) Factory.builder ("B"));            System.out.println (B.name); }}classfactory{//C can actually be a return value as an interface    Static  PublicC Builder (String typeName)throwsinstantiationexception, illegalaccessexception, classnotfoundexception{//Reflection Creation Class//Direct Pass in a, B type name, factory internal splicing permission naming can restrict the creation of the class packageObject o=class.forname ("Com.dhh.test.") +typeName). newinstance (); //can actually be strong to C interface        return(C) o; }}Interfacec{}classAImplementsc{String name= "168";}classBImplementsc{String name= "178";}

The above is the process of creating a static factory class, and all procedures for creating a class are hidden

Factory mode (think in Java design mode)

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.