自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

你應(yīng)該知道的 5 種 TypeScript設(shè)計(jì)模式

開發(fā) 前端
設(shè)計(jì)模式是可以幫助開發(fā)人員解決問題的模板。在本中涉及的模式太多了,而且它們往往針對(duì)不同的需求。

 [[352789]]

設(shè)計(jì)模式是可以幫助開發(fā)人員解決問題的模板。在本中涉及的模式太多了,而且它們往往針對(duì)不同的需求。但是,它們可以被分為三個(gè)不同的組:

  • 結(jié)構(gòu)模式處理不同組件(或類)之間的關(guān)系,并形成新的結(jié)構(gòu),以提供新的功能。結(jié)構(gòu)模式的例子有Composite、Adapter和Decorator。
  • 行為模式將組件之間的公共行為抽象成一個(gè)獨(dú)立的實(shí)體。行為模式的例子有命令、策略和我個(gè)人最喜歡的一個(gè):觀察者模式。
  • 創(chuàng)建模式 專注于類的實(shí)例化,讓我們更容易創(chuàng)建新的實(shí)體。我說的是工廠方法,單例和抽象工廠。

單例模式

單例模式可能是最著名的設(shè)計(jì)模式之一。它是一種創(chuàng)建模式,因?yàn)樗_保無論我們嘗試實(shí)例化一個(gè)類多少次,我們都只有一個(gè)可用的實(shí)例。

處理數(shù)據(jù)庫連接之類的可以單例模式,因?yàn)槲覀兿M淮沃惶幚硪粋€(gè),而不必在每個(gè)用戶請(qǐng)求時(shí)重新連接。

  1. class MyDBConn { 
  2.   protected static instance: MyDBConn | null = null 
  3.   private id:number = 0 
  4.  
  5.   constructor() { 
  6.     this.id = Math.random() 
  7.   } 
  8.  
  9.   public getID():number { 
  10.     return this.id 
  11.   } 
  12.  
  13.   public static getInstance():MyDBConn { 
  14.     if (!MyDBConn.instance) { 
  15.       MyDBConn.instance = new MyDBConn() 
  16.     } 
  17.     return MyDBConn.instance 
  18.   } 
  19.  
  20. const connections = [ 
  21.   MyDBConn.getInstance(), 
  22.   MyDBConn.getInstance(), 
  23.   MyDBConn.getInstance(), 
  24.   MyDBConn.getInstance(), 
  25.   MyDBConn.getInstance() 
  26.  
  27. connections.forEach( c => { 
  28.     console.log(c.getID()) 
  29. }) 

現(xiàn)在,雖然不能直接實(shí)例化類,但是使用getInstance方法,可以確保不會(huì)有多個(gè)實(shí)例。在上面的示例中,可以看到包裝數(shù)據(jù)庫連接的偽類如何從該模式中獲益。

這個(gè)事例展示了無論我們調(diào)用getInstance方法多少次,這個(gè)連接總是相同的。

上面的運(yùn)行結(jié)果:

  1. 0.4047087250990713 
  2. 0.4047087250990713 
  3. 0.4047087250990713 
  4. 0.4047087250990713 
  5. 0.4047087250990713 

工廠模式

工廠模式是一種創(chuàng)建模式,就像單例模式一樣。但是,這個(gè)模式并不直接在我們關(guān)心的對(duì)象上工作,而是只負(fù)責(zé)管理它的創(chuàng)建。

解釋一下:假設(shè)我們通過編寫代碼來模擬移動(dòng)車輛,車有很多類型,例如汽車、自行車和飛機(jī),移動(dòng)代碼應(yīng)該封裝在每個(gè)vehicle類中,但是調(diào)用它們的move 方法的代碼可以是通用的。

這里的問題是如何處理對(duì)象創(chuàng)建?可以有一個(gè)具有3個(gè)方法的單一creator類,或者一個(gè)接收參數(shù)的方法。在任何一種情況下,擴(kuò)展該邏輯以支持創(chuàng)建更多vehices都需要不斷增長相同的類。

但是,如果決定使用工廠方法模式,則可以執(zhí)行以下操作:

現(xiàn)在,創(chuàng)建新對(duì)象所需的代碼被封裝到一個(gè)新類中,每個(gè)類對(duì)應(yīng)一個(gè)車輛類型。這確保了如果將來需要添加車輛,只需要添加一個(gè)新類,而不需要修改任何已經(jīng)存在的東西。

接著來看看,我們?nèi)绾问褂肨ypeScript來實(shí)現(xiàn)這一點(diǎn):

  1. interface Vehicle { 
  2.     move(): void 
  3.  
  4. class Car implements Vehicle { 
  5.  
  6.     public move(): void { 
  7.         console.log("Moving the car!"
  8.     } 
  9.  
  10. class Bicycle implements Vehicle { 
  11.  
  12.     public move(): void { 
  13.         console.log("Moving the bicycle!"
  14.     } 
  15.  
  16. class Plane implements Vehicle { 
  17.  
  18.     public move(): void { 
  19.         console.log("Flying the plane!"
  20.     } 
  21.  
  22. // VehicleHandler 是“抽象的”,因?yàn)闆]有人會(huì)實(shí)例化它instantiate it 
  23. // 我們要擴(kuò)展它并實(shí)現(xiàn)抽象方法 
  24. abstract class VehicleHandler { 
  25.  
  26.     // 這是真正的處理程序需要實(shí)現(xiàn)的方法 
  27.     public abstract createVehicle(): Vehicle  
  28.  
  29.     public moveVehicle(): void { 
  30.         const myVehicle = this.createVehicle() 
  31.         myVehicle.move() 
  32.     } 
  33. }  
  34.  
  35. class PlaneHandler extends VehicleHandler{ 
  36.  
  37.     public createVehicle(): Vehicle { 
  38.         return new Plane() 
  39.     } 
  40.  
  41. class CarHandler  extends VehicleHandler{ 
  42.  
  43.     public createVehicle(): Vehicle { 
  44.         return new Car() 
  45.     } 
  46.  
  47. class BicycleHandler  extends VehicleHandler{ 
  48.  
  49.     public createVehicle(): Vehicle { 
  50.         return new Bicycle() 
  51.     } 
  52.  
  53. /// User code... 
  54. const planes = new PlaneHandler() 
  55. const cars = new CarHandler() 
  56.  
  57. planes.moveVehicle() 
  58. cars.moveVehicle() 

上面的代碼很多,但我們可以使用上面的圖表來理解它。本質(zhì)上最后,我們關(guān)心的是自定義處理程序,這里稱它為處理程序,而不是創(chuàng)造者,因?yàn)樗麄儾恢皇莿?chuàng)建的對(duì)象,他們也有邏輯,使用它們(moveVehicle方法)。

這個(gè)模式的美妙之處在于,如果您你要添加一個(gè)新的vehicle類型,所要做的就是添加它的vehicle類和它的處理程序類,而不增加任何其他類的LOC。

觀察者模式

在所有的模式,我最喜歡的是觀察者模式,因?yàn)轭愋偷男袨槲覀兛梢詫?shí)現(xiàn)它。

它是如何工作的呢?本質(zhì)上,該模式表明你擁有一組觀察者對(duì)象,這些對(duì)象將對(duì)被觀察實(shí)體狀態(tài)的變化做出反應(yīng)。為了實(shí)現(xiàn)這一點(diǎn),一旦在被觀察端接收到一個(gè)更改,它就負(fù)責(zé)通過調(diào)用它的一個(gè)方法來通知它的觀察者。

在實(shí)踐中,此模式的實(shí)現(xiàn)相對(duì)簡單,讓我們快速查看一下代碼,然后回顧一下

  1. type InternalState = { 
  2.   event: String 
  3.  
  4. abstract class Observer { 
  5.   abstract update(state:InternalState): void 
  6.  
  7. abstract class Observable { 
  8.   protected observers: Observer[] = [] 
  9.   protected state:InternalState = { event: ""
  10.  
  11.   public addObserver(o: Observer):void { 
  12.     this.observers.push(o) 
  13.   } 
  14.  
  15.   protected notify () { 
  16.     this.observers.forEach(o => o.update(this.state)) 
  17.   } 
  18.  
  19.  
  20. class ConsoleLogger extends Observer  { 
  21.  
  22.     public update(newState: InternalState) { 
  23.         console.log("New internal state update: ", newState) 
  24.     } 
  25.  
  26. class InputElement extends Observable { 
  27.  
  28.     public click():void { 
  29.         this.state = { event: "click" } 
  30.         this.notify() 
  31.     } 
  32.  
  33.  
  34. const input = new InputElement() 
  35. input.addObserver(new ConsoleLogger()) 
  36.  
  37. input.click() 

正如你所看到的,通過兩個(gè)抽象類,我們可以定義Observer,該觀察者將表示對(duì)Observable實(shí)體上的更改做出反應(yīng)的對(duì)象。在上面的示例中,我們假設(shè)具有一個(gè)被單擊的InputElement實(shí)體(類似于在前端具有HTML輸入字段的方式),以及一個(gè)ConsoleLogger,用于記錄控制臺(tái)發(fā)生的所有事情。

這種模式的優(yōu)點(diǎn)在于,它使我們能夠了解Observable的內(nèi)部狀態(tài)并對(duì)其做出反應(yīng),而不必弄亂其內(nèi)部代碼。我們可以繼續(xù)添加執(zhí)行其他操作的觀察者,甚至包括對(duì)特定事件做出反應(yīng)的觀察者,然后讓它們的代碼決定對(duì)每個(gè)通知執(zhí)行的操作。

裝飾模式

裝飾模式試圖在運(yùn)行時(shí)向現(xiàn)有對(duì)象添加行為。從某種意義上說,我們可以將其視為動(dòng)態(tài)繼承,因?yàn)榧词箾]有創(chuàng)建新類來添加行為,我們也正在創(chuàng)建具有擴(kuò)展功能的新對(duì)象。

這樣考慮:假設(shè)我們擁有一個(gè)帶有move方法的Dog類,現(xiàn)在您想擴(kuò)展其行為,因?yàn)槲覀兿胍恢怀?jí)狗和一只可以游泳的狗。

通常,我們需要在 Dog 類中添加move 行為,然后以兩種方式擴(kuò)展該類,即SuperDog和SwimmingDog類。但是,如果我們想將兩者混合在一起,則必須再次創(chuàng)建一個(gè)新類來擴(kuò)展它們的行為,但是,有更好的方法。

組合讓我們可以將自定義行為封裝在不同的類中,然后使用該模式通過將原始對(duì)象傳遞給它們的構(gòu)造函數(shù)來創(chuàng)建這些類的新實(shí)例。讓我們看一下代碼:

  1. abstract class Animal { 
  2.  
  3.     abstract move(): void 
  4.  
  5. abstract class SuperDecorator extends Animal { 
  6.     protected comp: Animal 
  7.      
  8.     constructor(decoratedAnimal: Animal) { 
  9.         super() 
  10.         this.comp = decoratedAnimal 
  11.     } 
  12.      
  13.     abstract move(): void 
  14.  
  15. class Dog extends Animal { 
  16.  
  17.     public move():void { 
  18.         console.log("Moving the dog..."
  19.     } 
  20.  
  21. class SuperAnimal extends SuperDecorator { 
  22.  
  23.     public move():void { 
  24.         console.log("Starts flying..."
  25.         this.comp.move() 
  26.         console.log("Landing..."
  27.     } 
  28.  
  29. class SwimmingAnimal extends SuperDecorator { 
  30.  
  31.     public move():void { 
  32.         console.log("Jumps into the water..."
  33.         this.comp.move() 
  34.     } 
  35.  
  36.  
  37. const dog = new Dog() 
  38.  
  39. console.log("--- Non-decorated attempt: "
  40. dog.move() 
  41.  
  42. console.log("--- Flying decorator --- "
  43. const superDog =  new SuperAnimal(dog) 
  44. superDog.move() 
  45.  
  46. console.log("--- Now let's go swimming --- "
  47. const swimmingDog =  new SwimmingAnimal(dog) 
  48. swimmingDog.move() 

注意幾個(gè)細(xì)節(jié):

  • 實(shí)際上,SuperDecorator類擴(kuò)展了Animal類,與Dog類擴(kuò)展了相同的類。這是因?yàn)檠b飾器需要提供與其嘗試裝飾的類相同的公共接口。
  • SuperDecorator類是abstract ,這意味著并沒有使用它,只是使用它來定義構(gòu)造函數(shù),該構(gòu)造函數(shù)會(huì)將原始對(duì)象的副本保留在受保護(hù)的屬性中。公共接口的覆蓋是在自定義裝飾器內(nèi)部完成的。
  • SuperAnimal和SwimmingAnimal是實(shí)際的裝飾器,它們是添加額外行為的裝飾器。

進(jìn)行此設(shè)置的好處是,由于所有裝飾器也間接擴(kuò)展了Animal類,因此如果你要將兩種行為混合在一起,則可以執(zhí)行以下操作:

  1. const superSwimmingDog =  new SwimmingAnimal(superDog) 
  2.  
  3. superSwimmingDog.move() 

Composite(組合)

關(guān)于Composite模式,其實(shí)就是組合模式,又叫部分整體模式,這個(gè)模式在我們的生活中也經(jīng)常使用。

比如編寫過前端的頁面,肯定使用過

等標(biāo)簽定義一些格式,然后格式之間互相組合,通過一種遞歸的方式組織成相應(yīng)的結(jié)構(gòu),這種方式其實(shí)就是組合,將部分的組件鑲嵌到整體之中。

 

關(guān)于此模式的有趣之處在于,它不是一個(gè)簡單的對(duì)象組,它可以包含實(shí)體或?qū)嶓w組,每個(gè)組可以同時(shí)包含更多組,這就是我們所說的樹。

看一個(gè)例子:

  1. interface IProduct { 
  2.   getName(): string 
  3.   getPrice(): number 
  4.  
  5. class Product implements IProduct { 
  6.   private price:number 
  7.   private name:string 
  8.  
  9.   constructor(name:string, price:number) { 
  10.     this.name = name 
  11.     this.price = price 
  12.   } 
  13.  
  14.   public getPrice():number { 
  15.     return this.price 
  16.   } 
  17.  
  18.   public getName(): string { 
  19.     return this.name 
  20.   } 
  21.  
  22. class Box implements IProduct { 
  23.  
  24.     private products: IProduct[] = [] 
  25.      
  26.     contructor() { 
  27.         this.products = [] 
  28.     } 
  29.      
  30.     public getName(): string { 
  31.         return "A box with " + this.products.length + " products" 
  32.     }  
  33.      
  34.     add(p: IProduct):void { 
  35.         console.log("Adding a ", p.getName(), "to the box"
  36.         this.products.push(p) 
  37.     } 
  38.  
  39.     getPrice(): number { 
  40.         return this.products.reduce( (curr: number, b: IProduct) => (curr + b.getPrice()),  0) 
  41.     } 
  42.  
  43. //Using the code... 
  44. const box1 = new Box() 
  45. box1.add(new Product("Bubble gum", 0.5)) 
  46. box1.add(new Product("Samsung Note 20", 1005)) 
  47.  
  48. const box2 = new Box() 
  49. box2.add( new Product("Samsung TV 20in", 300)) 
  50. box2.add( new Product("Samsung TV 50in", 800)) 
  51.  
  52. box1.add(box2) 
  53.  
  54. console.log("Total price: ", box1.getPrice()) 

在上面的示例中,我們可以將product 放入Box中,也可以將Box放入其他Box中,這是組合的經(jīng)典示例。因?yàn)槲覀円獙?shí)現(xiàn)的是獲得完整的交付價(jià)格,因此需要在大box里添加每個(gè)元素的價(jià)格(包括每個(gè)小box的價(jià)格)。

上面運(yùn)行的結(jié)果:

  1. Adding a  Bubble gum to the box 
  2. Adding a  Samsung Note 20 to the box 
  3. Adding a  Samsung TV 20in to the box 
  4. Adding a  Samsung TV 50in to the box 
  5. Adding a  A box with 2 products to the box 
  6. Total price:  2105.5 

因此,在處理遵循同一接口的多個(gè)對(duì)象時(shí),請(qǐng)考慮使用此模式。通過將復(fù)雜性隱藏在單個(gè)實(shí)體(組合本身)中,您會(huì)發(fā)現(xiàn)它有助于簡化與小組的互動(dòng)方式。

今天的分享就到這里了,感謝大家的觀看,我們下期再見。

作者:Fernando Doglio 譯者:前端小智 來源:medium 原文:https://blog.bitsrc.io/design-patterns-in-typescript-e9f84de40449

 本文轉(zhuǎn)載自微信公眾號(hào)「大遷世界」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系大遷世界公眾號(hào)。

 

責(zé)任編輯:武曉燕 來源: 大遷世界
相關(guān)推薦

2013-05-20 10:14:42

軟件工具項(xiàng)目工具開發(fā)工具

2017-06-06 11:59:26

Docker工具容器

2014-12-17 09:27:41

開源PaaS

2019-12-02 10:16:46

架構(gòu)設(shè)計(jì)模式

2022-05-18 09:01:31

JavaScriptEvalErrorURIError

2021-04-09 20:38:20

Vue模式.前端

2024-07-04 09:27:57

2023-11-02 08:32:11

機(jī)器學(xué)習(xí)人工智能

2019-11-07 11:49:14

架構(gòu)運(yùn)維技術(shù)

2020-04-03 19:21:59

JavaScript編程語言開發(fā)

2023-09-06 12:35:40

2011-03-25 15:56:58

2019-06-03 08:04:43

Apache服務(wù)器命令

2013-01-09 13:55:43

2020-04-29 14:30:35

HTTPHTTPS前端

2020-06-04 09:50:31

智能家居智能安防人工智能

2021-06-07 12:40:34

Python代碼陷阱

2022-01-04 10:10:34

Garuda LinuArch LinuxLinux

2022-11-04 08:22:14

編譯代碼C語言

2016-02-25 10:58:01

Live Linux桌面發(fā)行版
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)