实现代理模式示例,添加火车站和代售点类,增强代码可读性

This commit is contained in:
2026-01-02 18:18:06 +08:00
parent 232b926a97
commit 9bb30b8bfb
3 changed files with 191 additions and 0 deletions
+64
View File
@@ -0,0 +1,64 @@
/*
实例:
汤宝宝买火车票,可以去火车站买,也可以去代售点买,但是汤宝宝选择全都要。然而,火车站总共只剩两张票,这可苦了小明了。
*/
interface Seller {
sell(name: string): boolean;
}
class TrainStation implements Seller {
private stock: number;
constructor(stock: number) {
console.log(`火车站库存${stock}张票`);
this.stock = stock;
}
sell(name: string): boolean {
console.log(`${name}去火车站买票`);
if (this.stock > 0) {
this.stock--;
console.log(`${name}在火车站买到一张火车票。`);
return true;
}else {
console.log(`火车站没有票了, ${name}没买到票。`);
return false;
}
}
}
class TicketAgency implements Seller {
name: string;
private station: TrainStation;
constructor(name: string, station: TrainStation) {
this.name = name;
this.station = station;
}
sell(name: string): boolean {
console.log(`${name}去${this.name}买票`);
const result = this.station.sell(this.name);
if (result) {
console.log(`${name}在${this.name}买到一张火车票。`);
return true;
} else {
console.log(`${name}在${this.name}没买到票。`);
return false;
}
}
}
(function(){
console.log("============= 代理模式 =============");
const station = new TrainStation(2);
const agency = new TicketAgency("代售点A", station);
station.sell("汤宝宝");
agency.sell("汤宝宝");
console.log()
agency.sell("小明");
station.sell("小明");
console.log("\n=========== 代理模式结束 ===========");
})()