1

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?

8
  • -1 I don't understand what your question is. Commented Jan 22, 2014 at 14:01
  • check for equality to a certain value in that method and only do the work if it IS that certain value, then set it to another value in that method after your work has been done and ensure that value is not reset to the certain value again elsewhere Commented Jan 22, 2014 at 14:05
  • lets assume the method is from external API that you can not control but must not be called a second time :) Commented Jan 22, 2014 at 14:07
  • 2
    you could always wrap that external API method into your own so you regain control ;) Commented Jan 22, 2014 at 14:09
  • 1
    @Grzenio true, but noone ever claimed it was Commented Jan 22, 2014 at 14:11

2 Answers 2

2

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;
      }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

there isn't. I just like to see what solutions are people can think of :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.