实例化其他项目的类

问题描述 投票:0回答:1

我在项目a中有MyClassA。

package com.testa

public class MyClassA {

    private Data data;

    public data setData() {
        this.data = data;

    public Data getData() {
        return data;
    }
}

Data是项目a中声明的接口。

在项目 b 中我有特殊数据,例如:

package com.testb

public class SpecialData extends Data {
   // ...
}

项目 b 依赖于 a,但反过来则不然,因此 MyClassA 无法直接实例化 SpecialData。

我想重构 MyClassA 以摆脱设置器并实例化正确的数据惰性,例如:

    public Data getData() {
        if (data != null) {
            return data;
        }
        if (projectB.isEnabled) {
            return //somehow SpecialData
        }
        throw new IllegalStateException();
    }

有什么办法可以做到吗?我缺少任何设计模式吗?

java design-patterns
1个回答
0
投票

这是使用泛型的方法:

public class MyClassA<T extends Data> {
    private final T data;  // make it immutable

    public MyClassA(T data) { // add constructor
       this.data = data;
    }

    // return generic type
    public T getData() {
        return data;
    }
}

然后使用:

var withBasicData = new MyClassA<>(new Data());
var withSpecialData = new MyClassA<>(new SpecialData());

// compilation error as expected since the generic type is limited
var withSomethingElse = new MyClassA<>(Integer.valueOf(42));
© www.soinside.com 2019 - 2024. All rights reserved.