So sánh interface và abstract php

Also, just would like to add here that just because any other OO language has some kind of interfaces and abstraction too doesn't mean they have the same meaning and purpose as in PHP. The use of abstraction/interfaces is slightly different while interfaces in PHP actually don't have a real function. They merely are used for semantic and scheme-related reasons. The point is to have a project as much flexible as possible, expandable and safe for future extensions regardless whether the developer later on has a totally different plan of use or not.

If your English is not native you might lookup what Abstraction and Interfaces actually are. And look for synonyms too.

And this might help you as a metaphor:

INTERFACE

Let's say, you bake a new sort of cake with strawberries and you made up a recipe describing the ingredients and steps. Only you know why it's tasting so well and your guests like it. Then you decide to publish your recipe so other people can try that cake as well.

The point here is

- to make it right - to be careful - to prevent things which could go bad (like too much strawberries or something) - to keep it easy for the people who try it out - to tell you how long is what to do (like stiring) - to tell which things you CAN do but don't HAVE to

Exactly THIS is what describes interfaces. It is a guide, a set of instructions which observe the content of the recipe. Same as if you would create a project in PHP and you want to provide the code on GitHub or with your mates or whatever. An interface is what people can do and what you should not. Rules that hold it - if you disobey one, the entire construct will be broken.

ABSTRACTION

To continue with this metaphor here... imagine, you are the guest this time eating that cake. Then you are trying that cake using the recipe now. But you want to add new ingredients or change/skip the steps described in the recipe. So what comes next? Plan a different version of that cake. This time with black berries and not straw berries and more vanilla cream...yummy.

This is what you could consider an extension of the original cake. You basically do an abstraction of it by creating a new recipe because it's a lil different. It has a few new steps and other ingredients. However, the black berry version has some parts you took over from the original - these are the base steps that every kind of that cake must have. Like ingredients just as milk - That is what every derived class has.

Now you want to exchange ingredients and steps and these MUST be defined in the new version of that cake. These are abstract methods which have to be defined for the new cake, because there should be a fruit in the cake but which? So you take the black berries this time. Done.

There you go, you have extended the cake, followed the interface and abstracted steps and ingredients from it.

Nói về chủ đề này thì đã có quá nhiều bài viết trên mạng, thế nhưng mục đích mình bài này là để cho những đứa em của mình cũng đang theo con đường lập trình có một nơi để tham khảo. Rất hy vọng được các bạn góp ý để kiến thức mình chia sẽ được tốt hơn.

So sánh interface và abstract php

Thật ra thì với các bạn sinh viên mới ra trường đi làm (con đang là Internship hay Fresher) thì câu hỏi này là top những câu hỏi gặp phải khi phỏng vấn đó nha.

So sánh interface và abstract php

Bên cạnh đó, hiểu rõ sự khác nhau giữa Interface và Abstract Class sẽ giúp chúng ta có thể thiết kế được các ứng dụng mà nó có các kết nối lỏng lẽo (loosely coupled) và dễ dàng mở rộng. Vấn đề này bạn sẽ hiểu rõ hơn trong bài viết nói về Dependency Injection Principle. Một điều quan trọng là bạn không thể chọn dùng Interface hay Abstract Class nếu chỉ biết chúng khác nhau thế nào.

Interface trong C#

Có thể hiểu đơn giản Interface là một bản thiết kế cho bất kì class muốn thực hiện nó. Nghĩa là nó chỉ có phần khai báo các phương thức/sự kiện và thuộc tính. Các class muốn thực hiện Interface này sẽ viết code implement cho tất cả các khai báo của Interface này.

Các tính chất của Interface

  • Interface không cung cấp việc kế thừa như Class hay Abstract Class mà nó chỉ khai báo phương thức/sự kiện để các lớp khác thực hiện nó.
  • Nó không được khởi tạo nhưng nó có thể được tham chiếu bởi đối tượng của lớp thực hiện nó. ví dụ:

IUserRepository user = new UserRepository();

  • Không có interface lồng nhau (nested interface)
  • Không có constructor, destructor, constants, static và variable.
  • Một interface có thể kế thừa từ một hoặc nhiều interface khác.

public interface IList : ICollection, IEnumerable, IEnumerable

  • Một interface có thể mở rộng một interface khác.
  • Một class có thể implement một hoặc nhiều interfaces.
  • Mọi phương thức, property đều mặc định là public.

Abstract Class trong C#

Lớp trừu tượng (Abstract Class) là một loại lớp đặc biệt không thể khởi tạo được và nó hoạt động như một lớp cơ sở cho các lớp khác.

Mục đích của Abstract Class là cung cấp các chức năng cơ bản mặc định hoặc các chức năng chung chung mà các lớp dẫn suất có thể thực hiện và ghi đè. Nghĩa là, bạn có thể viết định nghĩa cho phương thức trong Abstract Class, các phương thức trong Abstract Class có thể vừa trừu tượng vừa cụ thể.

Các tính chất của Abstract Class

  • Một Abstract Class không thể được khởi tạo.
  • Abstract Class có thể chứa các phương thức trừu tượng và cụ thể (abstract method – virtual method).
  • Một Abstract Class không thể là một Sealed Class. Vì Sealed Class không cho phép kế thừa.
  • Không thể kế thừa từ một Class hay Interface.
  • Lớp dẫn xuất từ Abstract Class phải implement tất cả các abstract methods của Abstract Class đó.
  • Trong Abstract Class thì các abstract method chỉ có khai báo. Còn virtual method thì có thể được định nghĩa.
  • Abstract Class có thể dùng các access modifiers như: private, protected, internal. Nhưng các abstract/virtual methods thì không thể dùng private.
  • Abstract Class có thể có contructor, destructor, constants, fields
  • Không hỗ trợ đa kế thừa.

using System;
namespace ConsoleApp1  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            SampleClass sc = new SampleClass();  
            //AbsSimpleClass absSimpleClass = new AbsSimpleClass(); // Error here  
            sc.Paint();  
            Console.ReadKey();
            //Output:  
            //--> AbsSimpleClass constructor here  
            //--> Paint method here  
        }
        public abstract class AbsSimpleClass  
        {  
            public AbsSimpleClass()  
            {  
                Console.WriteLine("AbsSimpleClass constructor here");  
            }
            public abstract void DoSomething();
            public virtual void Paint()  
            {  
                Console.WriteLine("Paint method here");  
            }  
        }
        public class SampleClass : AbsSimpleClass  
        {  
            public override void DoSomething()  
            {  
                Console.WriteLine("Do something here");  
            }              
        }  
    }      
}

Những điểm khác nhau giữa Interface và Abstract Class

Interface Abstract Class Constructors, Fields and Constants Không Có Multiple inheritance Một class có thể hiện thực nhiều interface.(tạm coi là thừa kế) Không hỗ trợ đa thừa kế Default implementation Không thể định nghĩa code xử lý, chỉ có thể khai báo. Có thể định nghĩa thân phương thức, property. Access Modifiers Mọi phương thức, property đều mặc định là public. Có thể xác định modifier. Adding functionality Mọi phương thức, property của interface cần được hiện thực trong class. Không cần thiết.

Khi nào nên dùng Interface

  • Cần cung cấp các chức năng chung cho các lớp không liên quan.
  • Cần nhóm các đối tượng dựa trên các hành vi phổ biến.
  • Cần sử dụng đa hình vì một lớp có thể thực hiện nhiều interfaces.
  • Cần tạo các thành phần (components) được ghép lỏng lẻo, dễ bảo trì và dùng như 1 plugin vì việc implement cho interface được tách biệt với nó.

Khi nào nên dùng Abstract Class

  • Cần sử dụng kế thừa.
  • Cần cung cấp các phương thức mặc định cũng như các phương thức phổ biến mà nhiều lớp dẫn xuất có thể thực thi và ghi đè.
  • Cần tạo nhiều phiên bản cho các thành phần (components). Bạn có thể thêm các thuộc tính và phương thức vào Abstract Class mà không vi phạm mã và tất cả các lớp kế thừa được tự động cập nhật với thay đổi.

Một vấn đề khác là các Interfaces có thể được implement ngầm hoặc rõ ràng (implemented implicitly or explicitly).

À, còn một vấn đề nữa. Như các bạn thấy một Class có thể implement một hoặc nhiều interfaces. Vậy nếu một class implement 2 interfaces mà trong đó có cùng 1 phương thức (method) thì sẽ thế nào?

Thử mở Visual Studio và chạy console app sau xem như thế nào nhé:

using System;
namespace ConsoleApp1  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            SampleClass sc = new SampleClass();  
            IControl ctrl = new SampleClass();  
            ISurface srfc = new SampleClass();
            sc.Paint();  
            ctrl.Paint();  
            srfc.Paint();  
        }
        interface IControl  
        {  
            void Paint();  
        }  
        interface ISurface  
        {  
            void Paint();  
        }  
        class SampleClass : IControl, ISurface  
        {  
            public void Paint()  
            {  
                Console.WriteLine("Paint method in SampleClass");  
                Console.ReadKey();  
            }  
            void IControl.Paint()  
            {  
                Console.WriteLine("Paint method in IControl");  
                Console.ReadKey();  
            }
            void ISurface.Paint()  
            {  
                Console.WriteLine("Paint method in ISurface");  
                Console.ReadKey();  
            }  
        }  
    }  
}

Hy vọng bài viết này sẽ giúp bạn hiểu rõ hơn về Interface và Abstract Class. Từ đó giúp bạn xây dựng ứng dụng tốt hơn.