Hopefully the function is not really called fn() , but it is actually named the way it works, like CalculateTotal() . Then you can extract this method into a class, say: TotalCalculator .
Now when you start the application, preferably using dependency injection, you create one instance of the class that is shared between objects that require it. For instance:
class TotalCalculator { public int Calculate() { return 42; } } class NeedsCalculator1 { TotalCalculator _calculator; public NeedsCalculator1(TotalCalculator calculator) { _calculator = calculator; } public void Foo() { _calculator.Calculate(); } } class NeedsCalculatorToo { TotalCalculator _calculator; public NeedsCalculatorToo(TotalCalculator calculator) { _calculator = calculator; } public void Bar() { _calculator.Calculate(); } }
Then you instantiate the calculator once and pass it to the constructor of the other classes:
TotalCalculator calculator = new TotalCalculator(); NeedsCalculator1 dependency1 = new NeedsCalculator1(calculator); NeedsCalculatorToo dependency2 = new NeedsCalculatorToo(calculator);
Now you can further distract the dependency of the calculator by creating, for example, a base class that contains the constructor and the protected field of the TotalCalculator instance.
source share