针对Android HILT SingletonComponent的设计模式,可以采用以下示例的方式实现:
@Singleton
@Component
public interface AppComponent {
// ...
}
@Module
@InstallIn(ApplicationComponent.class)
public class AppModule {
@Singleton
@Provides
public SomeSingletonObj provideSomeSingletonObj() {
return new SomeSingletonObj();
}
}
public class SomeSingletonObj {
// ...
}
而对于GoF Singleton instance设计模式的实现,可以采用以下示例的方式实现:
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}