Description of mixins in Java

Mixin means mix in, which means mixing.

mixin type: loosely speaking, a mixin refers to a type that a class can implement in addition to its "primitive type" to indicate that it provides some optional behavior. For example, comparable is a mixin interface that allows a class to indicate that its instances can be sorted with other objects that are comparable to each other.

Similar to multiple inheritance, but usually mixin classes and Mixin classes themselves are not in an is-a relationship. Mixin classes are mixed in to add some (optional) functionality.

Mixin classes freely give you the flexibility to add different functionality to the mixed classes.

Interfaces are ideal for defining mixins (mixed types).

Traditional interfaces do not contain implementations, whereas Mixins contain implementations. In fact, the role of Mixin is very similar to that of many interfaces that end with "able" in Java. The difference is that Mixins provide (default) implementations, while Java classes that implement the able interface need the class itself to implement these mixins (Serializable interface is an exception).

Java syntax stipulates that only single inheritance can be used to avoid the trouble caused by multiple inheritance, but multiple inheritance also has its own advantages. The mixin pattern allows java to have multiple inheritance.

The purpose of a mixin is to add multiple functions to a class. In this way, when designing a class, we give priority to combining the functions of multiple mixins through multiple inheritance, rather than designing a multi-level complex inheritance relationship.

Three ways to implement MixIn in Java

1. Through the interface

2. Decorator pattern

3. Use dynamic proxies

Of course, by designing composition over inheritance, we can avoid having to use multiple inheritance.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325768318&siteId=291194637