Simple Factory mode

Source: Internet
Author: User

Pattern definition

Simple Factory pattern: Also known as the Static Factory method (Factory) mode, which belongs to the class-creation mode. In the simple factory model, you can return instances of different classes depending on the parameters , and the simple factory pattern defines a class that is responsible for creating instances of other classes, and the instances that are created typically have a common parent class

Pattern structure

1.Factory: Factory Role

The factory role is responsible for implementing the internal logic that creates all instances

2.Product: Abstract Product role

Abstract product roles are the parent of all objects created, and are responsible for describing common interfaces common to all instances

3.ConcreteProduct: Specific Product roles

The specific product role is to create the target, and all created objects act as instances of a specific class of this role

Instance

Background: Illustrate this pattern with a simple calculator < subtraction >

1. Create a factory where the class is generated by the operators that are passed in to generate the corresponding operations class

public class operationfactory {    public static operation  createoperation  (string operate)  {        operation  operation = null;        switch (operate)  {         case  "+":             operation = new operationadd ();             break;        case  "-":             operation = new operationsubtract () ;            break;         case  "*":             Operation = new&nBsp;operationmultiply ();            break;         case  "/":             operation = new operationdivide ();             break;        }         return operation;    }}

2. Define an abstract computing interface

Public interface Operation {//Gets the result of a two-digit calculation public int getresult (int numberone,int numbertwo);}

3. Each operation class to implement the Operation interface respectively

/** *  additive operations  *  @author  shengfenglai */public class OperationAdd  implements operation {     @Override     public int  GetResult (Int numberone, int numbertwo)  {         return numberone + numbertwo;    }}/** *  Subtraction Operations  *  @author  shengfenglai */public class OperationSubtract implements Operation {      @Override     public int getresult (int numberone, int  numbertwo)  {        return numberOne -  numbertwo;    }}/** *  multiplication Operation  *  @author  shengfenglai */public  class OperationMultiply implements Operation {     @Override     puBlic int getresult (Int numberone, int numbertwo)  {         return numberOne * numberTwo;    }}/** *  Division Operations  *  @author  shengfenglai */public class OperationDivide implements  operation {     @Override     public int getresult (int  numberone, int numbertwo)  {        int  Result = 0;        if (numbertwo != 0)  {             result = numberOne /  numbertwo;        }else {             throw new notbezeroexception ("Divisor cannot be 0");         }         return result;    }} 

4. Customize an exception to be thrown when the divisor is 0

public class Notbezeroexception extends RuntimeException {/** * */private static final long serialversion    UID = 9056463784173674087L;    Public notbezeroexception (String msg) {super (MSG); }}

5. Test class

Public class operationtest {    public static void main ( String[] args)  {        //test for add          Operation addOperation =  Operationfactory.createoperation ("+");        int addresult  = addoperation.getresult,         system.out.println ("1  + 2 =  " + addresult);         //test for  subtract        Operation subtractOperation =  Operationfactory.createoperation ("-");         int subtractresult  = subtractoperation.getresult (9,5);         System.out.println ("9 - 5 = "  + sUbtractresult);        //test for  multiply         Operation multiplyOperation =  Operationfactory.createoperation ("*");         int multiplyresult  = multiplyoperation.getresult (4,6);         System.out.println ("4 * 6 = "  + multiplyresult);         // test for divide        operation  divideoperation = operationfactory.createoperation ("/");         int divideresult = divideoperation.getresult (8,4);         //int divideresult = divideoperation.getresult (8,0);         system.out.println ("8 / 4 =  " + divideresult);     }} 

Pattern Benefits

The core of the pattern is the factory class, which contains the necessary judgment logic to decide when to create an instance of which product class, and the client can dispense with the responsibility to create the product object directly, but only to "consume" the product. The simple factory model realizes the division of responsibility.



Pattern disadvantage

1. Factory class Use static method as factory class, so there is no way to inherit the subclass, so there is no way to form the hierarchy of inheritance

2. Put multiple creation logic in a class, when the product class has different interface types, the factory class needs to determine when to create a product, making the system in the future to expand the function more difficult. Is that if else will be more and more, not conducive to maintenance

3. Only applicable to factory class is responsible for creating objects less


Simple Factory 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.