享元模式(Flyweight Pattern)是一种结构型设计模式,它旨在减少对象的内存使用,通过共享相似对象之间的共同状态来节省内存空间。该模式适用于需要创建大量相似对象的情况,通过共享对象的部分信息,可以有效地减少对象的数量,从而提高系统的性能和效率。
在享元模式中,对象被分为两种类型:内部状态(Intrinsic State)和外部状态(Extrinsic State)。内部状态是可以共享的,并且不会因为对象的不同而变化。外部状态是不可共享的,它会随着对象的不同而变化。
享元模式的核心思想是将可以共享的内部状态从对象中抽取出来,作为一个共享的对象,然后将外部状态作为参数传递给对象,从而实现对象的共享和复用。
TypeScript 实现
假设有一个图书馆管理系统,其中有大量的图书对象,每本图书都有书名(内部状态)和借阅状态(外部状态)。可以使用享元模式来共享相同书名的图书对象,从而减少内存消耗。
class Book {
private title: string;
constructor(title: string) {
this.title = title;
}
borrow(user: string): void {
console.log(`${user}借阅了《${this.title}》`);
}
returnBook(): void {
console.log(`《${this.title}》归还成功`);
}
}
class BookFactory {
private books: { [title: string]: Book } = {};
getBook(title: string): Book {
if (!this.books[title]) {
this.books[title] = new Book(title);
}
return this.books[title];
}
}
const bookFactory = new BookFactory();
const book1 = bookFactory.getBook('Harry Potter');
const book2 = bookFactory.getBook('Lord of the Rings');
book1.borrow('Alice');
book2.borrow('Bob');
book1.returnBook();
在这个例子中,BookFactory 负责共享图书对象,每本图书的书名作为内部状态,可以共享。外部状态是用户的名字,通过参数传递给图书对象,实现了图书的共享和复用。
JavaScript 实现
class Book {
constructor(title) {
this.title = title;
}
borrow(user) {
console.log(`${user}借阅了《${this.title}》`);
}
returnBook() {
console.log(`《${this.title}》归还成功`);
}
}
class BookFactory {
constructor() {
this.books = {};
}
getBook(title) {
if (!this.books[title]) {
this.books[title] = new Book(title);
}
return this.books[title];
}
}
const bookFactory = new BookFactory();
const book1 = bookFactory.getBook('Harry Potter');
const book2 = bookFactory.getBook('Lord of the Rings');
book1.borrow('Alice');
book2.borrow('Bob');
book1.returnBook();