We all know about the singleton pattern.
How do you implement a singleton "method"? - a method that is called only once and any other call will do nothing.
I can think a few ways (including Lazy - if (!.IsValueCreated) {... value.method();}) but how would you implement it?
I don't think so there is something like a singleton method.
If you want your method to do execute the block of code only once then you can do that. This can be done in several ways, one of them could be as follows-
public class Foo
{
private static bool _isInitialied;
public void Initialize()
{
if(_isInitialied)
return;
//TODO: Initialization stups.
_isInitialied = true;
}
}
You could achieve this using actions:
public class Test
{
private Action _action;
private void DoSomething()
{
// Do something interesting
_action = DoNothing;
}
private void DoNothing()
{
}
public Test()
{
_action = DoSomething;
}
public void Call()
{
_action();
}
} // eo class Test
Related
I am currently using Moq, but could use another framework if it's easier.
I want to test a class looking like this:
using System.Threading;
public class Foo
{
[SerializeField]
private Thread thread = new Thread(new ThreadStart(ThreadProc));
public static void ThreadProc()
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(0);
}
}
public Foo()
{
}
public virtual void Interrupt()
{
if (thread.IsAlive)
{
thread.Interrupt();
}
}
}
Now I want to test the Intertupt method. In order to do so I want to Mock the thread member in order to verify that the Intetrupt method is hit depending of the IsAlive value.
How can I mock it ?
PS: This is not my real code, this is simply an example as I cannot post my real code. However the issue I have is the same, I need to have a class constructor to return an object when called.
An admittedly ugly way of getting around this is to change the protection level of thread from private to protected, then have the testing class inherit from the class under test. Based on the example code you've provided, it would look something like this:
public class Foo
{
[SerializeField]
protected Thread thread = new Thread(new ThreadStart(ThreadProc));
...
}
public class FooUnitTests: Foo {
private readonly Mock<Thread> threadMock = new Mock<Thread>();
[TestMethod]
public void Interrupt_ThreadIsAlive_CallsThreadInterrupt() {
threadMock.SetUp(m => m.IsAlive).Returns(true);
threadMock.SetUp(m => m.Interrupt()).Verifiable();
Interrupt();
threadMock.VerifyAll();
}
public FooUnitTests {
thread = threadMock.Object;
}
}
I want to make a data class that will contain some information and provide an event to work with that information.
public abstract class EventData<T> where T : EventData<T>
{
Action<T> action_;
public void Subscribe(Action<T> _actor) { action_ += _actor; }
public void Unsubscribe(Action<T> _actor) { action_ -= _actor; }
public void Dispatch(T _data) { if (action_ != null) action_(_data); }
}
public class ConcreteEventData : EventData<ConcreteEventData>
{
int arg1;
string arg2;
}
So, I forced to use that uncomfortable construction ConcreteEventData : EventData<ConcreteEventData> instead of simple and short ConcreteEventData : EventData even if I keep in mind that I would use the same type as I've described.
Moreover, if someone will use that base class, he may write something like:
public class AnotherConcreteEventData : EventData<ConcreteEventData>
{
float arg1;
bool arg2;
}
As you can see, it is not a good way to use that idea, is there another one to use it more elegance?
Ok, solution was quite simple. Instead of making a class for my "event", i could simple use EventArgs as data class with no event needed.
My goal was use it for EventBus, so instead of doing stuff like
public abstract class EventData<T> where T : EventData<T>
{
Action<T> action_;
public void Subscribe(Action<T> _actor) { action_ += _actor; }
public void Unsubscribe(Action<T> _actor) { action_ -= _actor; }
public void Dispatch(T _data) { if (action_ != null) action_(_data); }
}
public class EventBus
{
static Dictionary<string, EventData> _dict;
}
(moreovere, i cannot do that and i could be forced to find a solution for that problem too)
I can simply use
public class EventBus<T> where T : EventArgs
{
static Dictionary<string, Action<T>> list;
public static void SubscribeOnEvent(string _sid, Action<T> _method)
{
// Do Stuff...
}
}
And use it in the way like
EventBus<MyData>.Subscibe("myID", (data) => { /*Do stuff...*/ });
And now i can use all the data, derived from EventArgs. Thanks to #JeroenMostert for the idea.
I have a method A which call another method B. Upon clicking on a button, method A is called which in turn calls method B. However, when 2 users click on the button simultaneously, I want only one user to access method B while the other waits for method B to complete. I thought of doing it this way:
private static Object _Lock = new Object();
private void A(){
lock(_Lock){
B();
}
}
The users are on different machines. The project is a web site.
But I think this is not correct. How can I improve the above code so that it is the proper way to work?
I agree with #Torestergaard, you should keep the lock as slim as possible. Therefor if taking the code sample provided above by #Rebornx and modifying it a bit you can use something like below example:
public class Program
{
public static void Main()
{
LockSample lockSampleInstance = LockSample.GetInstance();
lockSampleInstance.MethodA();
}
}
public class LockSample
{
private static readonly LockSample INSTANCE = new LockSample();
private static Object lockObject = new Object();
public static LockSample GetInstance()
{
return INSTANCE;
}
public void MethodA()
{
Console.WriteLine("MethodA Called");
MethodB();
}
private void MethodB()
{
lock(lockObject)
{
Console.WriteLine("MethodB Called");
}
}
}
Hope it will help,
Liron
Here is a simple program, I used single ton pattern. You can achieve the locking by using "Monitor" also.
public class Program
{
public static void Main()
{
LockSample lockObject = LockSample.GetInstance();
lock(lockObject)
{
lockObject.MethodA();
}
}
}
public class LockSample
{
private static LockSample _Lock;
public static LockSample GetInstance()
{
if(_Lock == null)
{
_Lock = new LockSample();
}
return _Lock;
}
public void MethodA()
{
Console.WriteLine("MethodA Called");
MethodB();
}
private void MethodB()
{
Console.WriteLine("MethodB Called");
}
}
Generally you should keep you lock as slim as possible, so dependent on what you do then it might make sense to move the lock statement into method B only guarding the resource that doesn't support multiple parallel users.
But generally there is nothing wrong with your example.
You can declare the method B with this attribute:
[MethodImpl(MethodImplOptions.Synchronized)]
public void B() {
...
}
I find that in some cases, there is a lot of code in a constructor, or a class has two or more constructors which have comparable code. In these cases, I often create a private method. In the former case to improve readability, in the latter to prevent duplicate code.
In some of these cases this results in a private method that should ONLY be called from the constructor (for whatever reason). Is there a way to enforce this? I could imagine doing something like this:
using System.Diagnostics;
public class Foo
{
private bool _constructing = true;
private Foo()
{
_constructing = false;
}
public Foo(string someString) : this()
{
// constructor-specific code
Initialize();
}
public Foo(double someDouble) : this()
{
// constructor-specific code
Initialize();
}
private void Initialize()
{
Debug.Assert(!_constructing, "Initialize method should only be called from constructor");
// shared code
}
}
but this feels somewhat clunky. Does anyone have a better suggestion?
Edit: added constructor chaining to example; I meant for this to be in the original example.
Edit: I think I missed a point in my original question - while chaining constructors does provide a solution in some cases, the chained code is always executed prior to the code in the constructor that you're chaining from (which, incidentally, is why the above example doesn't work). There are cases where you want to execute some part of shared code, and then do something else. I'll add another example to reflect this:
using System.Diagnostics;
public class Foo
{
private bool _constructing = true;
public Foo(string someString)
{
// constructor-specific pre-processing code
Initialize();
// constructor-specific post-processing code
_constructing = false;
}
public Foo(double someDouble)
{
// constructor-specific pre-processing code
Initialize();
// constructor-specific post-processing code
_constructing = false;
}
private void Initialize()
{
Debug.Assert(!_constructing, "Initialize method should only be called from constructor");
// shared code
}
}
Constructors can call each other:
class Foo
{
private Foo()
{
}
public Foo(int value) : this()
{
}
}
I think, you could use this feature.
You can use the CallerMemberName for that. The compiler will fill that with the original method the method is called from. In this case .ctor (constructor):
public static class Program
{
static void Main(string[] args)
{
A a = new A();
}
}
class A
{
public A()
{
B();
}
[MethodImplOptions.NoInlining]
private void B([CallerMemberName] string caller = null)
{
if (caller == ".ctor")
{
}
}
}
To prevent inlining, you can put the MethodImplOptions.NoInlining on the method B.
I suggest that you do this:
public class Foo
{
private Foo()
{
// private constructors can only be called from
// within the class during constuction
}
public Foo(string someString) : this()
{
}
public Foo(double someDouble) : this()
{
}
}
The use of : this() can only be called during construction and while this doesn't force your public constructors calling : this() you don't have any such guarantee that your public constructors will call Initialize() anyway.
Is it by any chance possible to call a method without referencing to its class?
For instance, you have a helper class:
class HelperTools
{
public static void DoWork()
{ /*...*/ }
}
And then you need to call it:
class MainClass
{
public static void Main()
{
HelperTools.DoWork();
}
}
Is it possible to call DoWork(); without a reference? Like this:
public static void Main()
{
DoWork();
}
Just for sake of simplicity.
Not quite, but here are 5 patterns that get you close:
namespace My.Namespace
{
using H = MyHelperClass;
public class MyHelperClass
{
public static void HelperFunc1()
{
Console.WriteLine("Here's your help!");
}
}
public class MyHelperClass2
{
public static void HelperFunc4()
{
Console.WriteLine("Here's your help!");
}
}
public interface IHelper{ }
public static class HelperExtensions
{
public static void HelperFunc3(this IHelper self)
{
Console.WriteLine("Here's your help!");
}
}
public class MyClass : MyHelperClass2, IHelper
{
private static readonly Action HelperFunc2 = MyHelperClass.HelperFunc1;
private static void HelperFunc5()
{
Console.WriteLine("Here's your help!");
}
public void MyFunction()
{
//Method 1 use an alias to make your helper class name shorter
H.HelperFunc1();
//Method 2 use a class property
HelperFunc2();
//Method 3 extend an interface that has extension methods.
//Note: you'll have to use the this keyword when calling extension
this.HelperFunc3();
//Method 4 you have access to methods on classes that you extend.
HelperFunc4();
//Method 5 put the helper method in your class
HelperFunc5();
}
}
}
No. Java has the concept of importing static like this, but C# does not. (IMO, a naked DoWork() without any clue as to where the implementation resides is non-ideal.)
a few years late but maybe this will help someone else...
Use a using static directive to reference the static class: (introduced in C# 6)
using static HelperTools;
class MainClass
{
public static void Main()
{
DoWork();
}
}
---------------- HelperTools.cs--------------------
class HelperTools
{
public static void DoWork()
{ /*...*/ }
}
The only place you can call DoWork from without referencing the class name is within the class itself. For instance, if you add a non-static method to HelperTools:
public void foo()
{
DoWork();
}
You can call DoWork from within it, even though foo() is not static.