Interface vs Base class

后端 未结 30 2541
甜味超标
甜味超标 2020-11-21 07:34

When should I use an interface and when should I use a base class?

Should it always be an interface if I don\'t want to actually define a base implementation of the

30条回答
  •  抹茶落季
    2020-11-21 07:40

    I recommend using composition instead of inheritence whenever possible. Use interfaces but use member objects for base implementation. That way, you can define a factory that constructs your objects to behave in a certain way. If you want to change the behavior then you make a new factory method (or abstract factory) that creates different types of sub-objects.

    In some cases, you may find that your primary objects don't need interfaces at all, if all of the mutable behavior is defined in helper objects.

    So instead of IPet or PetBase, you might end up with a Pet which has an IFurBehavior parameter. The IFurBehavior parameter is set by the CreateDog() method of the PetFactory. It is this parameter which is called for the shed() method.

    If you do this you'll find your code is much more flexible and most of your simple objects deal with very basic system-wide behaviors.

    I recommend this pattern even in multiple-inheritence languages.

提交回复
热议问题