简体   繁体   English

基于单个值使用不同的类

[英]Use of different classes based on a single value

I'm developing an application that should use different class types based on a single piece of information. 我正在开发一个应该根据单条信息使用不同类类型的应用程序。 To better illustrate my question, let me give an example: 为了更好地说明我的问题,让我举一个例子:

suppose INFO is a boolean value. 假设INFO是一个布尔值。 Based on its value, my code must use either instances of some class A , or some class B . 根据其值,我的代码必须使用某些类A实例或某些类B Note that for every A , B is its subclass. 请注意,对于每个AB是它的子类。 INFO is set when the application starts and it's not changed throughout the app lifecycle. INFO在应用程序启动时设置,并且在整个应用程序生命周期内不会更改。

My question: what's the most optimal way to implement this ? 我的问题: 实现这一目标的最佳方式是什么?

Here are some approaches I've come up with, but feel free to suggest others: 以下是我提出的一些方法,但随意建议其他人:

1. Factory class with methods: 1.工厂类的方法:

public static A getA(final boolean INFO) {
    return INFO ? new A() : new B();
}

2. Wrapper classes: 2.包装类:

class WrapperForSomeClass {

    public final A instance;

    public WrapperForSomeClass(final boolean INFO) {
        instance = INFO ? new A() : new B();
    }

}

3. Interface + Factory class: 3.接口+工厂类:

public interface IWrappable<T> {
    T get(final boolean INFO);
}

private static final IWrappable<A> WRAPPER_FOR_A = new IWrappable<A>() {
    public A get(final boolean INFO) {
        return INFO ? new A() : new B();
    }
};

public static A getA(final boolean INFO) {
    return WRAPPER_FOR_A.get(INFO);
}

If I had to choose, I'd go with no.3. 如果我不得不选择,我会选择3号。 What say ye? 你说什么?

I would do it as follows: 我会这样做:

class A
{
}

class B extends A
{
}

class AFactory
{
    public A getInstance(boolean info) 
    {
        return info ? new A() : new B();
    }
}

class MyMainLauncher
{
    private AFactory aFactory;
    private A instance;

    {
        // has access to the boolean value `info`.
        instance = aFactory.getInstance(info);
    }
}

1 is shortest and cleanest. 1是最短和最干净的。 Place this method into A class, in order not to create redundant factory class. 将此方法放入A类中,以便不创建冗余工厂类。

Why you'd go for 3? 你为什么要去3? It does the same, but with a lot more code. 它也是如此,但代码更多。

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

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