Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Abstraction ใน C++ (การสรุปทั่วไป/การนามธรรม)

Abstraction (การสรุปทั่วไป) คือการ แสดงเฉพาะสิ่งที่จำเป็น (What) และ ซ่อนรายละเอียดการทำงาน (How) ให้ผู้ใช้ไม่ต้องรู้ Implementation Details

ระดับของ Abstraction

ระดับ คำอธิบาย ตัวอย่าง C++
1. PhysicalHardware LevelRegisters, Memory Addresses
2. LogicalData StructuresArray, Linked List, Vector
3. View/ConceptualAbstract Data Types (ADT)Stack, Queue, Map Interface
4. InterfaceClass Interface (Public Methods)Class with Pure Virtual Functions

Abstraction ใน C++: Abstract Class & Pure Virtual Functions

#include <iostream>
#include <string>
using namespace std;

// Abstract Base Class - Interface
class Shape {
protected:
    string color;
public:
    Shape(string c) : color(std::move(c)) {}
    
    // Pure Virtual Functions = Abstract Methods
    virtual double area() const = 0;
    virtual double perimeter() const = 0;
    virtual void draw() const = 0;
    
    // Virtual Destructor (จำเป็น!)
    virtual ~Shape() = default;
    
    // Common functionality (Non-virtual)
    string getColor() const { return color; }
    void setColor(string c) { color = std::move(c); }
};

// Concrete Derived Classes
class Rectangle : public Shape {
    double width, height;
public:
    Rectangle(double w, double h, string c) : Shape(std::move(c)), width(w), height(h) {}
    
    double area() const override { return width * height; }
    double perimeter() const override { return 2 * (width + height); }
    void draw() const override { cout << "Drawing Rectangle [" << color << "]" << endl; }
};

class Circle : public Shape {
    double radius;
public:
    Circle(double r, string c) : Shape(std::move(c)), radius(r) {}
    
    double area() const override { return 3.14159 * radius * radius; }
    double perimeter() const override { return 2 * 3.14159 * radius; }
    void draw() const override { cout << "Drawing Circle [" << color << "]" << endl; }
};

// ใช้งานผ่าน Abstract Interface
void processShape(const Shape& shape) {
    cout << "Color: " << shape.getColor() << endl;
    cout << "Area: " << shape.area() << endl;
    cout << "Perimeter: " << shape.perimeter() << endl;
    shape.draw();
    cout << "---" << endl;
}

int main() {
    // Shape s;  // ❌ Error: Cannot instantiate Abstract Class
    
    Rectangle rect(5, 3, "Red");
    Circle circ(4, "Blue");
    
    processShape(rect);  // Polymorphism
    processShape(circ);
    
    // Vector of Shapes
    vector<unique_ptr<Shape>> shapes;
    shapes.push_back(make_unique<Rectangle>(10, 5, "Green"));
    shapes.push_back(make_unique<Circle>(3, "Yellow"));
    
    for (const auto& s : shapes)
        processShape(*s);
    
    return 0;
}

ผลลัพธ์

Color: Red
Area: 15
Perimeter: 16
Drawing Rectangle [Red]
---
Color: Blue
Area: 50.2654
Perimeter: 25.1327
Drawing Circle [Blue]
---
Color: Green
Area: 50
Perimeter: 30
Drawing Rectangle [Green]
---
Color: Yellow
Area: 28.2743
Perimeter: 18.8495
Drawing Circle [Yellow]
---

ตัวอย่าง Abstraction แบบง่าย (Data Abstraction)


// ADT: Stack Interface
class Stack {
public:
    virtual ~Stack() = default;
    virtual void push(int x) = 0;
    virtual int pop() = 0;
    virtual int top() const = 0;
    virtual bool empty() const = 0;
    virtual size_t size() const = 0;
};

// Implementation 1: Array-based
class ArrayStack : public Stack {
    vector<int> data;
public:
    void push(int x) override { data.push_back(x); }
    int pop() override { int v = data.back(); data.pop_back(); return v; }
    int top() const override { return data.back(); }
    bool empty() const override { return data.empty(); }
    size_t size() const override { return data.size(); }
};

// Implementation 2: Linked List-based
class ListStack : public Stack {
    struct Node { int val; Node* next; Node(int v, Node* n) : val(v), next(n) {} };
    Node* head = nullptr;
public:
    ~ListStack() { while (head) { Node* t = head; head = head->next; delete t; } }
    void push(int x) override { head = new Node(x, head); }
    int pop() override { int v = head->val; Node* t = head; head = head->next; delete t; return v; }
    int top() const override { return head->val; }
    bool empty() const override { return head == nullptr; }
    size_t size() const override { /* count nodes */ return 0; }
};

// Client Code - ไม่รู้ Implementation
void useStack(Stack& s) {
    s.push(1); s.push(2); s.push(3);
    while (!s.empty()) cout << s.pop() << " ";  // 3 2 1
}

int main() {
    ArrayStack as; useStack(as);
    ListStack ls; useStack(ls);
}

Interface Segregation Principle (ISP)

แยก Interface ให้เฉพาะเจาะจง แทน Interface เดียวใหญ่โต


// ❌ Fat Interface
class Machine {
    virtual void print() = 0;
    virtual void scan() = 0;
    virtual void fax() = 0;
    virtual void staple() = 0;
};

// ✓ Segregated Interfaces
class Printer { virtual void print() = 0; };
class Scanner { virtual void scan() = 0; };
class Fax { virtual void fax() = 0; };

class SimplePrinter : public Printer { /* ... */ };
class MultiFunction : public Printer, public Scanner, public Fax { /* ... */ };

สรุป: Encapsulation vs Abstraction

หัวข้อ Encapsulation Abstraction
Focusซ่อน Data & Implementationซ่อน Complexity, แสดง Interface
QuestionHow?What?
MechanismAccess ModifiersAbstract Class, Pure Virtual
LevelClass ImplementationDesign/Architecture
Exampleprivate fields + public methodsShape interface → Circle, Rectangle

Best Practices

  • Program to Interface (Abstract Base Class), not Implementation
  • ใช้ virtual destructor ใน Abstract Class เสมอ
  • ใช้ override keyword (C++11) ป้องกัน Typo
  • ใช้ final ป้องกัน Override เพิ่มเติม
  • Interface แยกเล็กๆ (ISP) ดีกว่า Interface ใหญ่โต
  • Prefer Composition over Inheritance เมื่อเป็นไปได้