简体   繁体   中英

Implementation of the Factory Design Pattern

I am developing a small application for my client and I tried to apply there Factory Method design pattern. I am not sure if I have done it correctly.

Basically I have an abstract class Scheme that is extended by concrete Schemes (AccountScheme, ContactScheme, OrderScheme etc.). Each class consists mainly of instance variables and a method responsible for transforming Scheme into actual system object (AccountScheme will be used eventually to create Account, ContactScheme to create Contact and so on).

I also have SchemeFactory class which has a static method createScheme taking two parameters - type of system object the Scheme should be able to transform into AND JSON String which will be parsed into the Scheme object itself.

And finally there is a ApiService class which handles Rest Requests and uses the SchemeFactory to create Schemes (using request body). The schemes are processed after that and at certain point if needed particular System Objects is created (using scheme) and inserted to database.

I believe the UML diagram (it is my first one) would look something like that: UML Diagram

The concept is correct.

Your UML not show the abstract class. In your case, you can have something like this (as described in you UML):

class SchemaFactory
{
  public static Schema getSchema(String type, String json)
  {
    if ( type.equals("account") )
      return new AccountSchema(json);
    else if ( type.equals("contact") )
      return new ContactSchema(json);
    else if ( type.equals("order") )
      return new OrderSchema(json);

    throw new IllegalArgumentException();
  }
}

The interface:

interface Schema {

}

The implementation of AccountSchema:

class AccountSchema implements Schema {
    AccountSchema(String json) {
        //use json
    }
}

The abstract class is optional for the pattern. It's useful if you would like to force that the Schemas fill the constructor of abstract class with json as parameter, but the schema class can still fake, like:

public class FakeSchema extends AbstractSchema {

    public FakeSchema () {
        super(null);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM