gpt4 book ai didi

java - 从接口(interface)创建全局唯一对象

转载 作者:行者123 更新时间:2023-12-01 12:36:17 26 4
gpt4 key购买 nike

这更多的是一个架构问题。我希望在我的项目中有一个全局对象,每个需要它的类都可以访问它,但不需要每次都创建它的实例。对象本身是不同服务的组合。我的第一种方法是定义一个接口(interface),在该接口(interface)中实例化对象,然后只需说 implements 即可将其注入(inject)到每个类中。我想知道的是,这种方法是干净的还是有点hacky或者真的很恶心。这是我到目前为止的实现:

public final class SystemServices
{
private final SecurityService securityService;
private final PersistencyService persistencyService;
private final RecordService recordService;
private final DispatcherService dispatcherService;

private SystemServices(Builder builder)
{
this.securityService = builder.securityService;
this.persistencyService = builder.persistencyService;
this.recordService = builder.recordService;
this.dispatcherService = builder.dispatcherService;
}

public SecurityService getSecurityService()
{
return securityService;
}

public PersistencyService getPersistencyService()
{
return persistencyService;
}

public RecordService getRecordService()
{
return recordService;
}

public DispatcherService getDispatcherService()
{
return dispatcherService;
}

public static class Builder
{
private SecurityService securityService;
private PersistencyService persistencyService;
private RecordService recordService;
private DispatcherService dispatcherService;

public Builder setSecurityService(SecurityService securityService)
{
this.securityService = securityService;
return this;
}

public Builder setPersistencyService(PersistencyService persistencyService)
{
this.persistencyService = persistencyService;
return this;
}

public Builder setRecordService(RecordService recordService)
{
this.recordService = recordService;
return this;
}

public Builder setDispatcherService(DispatcherService dispatcherService)
{
this.dispatcherService = dispatcherService;
return this;
}

public SystemServices build()
{
return new SystemServices(this);
}
}
}

这是创建 SystemServices 实例的接口(interface):

public interface ServiceProvider
{
public static SystemServices systemServices = new SystemServices.Builder()
.setSecurityService(new SecurityService())
.setPersistencyService(new PersistencyService(new BlackBoxDb(BlackboxApplication.getAppContext())))
.setRecordService(new RecordService()).setDispatcherService(new DispatcherService()).build();
}

现在我只需使用 systemServices.getSecurityService.doSomethingSecurityRelated() 即可访问每个类中的对象

该代码可以工作,并且对于我这个初学者来说似乎太好了,但我确信这种方法有一些丑陋的地方。所以任何批评都是值得赞赏的:)另外,JVM 如何处理接口(interface)也很有趣。它真的只是一个(一吨)对象还是为每个类创建一个对象?

最佳答案

JVM 会按照你想要的方式处理接口(interface),只会创建一个 SystemServices。但你所描述的方法确实被认为是“丑陋的”。我认为最好的方法是使用像 Spring 这样的依赖注入(inject)框架。它非常擅长满足您的需求——拥有其他类可以访问的全局对象。它还使测试变得更加容易,并且还使您能够快速更改应使用的全局对象。

关于java - 从接口(interface)创建全局唯一对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25555540/

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