4.23.3 پلی مورفیسم (Polymorphism)

4.23.3 پلی مورفیسم (Polymorphism)

پلی مورفیسم یکی از مفاهیم مهم در شی گرایی می باشد و هدف استفاده از پلی مورفیسم این است بین آبجکت ها رفتار مشترکی ایجاد کنیم. در زبان گو شما می توانید یک اینترفیس تعریف کنید و برای ساختارهای مختلف متدهای اینترفیس را پیاده سازی کنید.

به مثال زیر توجه کنید :

 1package main
 2
 3import "fmt"
 4
 5// Shape is an interface that defines a method named `Area`
 6type Shape interface {
 7	Area() float64
 8}
 9
10// Rectangle is a struct that represents a rectangle
11type Rectangle struct {
12	width  float64
13	height float64
14}
15
16// Area implements the Shape interface for Rectangle
17func (r Rectangle) Area() float64 {
18	return r.width * r.height
19}
20
21// Circle is a struct that represents a circle
22type Circle struct {
23	radius float64
24}
25
26// Area implements the Shape interface for Circle
27func (c Circle) Area() float64 {
28	return 3.14 * c.radius * c.radius
29}
30
31func CalcArea(shapes ...Shape) {
32	for _, shape := range shapes {
33		fmt.Println(shape.Area())
34	}
35}
36
37func main() {
38	r := Rectangle{width: 10, height: 5}
39	c := Circle{radius: 5}
40
41	CalcArea(r, c)
42}
1$ go run main.go
250
378.5

در کد فوق ما یک اینترفیس Shape داریم که داخلش یک متد به نام Area هست حال این متد را برای ساختارهای Rectangle و Circle پیاده سازی کردیم که مساحت دایره و مستطیل را محاسبه کنیم. حال یک تابع CalcArea داریم به عنوان پارامتر slice از Shape ها میگیرد که ما داخل تابع main ساختار Rectangle و Circle که متد Area اینترفیس Shape را پیاده سازی کرده اند را پاس دادیم و در نهایت محاسبه مساحت را در خروجی چاپ می کند.