开发者

C# Pattern for abstract class specific code

I have an abstract "Action" class, which has derived types of ActionAppointment, ActionCall, ActionEmail, and ActionLetter. I'm trying to write a function that will DRY up our service layer, so we're not writing CRUD calls 5 times anymore.

I have in our service layer some update logic (lots of other code removed for brevity):

private IServiceResponse UpdateAction<T>(T action, string originalActionStatus) where T : Action
{
        if (action.GetType() == typeof(Action))
        {
            _actionRepository.Update(action);
        }
        else if (action.开发者_如何转开发GetType() == typeof(ActionAppointment))
        {
            _actionAppointmentRepository.Update(action as ActionAppointment);
        }
        else if (action.GetType() == typeof(ActionCall))
        {
            _actionCallRepository.Update(action as ActionCall);
        }
        else if (action.GetType() == typeof(ActionEmail))
        {
            _actionEmailRepository.Update(action as ActionEmail);
        }
        else if (action.GetType() == typeof(ActionLetter))
        {
            _actionLetterRepository.Update(action as ActionLetter);
        }
}

Unfortunately, how our repositories are setup, I have to use the specifically named repositories (ie. I can not update an ActionLetter through the _actionRepository even though it derives from Action)

I have been reading on different patterns, and it sounds like something similar to a Factory Pattern, but I can't see how to make it work.

Am I missing something stupid?


Can't you just write an overload of that method for each action type? Forget the <T> and typeof stuff - what you're doing is implementing a built-in language feature (method overloading) by hand, and in a fragile way too.


Let's inverse the logic here:

abstract class Action {
    protected abstract Repository GetRepository();
    protected void Update(){
       this.GetRepository().Update(this);
    }
}

All you have to do is override the GetRepository in each of the deriving classes. For example:

class ActionAppointment : Action {
    protected override Repository GetRepository() {
        return _actionAppointmentRepository;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜