本篇文章给大家介绍5种TypeScript设计模式。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
|
本篇文章给大家介绍5种TypeScript设计模式。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
设计模式是可以帮助开发人员解决问题的模板。在本中涉及的模式太多了,而且它们往往针对不同的需求。但是,它们可以被分为三个不同的组:
单例模式单例模式可能是最著名的设计模式之一。它是一种创建模式,因为它确保无论我们尝试实例化一个类多少次,我们都只有一个可用的实例。 处理数据库连接之类的可以单例模式,因为我们希望一次只处理一个,而不必在每个用户请求时重新连接。 class MyDBConn {
protected static instance: MyDBConn | null = null
private id:number = 0
constructor() {
this.id = Math.random()
}
public getID():number {
return this.id
}
public static getInstance():MyDBConn {
if (!MyDBConn.instance) {
MyDBConn.instance = new MyDBConn()
}
return MyDBConn.instance
}
}
const connections = [
MyDBConn.getInstance(),
MyDBConn.getInstance(),
MyDBConn.getInstance(),
MyDBConn.getInstance(),
MyDBConn.getInstance()
]
connections.forEach( c => {
console.log(c.getID())
})现在,虽然不能直接实例化类,但是使用 这个事例展示了无论我们调用 上面的运行结果: 0.4047087250990713 0.4047087250990713 0.4047087250990713 0.4047087250990713 0.4047087250990713 工厂模式
解释一下:假设我们通过编写代码来模拟移动车辆,车有很多类型,例如汽车、自行车和飞机,移动代码应该封装在每个 这里的问题是如何处理对象创建?可以有一个具有3个方法的单一 但是,如果决定使用工厂方法模式,则可以执行以下操作: 现在,创建新对象所需的代码被封装到一个新类中,每个类对应一个车辆类型。这确保了如果将来需要添加车辆,只需要添加一个新类,而不需要修改任何已经存在的东西。 接着来看看,我们如何使用 interface Vehicle {
move(): void
}
class Car implements Vehicle {
public move(): void {
console.log("Moving the car!")
}
}
class Bicycle implements Vehicle {
public move(): void {
console.log("Moving the bicycle!")
}
}
class Plane implements Vehicle {
public move(): void {
console.log("Flying the plane!")
}
}
// VehicleHandler 是“抽象的”,因为没有人会实例化它instantiate it
// 我们要扩展它并实现抽象方法
abstract class VehicleHandler {
// 这是真正的处理程序需要实现的方法
public abstract createVehicle(): Vehicle
public moveVehicle(): void {
const myVehicle = this.createVehicle()
myVehicle.move()
}
}
class PlaneHandler extends VehicleHandler{
public createVehicle(): Vehicle {
return new Plane()
}
}
class CarHandler extends VehicleHandler{
public createVehicle(): Vehicle {
return new Car()
}
}
class BicycleHandler extends VehicleHandler{
public createVehicle(): Vehicle {
return new Bicycle()
}
}
/// User code...
const planes = new PlaneHandler()
const cars = new CarHandler()
planes.moveVehicle()
cars.moveVehicle()上面的代码很多,但我们可以使用上面的图表来理解它。本质上最后,我们关心的是自定义处理程序,这里称它为处理程序,而不是创造者,因为他们不只是创建的对象,他们也有逻辑,使用它们(moveVehicle方法)。 这个模式的美妙之处在于,如果您你要添加一个新的 观察者模式在所有的模式,我最喜欢的是 它是如何工作的呢?本质上,该模式表明你拥有一组观察者对象,这些对象将对被观察实体状态的变化做出反应。为了实现这一点,一旦在被观察端接收到一个更改,它就负责通过调用它的一个方法来通知它的观察者。 在实践中,此模式的实现相对简单,让我们快速查看一下代码,然后回顾一下 type InternalState = {
event: String
}
abstract class Observer {
abstract update(state:InternalState): void
}
abstract class Observable {
protected observers: Observer[] = []
protected state:InternalState = { event: ""}
public addObserver(o: Observer):void {
this.observers.push(o)
}
protected notify () {
this.observers.forEach(o => o.update(this.state))
}
}
class ConsoleLogger extends Observer {
public update(newState: InternalState) {
console.log("New internal state update: ", newState)
}
}
class InputElement extends Observable {
public click():void {
this.state = { event: "click" }
this.notify()
}
}
const input = new InputElement()
input.addObserver(new ConsoleLogger())
input.click()正如你所看到的,通过两个抽象类,我们可以定义 这种模式的优点在于,它使我们能够了解 装饰模式装饰模式试图在运行时向现有对象添加行为。 从某种意义上说,我们可以将其视为动态继承,因为即使没有创建新类来添加行为,我们也正在创建具有扩展功能的新对象。 这样考虑:假设我们拥有一个带有 通常,我们需要在 Dog 类中添加 组合让我们可以将自定义行为封装在不同的类中,然后使用该模式通过将原始对象传递给它们的构造函数来创建这些类的新实例。 让我们看一下代码: abstract class Animal {
abstract move(): void
}
abstract class SuperDecorator extends Animal {
protected comp: Animal
constructor(decoratedAnimal: Animal) {
super()
this.comp = decoratedAnimal
}
abstract move(): void
}
class Dog extends Animal {
public move():void {
console.log("Moving the dog...")
}
}
class SuperAnimal extends SuperDecorator {
public move():void {
console.log("Starts flying...")
this.comp.move()
console.log("Landing...")
}
}
class SwimmingAnimal extends SuperDecorator {
public move():void {
console.log("Jumps into the water...")
this.comp.move()
}
}
const dog = new Dog()
console.log("--- Non-decorated attempt: ")
dog.move()
console.log("--- Flying decorator --- ")
const superDog = new SuperAnimal(dog)
superDog.move()
console.log("--- Now let's go swimming --- ")
const swimmingDog = new SwimmingAnimal(dog)
swimmingDog.move()注意几个细节:
进行此设置的好处是,由于所有装饰器也间接扩展了 const superSwimmingDog = new SwimmingAnimal(superDog) superSwimmingDog.move() Composite(组合)关于Composite模式,其实就是组合模式,又叫部分整体模式,这个模式在我们的生活中也经常使用。 比如编写过前端的页面,肯定使用过 关于此模式的有趣之处在于,它不是一个简单的对象组,它可以包含实体或实体组,每个组可以同时包含更多组,这就是我们所说的树。 看一个例子: interface IProduct {
getName(): string
getPrice(): number
}
class Product implements IProduct {
private price:number
private name:string
constructor(name:string, price:number) {
this.name = name
this.price = price
}
public getPrice():number {
return this.price
}
public getName(): string {
return this.name
}
}
class Box implements IProduct {
private products: IProduct[] = []
contructor() {
this.products = []
}
public getName(): string {
return "A box with " + this.products.length + " products"
}
add(p: IProduct):void {
console.log("Adding a ", p.getName(), "to the box")
this.products.push(p)
}
getPrice(): number {
return this.products.reduce( (curr: number, b: IProduct) => (curr + b.getPrice()), 0)
}
}
//Using the code...
const box1 = new Box()
box1.add(new Product("Bubble gum", 0.5))
box1.add(new Product("Samsung Note 20", 1005))
const box2 = new Box()
box2.add( new Product("Samsung TV 20in", 300))
box2.add( new Product("Samsung TV 50in", 800))
box1.add(box2)
console.log("Total price: ", box1.getPrice())在上面的示例中,我们可以将 上面运行的结果: Adding a Bubble gum to the box Adding a Samsung Note 20 to the box Adding a Samsung TV 20in to the box Adding a Samsung TV 50in to the box Adding a A box with 2 products to the box Total price: 2105.5 因此,在处理遵循同一接口的多个对象时,请考虑使用此模式。 通过将复杂性隐藏在单个实体(组合本身)中,您会发现它有助于简化与小组的互动方式。 今天的分享就到这里了,感谢大家的观看,我们下期再见。
更多编程相关知识,请访问:编程课程!! 以上就是需要了解的TypeScript的5种设计模式的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |
