Handle Class 和 Interface Class

來源:互聯網
上載者:User

這兩者都是為了降低檔案間的編譯依存

1.編譯依存

#include"file1.h"
#include"file2.h"

class class_name
{
 member1 m_m1;
 member2 m_m2;
public:
 member1 get_member_1()const{};
 member2 get_member_2()const{};
};

假設上面的標頭檔為file.h,當file1.h或者file2.h發生變化,或者file中的class_name的實現發生變化時,所有包含file.h的檔案都得重新編譯,當file.h被很多檔案包含時,即使只是對class_name做了小小的改動,也要花費大量的編譯時間。

2. Handle class (控制代碼類)
handle classs 只是提高了所有的介面,同時包含了一個指向真正實作類別的指標。真正的實作類別包含在另外一個檔案中,當要修改這個類時,只有file.h會引起重編譯,而包含file.h的其它檔案不會引起重編譯

#include"file1.h" //contain member1
#include"file2.h" //contain member2
   #include"implement.h"

class class_name
{
  class_impl* implement; //一般會用shared pointer

public:
 member1 get_member_1()const
 {
   return implement->get_member_1();
 }

 member2 get_member_2() const
 {
   return implement->get_member_2();
 }
};

下面的是implement.h的實現


class class_impl
{
  member1 m_1;
  member2 m_2;
public;
  member1 get_member_1()const {}
  member2 get_member_2()const {}
};

2.Interface class
這是製作handle class的另外一種方法
首先聲明的class是抽象類別,一般裡面的介面都是純虛函數,就像Java的Interface
然後提高一個static的create函數(就是Factory 方法),這個函數返回改抽象類別的某個具體子類的對象,函式宣告中的傳回值仍然是該抽象類別的指標或引用。

具體子類在另外一個檔案中聲明。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.