gpt4 book ai didi

java - 设计模式只返回对象中的某些 LDAP 属性

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:44:20 25 4
gpt4 key购买 nike

假设我有以下类,有许多实例变量和相应的 getter 和 setter:

public class Foo {
private String a;
private int b;
...
private List<String> z;

public String getA() { return a; }
public void setA(String a) { this.a = a; }
public int getB() { return b; }
public void setB(int b) { this.b = b; }
...
}

还有另一个填充值的类,它是资源密集型的:

public class MyService {

public Foo retrieveFoo() {
// call some resource intensive code to retrieve the values
String a = getTheString();
int b = getTheInt();
List<String> z = getTheList();

Foo f = new Foo();
f.setA(a);
f.setB(b);
...
f.setZ(z);

return f;
}

}

我有多个客户想要使用上述类的实例,但有些客户只对获取变量值的一小部分感兴趣,而不是全部:

public class ClientA {
private MyService service;

public void doSomething() {
Foo f = service.retrieveFoo();
String a = f.getA();
int b = f.getB();
// not interested in anything else
}
}

public class ClientB {
private MyService service;

public void doSomething() {
Foo f = service.retrieveFoo();
List<String> z = f.getZ();
// not interested in anything else
}
}

我可以做的一件事是让客户端告诉 MyService 只检索它感兴趣的值。像这样:

public class ClientA {
private MyService service;

public void doSomething() {
// the Service would only retrieve a and b, which
// means all other variables would be set to Null
Foo f = service.retrieveFoo(Arrays.asList("a","b"));
String a = f.getA();
int b = f.getB();
// not interested in anything else
}
}

但是,这似乎是错误的,因为其他值将为空。有没有更好的设计方法?

编辑:

更具体地说,我在 LDAP 系统中处理用户属性。我不想拥有一个人的所有属性的“上帝对象”,我只想拉回每个用例所需的子集。例如,一个应用程序可能需要 uid 和 fullName;另一个可能需要 uid、电话号码、组等。

谢谢。

最佳答案

一个最简单的解决方案是使用不同的 getter 集声明多个接口(interface),在您的类中实现所有接口(interface),并让不同的客户端使用不同的接口(interface)。

例如

interface A {
String getA();
}

interface B {
String getB();
}

class MyClass implements A, B {
String getA() {...}
String getB() {...}
}

现在客户端A使用接口(interface)A,只能调用getA(),而客户端B使用接口(interface)B,只能调用getB()

如果某些客户端 C 必须与 A 和 B 一起操作,您可以:1.让它访问两个接口(interface)2.直接访问MyClass3. 定义扩展A 和B 的其他接口(interface)C,以便客户端C 可以使用它。

显然这个解决方案不是通用的,在某些情况下可能需要定义很多接口(interface)。

如果您想灵活地决定客户端可以在运行时访问的功能集,您可以使用接口(interface),但不在您的类中实现它们,而是使用动态代理来包装您的类并公开所需的接口(interface)。但是,由于反射调用,此解决方案的工作速度会变慢。

我可以考虑其他解决方案,但我希望这里已经写的对你来说足够好。

关于java - 设计模式只返回对象中的某些 LDAP 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30622401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com