Java 类内部方法公共参数应该怎么处理

2019-04-16 19:21:56 +08:00
 yonats

求问,像这种多个内部方法都有相同参数 config,有没有办法做一些抽取,让 fun1/2/3/4 只保留自己的参数,总觉得每个方法参数都有 config 蛮蠢的。。。

================================================================

import org.springframework.stereotype.Component;

@Component public class TestService {

public void handle() {

    Config config = init();

    fun1(config, 1); 
    fun2(config, "t"); 
    fun3(config, 0D); 
    fun4(config); 
}

private Config init() {
    // ...
}

private void fun1(Config config, Integer i) {
    // ...
}

private void fun2(Config config, String s) {
    // ...
}

private void fun3(Config config, Double d) {
    // ...
}

private void fun4(Config config) {
    // ...
}

}

2123 次点击
所在节点    Java
16 条回复
ywcjxf1515
2019-04-16 19:26:13 +08:00
在 fun1 到 fun4 里直接用实例变量 config。
ywcjxf1515
2019-04-16 19:30:05 +08:00
看错了,config 不是实例变量。。
Mistwave
2019-04-16 19:30:05 +08:00
self.config = init()
Mistwave
2019-04-16 19:30:33 +08:00
不好意思 Java 是 this
lhx2008
2019-04-16 19:33:35 +08:00
没看懂,Spring 注入不行吗
zhongchengyong
2019-04-16 19:33:42 +08:00
是否可以:声明为成员变量,在 handle()中初始化该成员变量,然后在各个 funx()中使用
yonats
2019-04-16 19:36:51 +08:00
@zhongchengyong
@ywcjxf1515
@Mistwave
声明成员变量并发会导致 a 读到 b 的 config 吧
yonats
2019-04-16 19:38:41 +08:00
@lhx2008 对的,new 出来应该可以用 config 做成员变量,注入就不行了...
lhx2008
2019-04-16 19:41:00 +08:00
@yonats init() 函数带一个 @bean 就可以注入了,不过是单例的,如果是多个 config 切换,也可以配置一下 bean name,不过每次启动就只有一个 config 就是了
lhx2008
2019-04-16 19:42:53 +08:00
↑ 每个函数只能用一个 config,具体你可以重新设计一下类的结构,不知道你的需求
yonats
2019-04-16 19:46:01 +08:00
@lhx2008 是这样的,config 是从缓存中拿到的一些配置,每次请求 handle 获取的配置可能都不一样,不应该叫 init 应该是 getConfig 这个样子
zhongchengyong
2019-04-16 19:46:49 +08:00
@yonats init()返回新的 config 对象不会出现你说的问题吧?你详细说一下?
yonats
2019-04-16 19:47:11 +08:00
@lhx2008 这个 getConfig 还有一些参数是 handle 透传过来的
twoyuan
2019-04-16 19:47:18 +08:00
柯里化 🌚
lhx2008
2019-04-16 19:49:25 +08:00
@yonats 一个办法是另外开定时任务去更新 config,但是如果 config 是随机的,好像是没有什么办法,用 new 有点脏。
mskf
2019-04-16 19:51:00 +08:00
可以写一个内部类
```
private void handle(){
Funs funs = new Funs(config);
funs.fun1(i);
...
}
private class Funs{
private Object config;
Funs(config){
this.config = config
}
fun1(Integer i)...
fun2(String s)...
}
```
如果方法是公有的还可以用类似反射来写,比较接近动态语言的方式,或者用注解注入

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/555792

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX