Mixin vs inheritance

前端 未结 9 894
梦毁少年i
梦毁少年i 2020-12-02 07:22

What is the difference between a mixin and inheritance?

相关标签:
9条回答
  • 2020-12-02 08:08

    mix-in is a specific, restricted case of (multiple) inheritance used for implementation purposes; some languages (e.g. Ruby) support it without supporting generalized multiple inheritance.

    0 讨论(0)
  • 2020-12-02 08:10

    Mixins are vastly used in a more "plugin" like manner.

    They are the same but in a different context each one of them. Usually when we talk about inheritance we are talking about SINGLE inheritance, and a mixin is a construct that allows MULTIPLE inheritance.

    This is a language construct that is highly controversial in the OOP world because of:

    • The ambiguity that it must be resolved
    • A lot of the time "mixin" classes don't work on its own, and may conflict with other mixins
    • It can result in a "diamond inheritance problem", where two super classes can inherit from the same class

    But that aside, is a powerful construct that's used in various languages and frameworks, some examples are:

    • Django
      • https://github.com/django/django/blob/98126cdfaf632abc8f0b5e65910e46a4eedc4641/django/views/generic/list.py#L194

      • https://docs.djangoproject.com/en/3.1/topics/class-based-views/mixins/

    • Typescript
      • https://www.typescriptlang.org/docs/handbook/mixins.html
      • https://vincit.github.io/objection.js/guide/plugins.html#_3rd-party-plugins
    0 讨论(0)
  • 2020-12-02 08:14

    I think its important to note, that mixin doesn't imply inheritance. According to wikipedia, a Mixin is:

    In object-oriented programming languages, a mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depends on the language. Mixins are sometimes described as being "included" rather than "inherited".

    Specifically, in a language like perl, mixins can be added using the Exporter module:

    package Mixins;
    
    use Exporter qw(import);
    our @EXPORT_OK = qw(pity);
    
    # assumes it will be mixed-in to a class with a _who_do_i_pity method
    sub pity {
        my ($self) = @_;
        printf("I pity %s\n", $self->_who_do_i_pity('da foo'));
    }
    

    Which can be mixed-in to any module containing one, or more, method(s) at a time:

    package MrT
    
    use Mixins qw(pity);
    
    sub new {
        return bless({}, shift);
    }
    
    sub _who_do_i_pity {
        return 'da foo!'
    }
    

    Then in your MrT module can be used thusly:

    use MrT;
    
    MrT->new()->pity();
    

    I know its an absurd example, but, it gets the point across...

    0 讨论(0)
提交回复
热议问题