Dart中不得不会的mixins

本文介绍了Mixins在面向对象编程中的作用,它允许代码重用并避免多重继承的问题。通过实例展示了如何在Dart中使用Mixins来定义不同职业角色的能力,如Teacher、Doctor和Developer,同时注意Mixins的使用限制和顺序。通过Mixins,类可以灵活地组合功能,而无需复杂的继承结构。
摘要由CSDN通过智能技术生成


一、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');
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dingwen_blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值