- Encapsulation: Bundling the data (properties) and methods (functions) that operate on the data into a single unit or class.
- Inheritance: Mechanism where a new class can inherit properties and methods from an existing class.
- Polymorphism: Ability to present the same interface for different underlying forms (data types).
- Abstraction: Hiding the complex reality while exposing only the necessary parts.
Example: OOP Concepts in Angular
Let's create a simple Angular application demonstrating these principles through a component and a service.
Step 1: Setup an Angular Component
First, we'll define a User
class demonstrating encapsulation and abstraction.
typescrip// user.model.ts
export class User {
constructor(private name: string, private age: number) {}
getName(): string {
return this.name;
}
getAge(): number {
return this.age;
}
isAdult(): boolean {
return this.age >= 18;
}
}
Step 2: Create a Service with Inheritance
Next, we'll create a base service and a derived service demonstrating inheritance.
typescri// base.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class BaseService {
log(message: string) {
console.log('BaseService:', message);
}
}
// user.service.ts
import { Injectable } from '@angular/core';
import { BaseService } from './base.service';
@Injectable({
providedIn: 'root',
})
export class UserService extends BaseService {
private users: User[] = [];
addUser(user: User) {
this.users.push(user);
this.log(`User added: ${user.getName()}`);
}
getUsers(): User[] {
return this.users;
}
}
Step 3: Implement a Component to Use the Service
Now, we’ll create a component to utilize the User
class and UserService
.
typescr// app.component.ts
import { Component } from '@angular/core';
import { User } from './user.model';
import { UserService } from './user.service';
@Component({
selector: 'app-root',
template: `
<h1>User Management</h1>
<button (click)="addUser()">Add User</button>
<ul>
<li *ngFor="let user of users">
{{ user.getName() }} - Age: {{ user.getAge() }} - Adult: {{ user.isAdult() }}
</li>
</ul>
`,
})
export class AppComponent {
users: User[] = [];
constructor(private userService: UserService) {}
addUser() {
const newUser = new User('John Doe', 25);
this.userService.addUser(newUser);
this.users = this.userService.getUsers();
}
}
Summary
- Encapsulation: The
User
class encapsulates user data and provides methods to access it. - Inheritance:
UserService
extendsBaseService
, inheriting its logging functionality. - Polymorphism: We could add different user types (e.g.,
AdminUser
,GuestUser
) that override base functionalities. - Abstraction: The complex logic of user management is hidden behind the
UserService
interface.
This simple example illustrates how OOP concepts can be effectively utilized in Angular applications, promoting cleaner, more maintainable code.
No comments:
Post a Comment