可以使用单在C#中的非默认构造函数? [英] Possible to use a singleton with a non-default constructor in C#?

查看:173
本文介绍了可以使用单在C#中的非默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我执行我的一个项目的通知框架。正如我想这是很普通的,用户可以使用多个传输层,让他并不真正需要关心使用一种交付方法(可以说WCF)或其他(如用于ActiveMQ的)。 B中的接口,用户可以访问$ B $当然是独立于传送方式(WCF或ActiveMQ的)的。
尽管如此,两班(消费者和生产者)实现了单身,所以他们实际使用默认的构造函数(意思是,没有参数)。
我的问题是,我想有一个参数,交货方式,用户希望使用。
但据我所知,单只使用默认的构造函数?这是正常的,因为应该没有使用与单身参数的点。
那么,什么是我选择这里?不创建一个单身?创建设置传递方法的方法?

I'm implementing a notification framework for one of my projects. As i want it to be very generic, the user can use several transport layers, so that he doesn't really need to care about using one delivery method (lets say WCF) or another (for eg ActiveMQ). The interface the user has access is of course independent of the delivery method (WCF or ActiveMQ). Still, the two classes (consumer and producer) implements singletons, so they actually use default constructors (meaning, no parameters). My problem is that i would like to have one parameter, the delivery method the user want to use. But as far as i know, singleton only use default constructors? which is normal, as there should be no point of using singletons with parameters. So, what are my options here? not to create a singleton? create a method to set the delivery method?

塞巴斯蒂安

推荐答案

您当然可以有单身的参数,除了没有传递参数到构造函数时,它传递到的getInstance()方法。你重写的构造函数必须是私有的,当然一个真正的单身执行。我的例子是用Java编写的,但适用于C#以及

You can certainly have parameters with singletons, except instead of passing the parameter into a constructor, you are passing it into the getInstance() method. Your overridden constructor needs to be private of course for a true singleton implementation. My example is written in Java but applies for C# as well.

例如:

Singleton s = Singleton.getInstance(42);

在辛格尔顿代码:

private Singleton() {

}

private Singleton(int num) {
   //set num
}

public getInstance(int num) {
  //singleton code (calls the private non-default constructor if an object 
  //does not already exist) 
}

这篇关于可以使用单在C#中的非默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆