Typescript 设计模式
设计模式是一组最佳实践,用于解决软件开发中的常见问题,并使编写简洁易维护的代码更加容易。在本篇博文中,我们将讨论 TypeScript 中一些最常用的设计模式。
单例模式
单例模式是一种设计模式,它将类的实例化限制为一个对象,并确保每个类只创建一个对象。在 TypeScript 中实现单例模式非常简单:
class Singleton {
private static instance: Singleton;
private constructor() {}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
你可以像这样使用它:
const singleton = Singleton.getInstance();
工厂
工厂模式是一种设计模式,它允许你创建对象时无需指定要创建对象的具体类。在这个例子中,我们想要根据车辆的类型来创建它,因此我们不是为每种类型都创建一个类,而是创建一个工厂类,根据我们指定的类型来创建车辆。
abstract class Vehicle {
abstract getType(): string;
}
class Car extends Vehicle {
getType() {
return 'car';
}
}
class Truck extends Vehicle {
getType() {
return 'truck';
}
}
class VehicleFactory {
public createVehicle(type: string): Vehicle {
switch (type) {
case 'car':
return new Car();
case 'truck':
return new Truck();
default:
throw new Error(`Vehicle of type ${type} not found`);
}
}
}
您可以像这样使用它来制造任意数量的车辆,只要您提供类型即可:
const factory = new VehicleFactory();
const car = factory.createVehicle('car');
const truck = factory.createVehicle('truck');
观察者
观察者模式是一种设计模式,它允许你定义一种订阅机制来通知多个对象,并用于事件驱动的编程范式。在 TypeScript 中实现观察者模式可以如下所示:
interface Observer {
update(data: any): void;
}
class Subject {
private observers: Observer[] = [];
public subscribe(observer: Observer) {
this.observers.push(observer);
}
public unsubscribe(observer: Observer) {
const index = this.observers.indexOf(observer);
this.observers.splice(index, 1);
}
public notify(data: any) {
this.observers.forEach(observer => observer.update(data));
}
}
那么你将需要一个观察者类:
class ConcreteObserver implements Observer {
public update(data: any) {
console.log(data);
}
}
您可以通过订阅我们创建的观察者来让主题知道有新的可用数据:
const subject = new Subject();
const observer = new ConcreteObserver();
subject.subscribe(observer);
subject.notify('Hello World');
// Unsubscribe the observer from the subject:
subject.unsubscribe(observer);
命令
命令模式是一种设计模式,它允许你将执行某个操作所需的所有信息封装在一个对象中。命令模式的实现可以如下所示:
interface Command {
execute(): void;
}
class ConcreteCommand implements Command {
constructor(private receiver: Receiver) {}
public execute() {
this.receiver.action();
}
}
class Receiver {
public action() {
console.log('Action called');
}
}
然后,您可以使用命令模块创建命令对象并将其传递给调用者:
const receiver = new Receiver();
const command = new ConcreteCommand(receiver);
const invoker = new Invoker();
invoker.setCommand(command);
invoker.execute();
战略
策略模式是一种设计模式,它允许你定义一系列算法,封装每个算法,并使它们可以互换。在 TypeScript 中实现策略模式非常简单,你可以从这个Strategy
类开始:
interface Strategy {
execute(data: any): any;
}
class LastElementStrategy implements Strategy {
public execute(data: []) {
return data[data.length - 1];
}
}
然后你可以像这样使用它:
const strategy = new LastElementStrategy();
const data = [1, 2, 3, 4, 5];
let last = strategy.execute(data);
模板方法
模板方法模式是一种设计模式,它允许你定义操作中算法的框架,并将某些步骤推迟到子类中。例如,你想做一个披萨,用番茄酱和奶酪制作,但配料可以不同。你可以像这样使用模板方法模式:
abstract class Pizza {
public makePizza() {
this.prepareDough();
this.addTomatoSauce();
this.addCheese();
this.addToppings();
this.bakePizza();
}
protected prepareDough() {
console.log('Preparing dough');
}
protected addTomatoSauce() {
console.log('Adding tomato sauce');
}
protected addCheese() {
console.log('Adding cheese');
}
protected abstract addToppings(): void;
protected bakePizza() {
console.log('Baking pizza');
}
}
class PepperoniPizza extends Pizza {
protected addToppings() {
console.log('Adding pepperoni');
}
}
class VegetarianPizza extends Pizza {
protected addToppings() {
console.log('Adding vegetables');
}
}
您可以像这样使用它来制作两种类型的披萨:
const pepperoniPizza = new PepperoniPizza();
pepperoniPizza.makePizza();
const vegetarianPizza = new VegetarianPizza();
vegetarianPizza.makePizza();
结论
这些只是 TypeScript 中可以使用的设计模式的几个示例。通过使用这些模式,您可以编写更优质、更易于维护和扩展的代码。需要注意的是,设计模式不应盲目使用,而应将其作为解决代码中特定问题的工具。
文章来源:https://dev.to/triyanox/design-patterns-in-typescript-e68