/* book-library.ts */
import IBookLibrary from './i-book-library';
export default class BookLibrary implements IBookLibrary{
// 实例可能占用内存较多
private static bookList: string[];
constructor() {
if (!BookLibrary.bookList) {
BookLibrary.bookList = [];
// 创建实例时间长
const time = Date.now() + 10000;
while (Date.now() < time) {};
BookLibrary.bookList.push('Harry Potter');
BookLibrary.bookList.push('Animal Spirits');
BookLibrary.bookList.push('Tuesdays with Morrie');
}
}
public getBook(bookName: string) {
const index = BookLibrary.bookList.findIndex(book => book === bookName);
if (index !== -1) {
return BookLibrary.bookList[index];
} else {
throw new Error(`can not find ${bookName}`);
}
}
public addBook(bookName: string) {
const index = BookLibrary.bookList.findIndex(book => book === bookName);
if (index !== -1) {
throw new Error(`already has ${bookName}`);
} else {
BookLibrary.bookList.push(bookName);
}
}
public removeBook(bookName: string) {
const index = BookLibrary.bookList.findIndex(book => book === bookName);
if (index !== -1) {
BookLibrary.bookList.splice(index, 1);
} else {
throw new Error(`can not find ${bookName}`);
}
}
}
代理角色
import BookLibrary from './book-library';
import IBookLibrary from './i-book-library';
export default class BookProxy implements IBookLibrary {
private readonly bookLibrary: BookLibrary;
private readonly isAdmin: boolean;
constructor(isAdmin?: boolean) {
this.isAdmin = isAdmin;
// 给出提示消息
console.log('正在创建中,请等待');
this.bookLibrary = new BookLibrary();
console.log('创建完成');
}
public getBook(bookName: string) {
return this.bookLibrary.getBook(bookName);
}
public addBook(bookName: string) {
if (!this.isAdmin) {
throw new Error('Sorry, you have no right to operate');
}
return this.bookLibrary.addBook(bookName);
}
public removeBook(bookName: string) {
if (!this.isAdmin) {
throw new Error('Sorry, you have no right to operate');
}
return this.bookLibrary.removeBook(bookName);
}
}
客户端调用
/* client.ts */
import BookProxy from './book-proxy';
export default class Client {
public static userTest() {
const proxy = new BookProxy();
return proxy.getBook('Animal Spirits');
}
public static adminTest() {
const proxy = new BookProxy(true);
proxy.getBook('Animal Spirits');
proxy.addBook('Lord of the flies');
}
}
//Client.userTest();
Client.adminTest();
请发表评论