Pro JavaScript Design Patterns 2008 phần 2

ông giao diện là một trong những công cụ hữu ích nhất trong hộp công cụ JavaScript lập trình hướng đối tượng của. Nguyên tắc đầu tiên của thiết kế hướng đối tượng tái sử dụng được đề cập trong Gang of mẫu thiết kế của Bốn nói "Chương trình một giao diện, không phải là một thực hiện," nói cho bạn khái niệm này là cơ bản như thế nào. | CHAPTER 2 Interfaces The interface is one of the most useful tools in the object-oriented JavaScript programmer s toolbox. The first principle of reusable object-oriented design mentioned in the Gang of Four s Design Patterns says Program to an interface not an implementation telling you how fundamental this concept is. The problem is that JavaScript has no built-in way of creating or implementing interfaces. It also lacks built-in methods for determining whether an object implements the same set of methods as another object making it difficult to use objects interchangeably. Luckily JavaScript is extremely flexible making it easy to add these features. In this chapter we look at how other object-oriented languages implement interfaces and try to emulate the best features of each. We look at several ways of doing this in JavaScript and eventually come up with a reusable class that can be used to check objects for needed methods. What Is an Interface An interface provides a way of specifying what methods an object should have. It does not specify how those methods should be implemented though it may indicate or at least hint at the semantics of the methods. For example if an interface contains a method called setName you can be reasonably sure that the implementation of that method is expected to take a string argument and assign it to a name variable. This allows you to group objects based on what features they provide. For example a group of extremely dissimilar objects can all be used interchangeably in anotherObject if they all implement the Comparable interface. It allows you to exploit the commonality between different classes. Functions that would normally expect an argument to be of a specific class can instead be changed to expect an argument of a specific interface allowing you to pass in objects of any concrete implementation. It allows unrelated objects to be treated identically. Benefits of Using Interfaces What does an interface do in .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
251    80    1    03-06-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.