简体   繁体   English

工厂设计模式的实施

[英]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. 我正在为我的客户开发一个小应用程序,我试图在那里应用Factory Method设计模式。 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.). 基本上我有一个抽象类Scheme,它由具体的Schemes(AccountScheme,ContactScheme,OrderScheme等)扩展。 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). 每个类主要由实例变量和负责将Scheme转换为实际系统对象的方法组成(AccountScheme最终将用于创建Account,ContactScheme用于创建Contact等)。

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. 我还有一个SchemeFactory类,它有一个带有两个参数的静态方法createScheme - Scheme应该能够转换为AND JSON String的系统对象的类型,它将被解析为Scheme对象本身。

And finally there is a ApiService class which handles Rest Requests and uses the SchemeFactory to create Schemes (using request body). 最后有一个ApiService类来处理Rest Requests并使用SchemeFactory创建Schemes(使用请求体)。 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 我相信UML图(它是我的第一个)看起来像这样: UML Diagram

The concept is correct. 这个概念是正确的。

Your UML not show the abstract class. 您的UML不显示抽象类。 In your case, you can have something like this (as described in you UML): 在你的情况下,你可以有这样的东西(如你在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: 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: 如果您想强制Schemas使用json作为参数填充抽象类的构造函数,那么它很有用,但架构类仍然可以伪造,如:

public class FakeSchema extends AbstractSchema {

    public FakeSchema () {
        super(null);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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