๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“Œ Language/Dart

[Dart] Mixin์ด๋ž€? (feat. ์—ฌ๋Ÿฌ ํด๋ž˜์Šค ์ƒ์†๋ฐ›๊ธฐ)

by Fomagran ๐Ÿ’ป 2021. 8. 21.
728x90
๋ฐ˜์‘ํ˜•

์•ˆ๋…•ํ•˜์„ธ์š” Foma๐Ÿ‘Ÿ ์ž…๋‹ˆ๋‹ค!

Dart์— ๋Œ€ํ•œ ์ฒซ ๊ธ€์„ ์“ฐ๊ฒŒ ๋๋Š”๋ฐ์š”.

 

์˜ค๋Š˜์€ Dart์—์„œ ์—ฌ๋Ÿฌ ํด๋ž˜์Šค์˜ ์ฝ”๋“œ๋ฅผ ์žฌ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” Mixin์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๋ฐ”๋กœ ์‹œ์ž‘ํ• ๊ฒŒ์š”~


Mixin์ด๋ž€?

 

๊ณต์‹ ๋ฌธ์„œ์—๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ๋‚˜์™€์žˆ์Šต๋‹ˆ๋‹ค.

 

"Mixin์€ ์—ฌ๋Ÿฌ ํด๋ž˜์Šค ๊ณ„์ธต์—์„œ ํด๋ž˜์Šค ์ฝ”๋“œ๋ฅผ ์žฌ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค."

 

๋ง๋ถ™์—ฌ Mixin์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„  with ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด ์ด๋ฆ„์„ ์ ์–ด์ฃผ๋ฉด ๋œ๋‹ค๊ณ  ๋‚˜์™€์žˆ์Šต๋‹ˆ๋‹ค.


Example

 

์•„๋ž˜์™€ ๊ฐ™์ด ํด๋ž˜์Šค๋“ค์ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ• ๊ฒŒ์š”.

 

๋ณดํ†ต ์•„๋ž˜์™€ ๊ฐ™์ด Player ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค๊ณ  ์•„๋ž˜ ํ•˜์œ„ ํด๋ž˜์Šค๋Š” ์ƒ์œ„ ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›์•„์„œ ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

class Player {
  void play() {
    print("๊ฒฝ๊ธฐํ•˜๋Š” ์ค‘...");
  }
}

class BasketBallPlayer extends Player{
 @override
  void play() {
    super.play();
    print("๋†๊ตฌ๊ฒฝ๊ธฐ ํ•˜๋Š” ์ค‘...");
  }
}

//๊ฒฝ๊ธฐํ•˜๋Š”  ์ค‘...
//๋†๊ตฌ๊ฒฝ๊ธฐ ํ•˜๋Š” ์ค‘...

 

์—ฌ๊ธฐ์„œ ๋ฌธ์ œ๋Š” ์ƒ์†๋ฐ›์„ ๋•Œ OOP์—์„  ์ฃฝ์Œ์˜ ๋‹ค์ด์•„๋ชฌ๋“œ ๋ฌธ์ œ๋กœ ๋‹ค์ค‘ ์ƒ์†์ด ์•ˆ๋œ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

 

๋งŒ์•ฝ ๋›ฐ๊ธฐ,์ ํ”„,์ŠˆํŒ…์„ ๊ฐ ์šด๋™์„ ์ˆ˜๋“ค์ด ๋‹ค์ค‘์œผ๋กœ ์ƒ์† ๋ฐ›์œผ๋ ค๋ฉด ์–ด๋–ป๊ฒŒ ํ•ด์•ผ ํ• ๊นŒ์š”?

 

๋ฐ”๋กœ ์ด ๋•Œ Mixin์„ ์‚ฌ์šฉํ•ด์ฃผ๋Š” ๊ฒƒ ์ž…๋‹ˆ๋‹ค.

 

Mixin์€ ์•„๋ž˜์™€ ๊ฐ™์ด ์•ž์— mixin์„ ๋ถ™์—ฌ์ฃผ๊ณ  ์ด๋ฆ„์„ ์ง€์–ด์ค๋‹ˆ๋‹ค.

 

๊ทธ๋ฆฌ๊ณค ๊ฐ mixin๋“ค์— ๋ฉ”์†Œ๋“œ๋“ค์„ ๋งŒ๋“ค์–ด์ค๋‹ˆ๋‹ค.

 

mixin CanRun {
  void run() {
    print("๋›ฐ๋Š” ์ค‘...");
  }
}

mixin CanJump {
  void jump() {
    print("์ ํ”„ํ•˜๋Š” ์ค‘...");
  }
}

mixin CanShoot {
  void shoot() {
    print("์ŠˆํŒ…ํ•˜๋Š” ์ค‘...");
  }
}

 

์ ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์•„๋ž˜์™€ ๊ฐ™์ด with ํ‚ค์›Œ๋“œ๋ฅผ ์ด์šฉํ•ด ์ ์šฉ๋˜๋Š” mixin๋“ค์„ ์—ฌ๋Ÿฌ๊ฐœ ์„ ํƒํ•ด์„œ ์‚ฌ์šฉํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

class Striker extends FootBallPlayer with CanRun,CanJump,CanShoot {
  @override
  void play() {
    run();
    shoot();
    jump();
  }
}

//๋›ฐ๋Š” ์ค‘...
//์ŠˆํŒ…ํ•˜๋Š” ์ค‘...
//์ ํ”„ํ•˜๋Š” ์ค‘...

class Pitcher extends BaseBallPlayer with CanRun,CanJump {
  @override
  void play() {
    run();
    jump();
  }
}

//๋›ฐ๋Š” ์ค‘...
//์ ํ”„ํ•˜๋Š” ์ค‘...

์˜ค๋Š˜์€ ์ด๋ ‡๊ฒŒ Dart์—์„œ ์—ฌ๋Ÿฌ ํด๋ž˜์Šค์˜ ์ฝ”๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ธ Mixin์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด์•˜์Šต๋‹ˆ๋‹ค.

 

ํ˜น์‹œ๋ผ๋„ ํ‹€๋ฆฐ ์ ์ด ์žˆ๊ฑฐ๋‚˜ ๊ถ๊ธˆํ•˜์‹  ์ ์ด ์žˆ๋‹ค๋ฉด ๋Œ“๊ธ€๋กœ ์•Œ๋ ค์ฃผ์„ธ์š”!

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€