草庐IT

java - 没有 switch 语句的 Java 工厂

coder 2024-03-10 原文

我正在尝试构建一个工厂对象,但无法找到在 Java 中执行此操作的好方法。

我正在编写的应用程序用于处理各种格式的文件,因此有一个 CodecInterface 适用于所有用于读取和写入文件的类。让我们假设它定义了以下方法。这些文件中的每一个都有一个唯一的人为指定的 ID 字符串,用于识别编码器\解码器。

String read();
void write(String data);
String getID();

工厂类将有一个 create 方法,用于创建这些编解码器类的实例。我想方法签名看起来像这样。
static CodecInterface CodecFactory.create(String filename, String codecid, String args);

filename 是要读/写的文件的名称,codecid 是唯一 ID,指示要使用的编解码器。 args 参数是传递给正在生成的解码器/编码器对象的参数字符串。 this 的返回应该是请求的编解码器对象的实例。

我见过的所有工厂示例通常在 create 方法中都有一个 switch 语句,该语句创建一个依赖于 ID 的对象实例。我想避免这样做,因为它似乎不是“正确”的方式,这也意味着列表或多或少是固定的,除非您修改 create 方法。理想情况下,我想使用类似字典(由编解码器 ID 索引)之类的东西,其中包含可用于创建我想要的编解码器类的实例(我将这个神秘类称为 ClassReference)的东西。再次使用一些准 java 代码,这里是我认为的 create 方法的主体。
static Dictionary<String, ClassReference>;

static CodecInterface CodecFactory.create(String filename, String codecid, String args);
{
    ClassReference classreference;

    classreference = codeclibrary(codecid);

    return classreference.instanceOf(args);
}

ID 的字典很简单,但我不知道 ClassReference 应该是什么。类引用应该允许我创建所需类的实例,如上例所示。

从网上环顾四周,类方法和 instanceOf 似乎朝着正确的方向前进,但我没有找到将两者结合在一起的任何东西。作为一个额外的复杂因素,正在创建的对象的构造函数将具有参数。

关于我应该看什么的任何提示将不胜感激。

提前致谢。

解决方案

谢谢大家的建议。我最终从您的所有建议中汲取了点点滴滴,并提出了以下似乎可以正常工作的建议。

请注意,我省略了大部分健全性\错误检查代码来展示重要的部分。
import java.lang.reflect.Constructor;
import java.util.HashMap;

public class CodecFactory
{
    private static HashMap<String, Class<? extends CodecInterface>> codecs;

    static
    {        
        codecs = new HashMap<String, Class<? extends CodecInterface>>();

        //Register built-in codecs here
        register("codecA", CodecA.class);
        register("codecB", CodecB.class);
        register("codecC", CodecC.class);
    }

    public static void register(String id, Class<? extends CodecInterface> codec)
    {
        Class<? extends CodecInterface> existing;

        existing = codecs.get(id);        
        if(existing == null)
        {
          codecs.put(id, codec);
        }
        else
        {
          //Duplicate ID error handling
        }
    }

    public static CodecInterface create(String codecid, String filename, String mode, String arguments)
    {
        Class<? extends CodecInterface> codecclass;
        CodecInterface codec;
        Constructor constructor;

        codec = null;

        codecclass = codecs.get(codecid);
        if(codecclass != null)
        {
          try
          {
            constructor = codecclass.getDeclaredConstructor(String.class, String.class, String.class, String.class);
            codec = (CodecInterface)(constructor.newInstance(codecid, filename, mode, arguments));
          }
          catch(Exception e)
          {
            //Error handling for constructor/instantiation
          }
        }

        return codec;
    }
}

最佳答案

尝试这样的事情:

public class CodecFactory {
    final private static Map<String, Class<? extends CodecInterface>> codecLibrary;

    static {
        codecLibrary = new HashMap<String, Class<? extends CodecInterface>>();
        codecLibrary.put("codec1", Codec1.class);
        //...
    }

    static CodecInterface create(String filename, String codecid, String args) throws InstantiationException, IllegalAccessException {
        Class<? extends CodecInterface> clazz;

        clazz = codecLibrary.get(codecid);

        CodecInterface codec = clazz.newInstance();

        codec.setArgs(args);
        codec.setFilename(filename);

        return codec;
    }
}

关于java - 没有 switch 语句的 Java 工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22314256/

有关java - 没有 switch 语句的 Java 工厂的更多相关文章

  1. ruby-on-rails - Railstutorial : db:populate vs. 工厂女孩 - 2

    在railstutorial中,作者为什么选择使用这个(代码list10.25):http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-usersnamespace:dbdodesc"Filldatabasewithsampledata"task:populate=>:environmentdoRake::Task['db:reset'].invokeUser.create!(:name=>"ExampleUser",:email=>"example@railstutorial.org",:passwo

  2. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  3. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  4. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  5. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  6. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  7. 没有类的 Ruby 方法? - 2

    大家好!我想知道Ruby中未使用语法ClassName.method_name调用的方法是如何工作的。我头脑中的一些是puts、print、gets、chomp。可以在不使用点运算符的情况下调用这些方法。为什么是这样?他们来自哪里?我怎样才能看到这些方法的完整列表? 最佳答案 Kernel中的所有方法都可用于Object类的所有对象或从Object派生的任何类。您可以使用Kernel.instance_methods列出它们。 关于没有类的Ruby方法?,我们在StackOverflow

  8. ruby - 如何在 Ruby 中向现有方法定义添加语句 - 2

    我注意到类定义,如果我打开classMyClass,并在不覆盖的情况下添加一些东西我仍然得到了之前定义的原始方法。添加的新语句扩充了现有语句。但是对于方法定义,我仍然想要与类定义相同的行为,但是当我打开defmy_method时似乎,def中的现有语句和end被覆盖了,我需要重写一遍。那么有什么方法可以使方法定义的行为与定义相同,类似于super,但不一定是子类? 最佳答案 我想您正在寻找alias_method:classAalias_method:old_func,:funcdeffuncold_func#similartoca

  9. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

  10. ruby-on-rails - 有没有办法为 CarrierWave/Fog 设置上传进度指示器? - 2

    我在Rails应用程序中使用CarrierWave/Fog将视频上传到AmazonS3。有没有办法判断上传的进度,让我可以显示上传进度如何? 最佳答案 CarrierWave和Fog本身没有这种功能;你需要一个前端uploader来显示进度。当我不得不解决这个问题时,我使用了jQueryfileupload因为我的堆栈中已经有jQuery。甚至还有apostonCarrierWaveintegration因此您只需按照那里的说明操作即可获得适用于您的应用的进度条。 关于ruby-on-r

随机推荐