Part1 -> Section2 -> Classes -> 008. Interface

     จากบทความที่แล้ว (Inheritance) ในตอนท้ายเรามีการกล่าวถึง class diagram คร่าวๆ ซึ่งพอเราสร้าง class diagram เสร็จแล้ว ขั้นต่อไปก็นำ diagram มาลงโค้ดจริง หากทั้งโปรแกรมมีแค่ class เดียว คงไม่มีปัญหาอันใด แต่ในชีวิตจริงมันมีมากกว่านั้นเยอะคับ เราจึงควรใช้ตัวนี้เข้ามาช่วยในการสร้างโครงของโปรแกรม สิ่งนี้คือ Interface นั่นเอง
     อย่างที่ได้กล่าวไปแล้ว Interface คือ โครงของ class ซึ่งหาก class ใด implement interface จะต้อง implement method และ property ที่เราได้ประกาศใน Interface ให้ครบ ถ้าไม่ครบ build ไม่ผ่านนะจร๊ะ ดูตัวอย่างประกอบเลยจร้า


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Animal animal = new Animal();
            animal.Greet();

            Dog dog = new Dog();
            dog.Greet();

            Animal dogAnimal = new Dog();
            dogAnimal.Greet();
        }

    }

    interface IAnimal
    {
        void Greet();
    }

    public class Animal : IAnimal
    {
        public virtual void Greet()
        {
            Console.WriteLine("Hello, I am Animal");
        }
    }

    public class Dog : Animal
    {
        public override void Greet()
        {
            Console.WriteLine("Hi, I am Dog");
            base.Greet();
        }
    }

}

จากตัวอย่าง มีการเพิ่ม Interface ที่ชื่อว่า IAnimal (โดยปกติจะตั้งชื่อ interface ขึ้นต้นด้วย i เพื่อให้รู้ว่านี้คือ interface นะ) ด้วย keyword interface และที่ class Animal ได้ implement interface IAnimal โดยใช้ : (colon) (ซึ่งเขียนแบบเดียวกันกับ Inheritance) และใน class Animal ได้ implement method Greet() ลอง comment ไว้แล้ว build ดูท่านจะเจอกับ error คับ ลองดูหน้าตามันได้ ส่วนผลลัพธ์ ก็จะได้เหมือนเดิมเลย
     บทสรุป สำหรับ Interface นั้นหน้าที่หลักคือการ lock โครงสร้างของโปรแกรมในภาพรวม มีประโยชน์มากสำหรับโปรแกรมขนาดใหญ่
     จบแล้วนะคับ สำหรับ Part 1 => Section 2 => Classes ต่อไปอย่าลืมติดตามนะคับ ผมกะลังคิดว่าน่าจะเบรกก่อนเข้าไปเรื่องเว็บด้วยการพาทำโปรแกรมง่อยๆสักโปรแกรม เป็น windows application เพราะที่เราเรียนรู้มาถึงตรงนี้นั้นสามารถสร้างโปรแกรมได้แล้วนะ แล้วมาศึกษาไปด้วยนะคับ ยะฮู้วววววว

สอบถามหรือติดตามได้ที่ https://www.facebook.com/learnaspnetmvcjquery

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

Part2 -> Section1 The Basic -> 003. MVC Folder Structure

Part2 -> Section1 The Basic -> 001. Introduction

สารบัญ (Table of content)