混入的概念
把多個(gè)類的能力混合在一起產(chǎn)生一個(gè)能代表所有混入類的類型的類罩锐。
the fundamental concept is that of mixing in capabilities from multiple classes in order to produce a resulting class that represents all the types of the mixins.
混入就是把存在的多個(gè)類映射為一個(gè)新的子類。
a mixin as a function that maps existing classes to new subclasses.
混入的價(jià)值
被混入的類如果發(fā)生改變則改變會(huì)影響到所有混入該類的類。
混入跟AOP很類似痊硕,同時(shí)也建議使用AOP來解決混入的問題强戴。
C++混入
C++的多繼承可以實(shí)現(xiàn)混入预烙。
參數(shù)類型實(shí)現(xiàn)混入是最好的方式翘县,一個(gè)類繼承類型參數(shù)牺蹄。
使用接口實(shí)現(xiàn)混入
組合優(yōu)于配置鼎天,雖然JDK8之前的接口是不能有
使用裝飾模式實(shí)現(xiàn)混入——裝飾器的目的
滿足各種可能的組合
使用裝飾模式實(shí)現(xiàn)混入——裝飾器的做法
The Decorator pattern uses layered objects to dynamically and transparently
add responsibilities to individual objects.
具有相同的接口育勺。
Decorators are implemented using composition and formal structures (the
decoratable/decorator hierarchy), whereas mixins are inheritance-based.
參數(shù)類型的混入可以被當(dāng)做是不需要繼承結(jié)構(gòu)的裝飾器模式。
使用裝飾器實(shí)現(xiàn)混入只有最后一層的方法是可見的潜慎。
使用動(dòng)態(tài)代理實(shí)現(xiàn)混入
動(dòng)態(tài)代理實(shí)現(xiàn)混入的最大好處就是生成的類是所有被混入類的子類。
動(dòng)態(tài)代理實(shí)現(xiàn)混入的最大缺點(diǎn)就是每個(gè)混入的類必須實(shí)現(xiàn)接口。
使用之前必須先進(jìn)行強(qiáng)制類型轉(zhuǎn)換。