Dan Tao
Dan Tao

Reputation: 128417

What is the accepted way to dynamically change the function of a delegate in .NET?

Suppose I have a class that represents a product to be priced using one of a number of different pricing strategies. This pricing occurs hundreds of times per second, so to eliminate repetitive if/else statements I am instead using a delegate to launch the appropriate strategy, like so:

Private Delegate Sub PricingModel(ByVal params As PricingParameters)
Private myPricingModel As PricingModel
Private myPricingParameters As PricingParameters

Public Sub RunPricingModel()
    myPricingModel(myPricingParameters)
End Sub

My question is this: if I want to be able to change the strategy, what do I do with myPricingModel? Currently I am simply setting it to a new PricingModel:

Public Sub SwitchStrategy(ByVal strategy As PricingStrategy)
    Select Case strategy
        Case PricingStrategy.STRATEGY_X
            myPricingModel = New PricingModel(AddressOf PricingModelStrategyX)
        Case PricingStrategy.STRATEGY_Y
            myPricingModel = New PricingModel(AddressOf PricingModelStrategyY)
        Case Else
            Exit Sub
    End Select
End Sub

But this doesn't look right to me (though it seems to work). Is there an accepted/better way of doing this? Or is this the standard way? Or is this just simply a doomed approach from the start?

Upvotes: 1

Views: 138

Answers (2)

TcKs
TcKs

Reputation: 26642

You can have a static class with the pricing stretegies (C#):

public static class PricingStrategies {
    public static PricingStrategyX( PricingParameters parameters ) { /* here is body */ }
    public static PricingStrategyY( PricingParameters parameters ) { /* here is body */ }
}

// ... somewhere elsewhere ...
public PricingStrategyDelegate Pricing;
// ...
this.Pricing = PricingStrategies.PricingStrategyX;

Upvotes: 0

JaredPar
JaredPar

Reputation: 755387

There is nothing inherently wrong with this overall approach. As long as PricingStrategy is otherwise acceptable as an enum then this is a perfectly acceptable way of changing private behavior for a different pricing strategy.

My only nitpick comment would be that in "Case Else" you should avoid failing silently.

Upvotes: 4

Related Questions