利用函數指標實現高內聚、低耦合__函數

來源:互聯網
上載者:User

 作為c的初學者,如果寫一個求四邊形的周長的函數的話,我傾向於像下面這樣書寫:

 

//計算四邊形的周長
#include <stdio.h>

#define RECTANGLE 0  //長方形
#define SQUARE 1 //正方形

//多邊形
struct polygon{
int type;
int length;
int width;
};

int get_circumference(struct polygon pygn)
{
 if(pygn.type == RECTANGLE)
 {
  return 2 * (pygn.length + pygn.width);
 }
 else if(pygn.type == SQUARE)
 {
  return 4 * pygn.width;
 }
 else
 {
  //todo
 }
}

int main(void)
{
 struct polygon pygn_rec, pygn_squ;
 pygn_rec.type = RECTANGLE;
 pygn_rec.width = 6;
 pygn_rec.length = 10;
 pygn_squ.type = SQUARE;
 pygn_squ.width = 6;
 printf("get cir rec is: %d\n", get_circumference(pygn_rec));
 printf("get cir squ is: %d\n", get_circumference(pygn_squ));
 return 0;
}

今天,看了<linux c編程一站式學習>的“函數類型和函數指標”(http://learn.akae.cn/media/ch23s08.html)後,又學到了一種更好的方式:

//計算四邊形的周長
#include <stdio.h>

#define RECTANGLE 0  //長方形
#define SQUARE 1 //正方形
//多邊形
struct polygon{
int type;
int length;
int width;
};

int get_rectangle_cir(struct polygon pygn)
{
 return 2 * (pygn.length + pygn.width);
}
int get_square_cir(struct polygon pygn)
{
 return 4 * pygn.width;
}

int (* get_circumference[])(struct polygon pygn) = {get_rectangle_cir, get_square_cir};

#define get_cir(pygn) get_circumference[pygn.type](pygn)


int main(void)
{
 struct polygon pygn_rec, pygn_squ;
 pygn_rec.type = RECTANGLE;
 pygn_rec.width = 6;
 pygn_rec.length = 10;
 pygn_squ.type = SQUARE;
 pygn_squ.width = 6;

 printf("get cir rec is: %d\n", get_cir(pygn_rec));
 printf("get cir squ is: %d\n", get_cir(pygn_squ));

 return 0;
}

          當調用get_cir(pygn)時,用類型欄位pygn.type做索引,從指標數組get_circumference中取出相應的函數指標來調用,
也可以達到if ... else ...的效果,但相比之下這種實現更好,每個函數都只做一件事情,
而不必用if ... else ...兼顧好幾件事情,比如get_rectangle_cir和get_square_cir各做各的,
互相獨立,而不必把它們的代碼都耦合到一個函數中。
      “低耦合,高內聚”(Low Coupling, High Cohesion)是程式設計的一條基本原則,
這樣可以更好地複用現有代碼,使代碼更容易維護。如果類型欄位pygn.type又多了一種取值,
只需要添加一組新的函數,修改函數指標數組,原有的函數仍然可以不加改動地複用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.