在Jon的网站上,他在C#中使用了这个优雅设计的单例,如下所示:
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何在C++中编写等效代码?我有这个,但我不确定它是否实际上具有与Jon相同的功能.(顺便说一下,这只是一个星期五的练习,不需要任何特别的东西).
class Nested;
class Singleton
{
public:
Singleton() {;}
static Singleton& Instance() { return Nested::instance(); }
class Nested
{
public:
Nested() {;}
static Singleton& instance() { …Run Code Online (Sandbox Code Playgroud) 我正在思考编写单例类的其他方法.那么这个类被认为是一个单例类吗?
public class MyClass{
static Myclass myclass;
static { myclass = new MyClass();}
private MyClass(){}
public static MyClass getInstance()
{
return myclass;
}
}
Run Code Online (Sandbox Code Playgroud)
因为静态块只运行一次.
我一直想知道在什么情况下在objective-C中采用单例模式是非常必要的(例如,定义一个专用类并创建一个单独的实例),使用类作为对象是不行的.
特别是,我正在考虑以下解决方案:
static变量(文件范围全局变量),而不是单例实例的实例变量;例如,而不是一个Texture类(模型对象)和一个TextureManager单(资源管理器),你可以有作为类的方法和相同的静态变量实现的所有纹理制作/清除Texture类(工厂模式加上一些资源管理).
有关这个设计的任何想法?
编辑:
现在我想到了它,仍然在Texture上面的例子中,即使我将这两个类分开(Texture和TextureManager)我必须在A之间做出选择.让经理成为单身人士,并使用实例方法或B.让经理成为无实体的辅助类.澄清:
Texture* myTexture = [[TextureManager defaultManager] textureWithName:@"TextureName"];
// (singleton, client uses instance methods)
Run Code Online (Sandbox Code Playgroud)
与
Texture* myTexture = [TextureManager textureWithName:@"TextureName"];
// (Class standing in for singleton, client uses class methods)
Run Code Online (Sandbox Code Playgroud)
后者看起来更直接,不那么繁琐/冗长,但我想知道哪种设计"更正确".当然,前者允许TextureManager出现不止一个实例(不是在我的情况下).
以下代码是否有助于延迟初始化?
或者singletonInstance只要有人包含标题(甚至在程序启动时),就会创建?
class SingletonClass
{
private:
SingletonClass();
~SingletonClass();
public:
static const SingletonClass& Instance()
{
static SingletonClass singletonInstance;
return singletonInstance;
}
};
Run Code Online (Sandbox Code Playgroud) 下面是一个非常流行的JavaScript Singleton模式实现的示例:
var mySingleton = (function() {
var instance;
function init() {
function privateMethod() {
console.log("I am private");
}
var privateVariable = "Im also private";
var privateRandomNumber = Math.random();
return {
publicMethod: function() {
console.log("The public can see me!");
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
Run Code Online (Sandbox Code Playgroud)
我已经考虑了一段时间,当我们用这个简单的代码实现相同的结果时,我并不真正理解这种复杂性的需要:
singleton = (function() {
var obj = {
someMethod: …Run Code Online (Sandbox Code Playgroud) 我正在深入研究Angular 2中的DI.我正在使用泛型子类型实现一个REST-Client,用于具体的数据类型,如下所示:
class RESTClient<T>{
constructor() {
var inj = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
this.http = inj.get(Http);
this.conf = RESTConfiguration;
}
}
class BookClient extends RESTClient<Book>{
constructor(){
// since I dont want to inject the HTTP Providers here, I'm using a custom injector in the super class
super();
}
}
class WriterClient extends RESTClient<Writer>{
...
...
}
Run Code Online (Sandbox Code Playgroud)
据我所知,在超类REST-Service注入的所有RESTClient之间将共享一个http服务.
现在我希望有一个RESTConfiguration类:
@Injectable()
export class RESTConfiguration {
get baseURL() {
return this._baseURL;
}
set baseURL(value) {
alert("sets value to"+value);
this._baseURL = value;
}
private _baseURL;
}
Run Code Online (Sandbox Code Playgroud)
它应该在主应用程序中配置如下: …
我需要一个处理我的SharedPreferences的类,我想出了3种方法,但经过一些研究后,似乎大多数都被认为是"反模式".
输入1
public final class MyPrefs {
private MyPrefs(){ throw new AssertionError(); }
public static void setFavoriteColor(Context context, String value){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putString("color_key", value).apply();
}
public static void setFavoriteAnimal(Context context, String value){
// ...
}
// ...
}
/* Usage */
MyPrefs.setFavoriteColor(this, "yellow");
// Reason why it might be considered "Bad"
// Class is not OO, just collection of static methods. "Utility Class"
Run Code Online (Sandbox Code Playgroud)
类型2
public class MyPrefs {
private SharedPreferences mPreferences;
private static volatile MyPrefs sInstance;
public static …Run Code Online (Sandbox Code Playgroud) 两种情况:
1. Session data - For example the logged in User details, or some other session data.
2. Global/stateless data - A repository with retrofit client.
Run Code Online (Sandbox Code Playgroud)
对于情况 1:最简单的方法是使用某种单例 "DataManager/LoginManger" ,但单例很糟糕(测试,随着时间的推移状态不可预测......)另一种方法是使用 Application 类,这也是坏的。
那么我们在哪里存储这些数据呢?
对于案例 2:一个简单的存储库,其中包含对 Retrofit 客户端或其他客户端的引用。
使用它作为单例更有意义,因为这个类是不可变的/无状态的。我们只想创建一次改造客户端。但是.. 测试?
3 . 另外,如果我们想获取 location 怎么办?我们可以在 ViewModel 中使用 LiveData 来负责。但是 ViewModel 的范围是某个视图/活动。所以这意味着如果我们更改视图(例如从抽屉中输入设置,而主页的视图模型正在获取位置),一旦检索到位置数据,我们将丢失位置数据,然后当用户返回主页时,我们不仅要向他们显示位置,还必须重新请求位置。
我还没有找到任何方式来处理所有这些情况。似乎没有明确的答案。
我开始开发的 FastAPI 应用程序使用了多个服务,我只想在应用程序启动时初始化一次这些服务,然后在不同的地方使用该对象的方法。
它可以是云服务或任何其他重型服务。
可能的方法是使用Lazy loading和 with来实现Singlenton pattern,但我正在寻找更好的 FastAPI 方法。
另一种可能的方法是使用Depends类并缓存它,但它的使用仅对路由方法有意义,而对从路由方法调用的其他常规方法则无效。
例子:
async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
async def non_route_function(commons: dict = Depends(common_parameters)):
print(commons) # returns `Depends(common_parameters)`
@router.get('/test')
async def test_endpoint(commons: dict = Depends(common_parameters)):
print(commons) # returns correct dict
await non_route_function()
return {'success': True}
Run Code Online (Sandbox Code Playgroud)
还可以使用@app.on_event("startup")事件来初始化重类,但不知道如何使这个初始化的对象可以从每个地方访问,而不使用singleton.
另一种丑陋的方法是将初始化的对象保存到 @app( 中,然后从请求中获取此应用程序,但随后您必须传递request到每个非路由函数中。
我描述的所有方法要么是丑陋的、不方便的、非Pythonic的,要么是更糟糕的实践,我们这里也没有像flask中那样的线程局部变量和代理对象,那么对于我描述的此类问题的最佳方法是什么多于?
谢谢!
我什么时候应该更喜欢一个?下面显示的方法的目的是什么?
class A {
public static A newInstance() {
A a = new A();
return a ;
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释这两个电话之间的区别吗?
singleton ×10
android ×3
java ×3
c++ ×2
angular ×1
c# ×1
factory ×1
fastapi ×1
gang-of-four ×1
global ×1
javascript ×1
mvvm ×1
objective-c ×1
preferences ×1
python ×1
typescript ×1