首页 > 其他分享 >Dart中不得不会的mixins

Dart中不得不会的mixins

时间:2023-01-06 14:05:39浏览次数:41  
标签:coding study mixins Dart Person mixin print class 不得不


文章目录

  • ​​一、mixins是什么?​​
  • ​​二、使用场景​​
  • ​​三、注意​​
  • ​​四、代码案例​​

一、mixins是什么?

在面向对象的编程语言中,mixin(或mix-in)是一个类,其中包含供其他类使用的方法,而不必成为其他类的父类。这些其他类如何获得对mixin方法的访问权限取决于语言。混合素有时被描述为“包含”而不是“继承”。Mixins鼓励代码重用,并且可用于避免多重继承可能导致的继承歧义(“钻石问题”),或解决语言中对多重继承的支持不足的问题。混合也可以看作是已实现方法的接口。此模式是强制执行依赖关系反转原理的示例。

二、使用场景

定义一个基类 Person ,有sudy()。
有三个实际的人类(不同的职业),Teacher Doctor Developer。他们都继承Person,三种职业拥有不一样的技能。Teacher: tearching , Doctor : cure , Developer: coding。
因为三种技能不是每一个人都会的,如果定义在父类Person中是不合适的。如果将三种技能定义为一个interface的话三个子类都要实现三种技能。

三、注意

  • 需要mixins的类无法定义构造函数
  • 使用on 给混入添加条件
  • 混入顺序

四、代码案例

/*
* @Author DingWen
* @Description Mixins 使用案例二
* @Date 10:00 2021/2/7
**/

void main() {
Doctor doctor = Doctor();
doctor.cure();
doctor.study();

Developer developer = Developer();
developer.study();
developer.coding();

Teacher teacher = Teacher();
teacher.study();
teacher.teaching();
}

class Person {
study() => print('study');
}


class Doctor extends Person with Cure {}

class Developer extends Person with Coding {}

class Teacher extends Person with Teaching {}

//class Cure {
// cure() => print('cure');
//}
//
//class Teaching {
// teaching() => print('teaching');
//}
//
//class Coding {
// // 需要Mixins的类无法定义构造函数
Coding(){}
// coding() => print('coding');
//}

mixin Cure {
cure() => print('cure');
}

mixin Teaching {
teaching() => print('teaching');
}

mixin Coding on Person{ //添加限制条件只有Person有coding这个技能
// 需要Mixins的类无法定义构造函数
// Coding(){}
coding() => print('coding');
@override
study() {
//调用父类的study()
super.study();
print('children');
}
}

//class Dog with Coding{
//
//}
/*
* @Author DingWen
* @Description Mixins 案例三 混合顺序
* @Date 10:17 2021/2/7
**/

import 'dart:io';

mixin D1 {
d() => print('d d1');
}

mixin D2 {
d() => print('d d2');
}

class D with D1, D2 {}

void main() {
D d = D();
d.d();
// D1 & D2 都有d() D2 覆盖了 D1

XY xy = XY();
// XY > Y > X > Z
xy.a();

// 混合后的类是超类的子类型
print(xy is Z);
}

class X {
a() {
print('X a');
}
}

class Y {
a() => print('Y a');
}

class Z {
a() => print('Z a');
}

class XY extends Z with X,Y{
a() => print('XY a');
}


标签:coding,study,mixins,Dart,Person,mixin,print,class,不得不
From: https://blog.51cto.com/u_15932195/5993206

相关文章