使用单例类和应用程序范围的托管bean来保存应用程序数据有区别吗?
我需要查找某些JNDI资源,例如远程bean接口,因此我自己写了一个单例来缓存我的引用,只允许单引用.(服务定位)
我在两个不同的浏览器中打开了我的网站,而且这个单例只被初始化了一次.所以我假设它的应用范围?
应用程序范围托管bean的任何其他好处,然后能够访问其在jsf中的属性?
我有一个python脚本,我想只允许在一台机器上运行一次.我希望它打印像"错误,已经运行"的东西,如果它已经在运行,无论是在后台运行还是在不同的ssh会话中运行.我该怎么做?这是我的剧本.
import urllib, urllib2, sys
num = sys.argv[1]
print 'Calling'
phones = [
'http://phone1/index.htm',
'http://phone2/index.htm',
'https://phone3/index.htm',
'https://phone4/index.htm',
'https://phone5/index.htm'
]
data = urllib.urlencode({"NUMBER":num, "DIAL":"Dial", "active_line":1})
while 1:
for phone in phones:
try:
urllib2.urlopen(phone,data) # make call
urllib2.urlopen(phone+"?dialeddel=0") # clear logs
except: pass
Run Code Online (Sandbox Code Playgroud)
PS如果重要,我正在使用CentOS 5.
是否需要将synchronize关键字应用于实现单例模式的类的每个方法?
public class Singleton {
private Singleton(){}
public synchronized static Singleton getInstance()
{
if(instance == null)
instance = new Singleton ();
return instance;
}
public void DoA(){
}
}
Run Code Online (Sandbox Code Playgroud)
由于Singletons不公开公共构造函数并且getInstance()方法是同步的,因此不需要同步方法DoA和Singleton类公开的任何其他公共方法.
这个推理是否正确?
我想创建一个可以从我的应用程序中的所有点调用的Singleton类.问题是这个类需要一个操作的上下文.
我不想在每个活动中重新创建单例,因为这样就失去了所有意义,所以我考虑在我的MainActivity中创建它,使用init方法将上下文作为参数传递.从那时起,我的Singleton将是可用的,但我认为这是糟糕的设计,因为这样我的MainActivity引用将始终保持,因此我可能会遇到内存泄漏.
我在这儿吗?
随着斯威夫特,一个单初始化被称为两次运行XCTest单元测试时.
但是,没有Objective-C的问题,init()方法只按预期调用一次.
以下是构建两个测试项目的方法:
使用测试创建一个空的Objective-C项目.添加以下裸机单例:
#import "Singleton.h"
@implementation Singleton
+ (Singleton *)sharedInstance
{
static Singleton *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[Singleton alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
- (instancetype)init
{
self = [super init];
if (self) {
NSLog(@"%@", self);
}
return self;
}
@end
Run Code Online (Sandbox Code Playgroud)
在应用程序委托中添加对单例的调用,如下所示:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[Singleton sharedInstance];
return YES;
} …Run Code Online (Sandbox Code Playgroud) 根据C++ 单例设计模式, 我写了一个单例模板
template <typename T>
class Singleton
{
public:
static T& getInstance()
{
static T instance;
return instance;
}
protected:
Singleton() {}
~Singleton() {}
public:
Singleton(Singleton const &) = delete;
Singleton& operator=(Singleton const &) = delete;
};
Run Code Online (Sandbox Code Playgroud)
然后我写了一个 Logger 单例(第一个)
class Logger // not derived Singleton<Logger>
{
friend class Singleton<Logger>;
private:
Logger(){};
~Logger(){};
public:
void print(void){std::cout << "hello" << std::endl;}
};
int main(void)
{
Singleton<Logger>::getInstance().print(); // use Singleton<Logger>
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但我也可以(第二个)
class Logger:public Singleton<Logger> // derived Singleton<Logger> …Run Code Online (Sandbox Code Playgroud) 我知道我的一些 BLOC 在整个应用程序生命周期中只会被实例化一次。将这些 BLOC 类创建为单例是不好的做法还是反模式。Singleton 可以帮助在任何地方访问 BLOC,并确保该类仅实例化一次。
我还可以确保在另一个 BLOC 中使用一个 BLOC 并传递单例时是安全的,就好像它是“只是另一个”实现一样。
这样做可能会产生什么影响?
我有两个区块
AuthenTicationBloc 必须使用其中的 UserBloc。如果我将 UserBloc 设为单例,那么将其用作 UserBloc().
否则,我必须在 AuthenTicationBloc 中创建 UserBloc 作为实例变量,如下所示:
class AuthenTicationBloc {
UserBloc _userBloc;
AuthenTicationBloc({@required UserBloc userBloc}) : _userBloc = userBloc;
myMethod(){
//use the userBloc
_userBloc.setDetails();
}
}
runApp(
UserBloc userBloc = UserBloc();
Provider(
value: AuthenTicationBloc(userBloc: userBloc),
child: MyApp(),
),
);
Run Code Online (Sandbox Code Playgroud)
如果我必须在其他地方的小部件链中使用 UserBloc,我必须使 UserBloc 也按如下方式全局提供,对吗?
UserBloc userBloc = UserBloc();
MultiProvider(
providers: [
Provider<AuthenTicationBloc>(
value: AuthenTicationBloc(userBloc:userBloc),
), …Run Code Online (Sandbox Code Playgroud) 我有一个资源文件,其中有一些设置。我有一个 ResourceLoader 类,它从这个文件加载设置。这个类目前是一个急切实例化的单例类。这个类一加载,它就会从文件中读取设置(文件路径存储为另一个类中的常量字段)。其中一些设置不适合单元测试。例如,我在这个文件中有线程睡眠时间,对于生产代码来说可能是几个小时,但我希望单元测试是几毫秒。所以我有另一个测试资源文件,它有一组不同的值。我的问题是如何在单元测试期间用这个测试文件交换主资源文件?该项目是一个 maven 项目,我使用 testng 作为测试框架。这些是我的一些方法
使用@BeforeSuite 并修改FilePath 常量变量指向测试文件并使用@AfterSuite 将其指向原始文件。这似乎有效,但我认为因为 ResourceLoader 类被急切地实例化,不能保证 @BeforeSuite 方法总是在加载 ResourceLoader 类之前执行,因此可能会在文件路径更改之前加载旧属性。尽管大多数编译器仅在需要时才加载类,但我不确定这是否是 Java 规范要求。所以理论上这可能不适用于所有 Java 编译器。
将资源文件路径作为命令行参数传递。我可以在 pom.xml 的surefire配置中添加测试资源文件路径作为命令行参数。这似乎有点过分。
使用1.中的方法,让ResourceLoader延迟实例化。这保证如果在第一次调用 ResourceLoader.getInstance().getProperty(..) 之前调用 @BeforeMethod,ResourceLoader 将加载正确的文件。这似乎比前两种方法要好,但我认为使单例类延迟实例化会使其变得丑陋,因为我不能使用简单的模式,例如将其设为枚举等(如急切实例化的情况)。
这似乎是一个常见的场景,最常见的处理方式是什么?
我正在努力将这个改造类翻译成 Kotlin。它基本上是一个作为客户端工作的单例,我不确定我的 Kotlin 实现。UserAPI 和 ProfileAPI 只是接口。
public class RetrofitService {
private static final String BASE_URL = "https://test.api.com/";
private ProfileAPI profileAPI;
private UserAPI userAPI;
private static RetrofitService INSTANCE;
/**
* Method that returns the instance
* @return
*/
public static RetrofitService getInstance() {
if (INSTANCE == null) {
INSTANCE = new RetrofitService();
}
return INSTANCE;
}
private RetrofitService() {
Retrofit mRetrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build();
profileAPI = mRetrofit.create(ProfileAPI.class);
UserAPI = mRetrofit.create(UserAPI.class);
}
/**
* Method that returns …Run Code Online (Sandbox Code Playgroud) 我有一堂这样的课:
from __future__ import annotations
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
name: str
age: str
@staticmethod
def init() -> Config:
return Config(
name=...
age=...
)
Run Code Online (Sandbox Code Playgroud)
我想确保 init 方法始终返回相同的Config.
我可以通过这样做来实现这一目标:
@dataclass(frozen=True)
class Config:
name: str
age: str
@staticmethod
def init() -> Config:
if not _private_instance:
global _private_instance = Config(
name=...
age=...
)
return _private_instance
_private_instance: Optional[Config] = None
But I am wondering if there is a more Pythonic way of doing this. Thanks
Run Code Online (Sandbox Code Playgroud)