├── .DS_Store ├── Adapter.ts ├── Decorator.ts ├── Facade.ts ├── Factory.ts ├── Iterator.ts ├── LICENSE ├── Observer.ts ├── Prototype.ts ├── README.md ├── Singleton.ts └── State.ts /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GreenhornDeveloper/TypeScriptPatterns/11828e7e91610a430343c78b271a1482b3bfb065/.DS_Store -------------------------------------------------------------------------------- /Adapter.ts: -------------------------------------------------------------------------------- 1 | //tsc Adapter.ts && node Adapter.js 2 | 3 | interface FourByFour{ 4 | 5 | driveOnDrirt():void 6 | 7 | } 8 | 9 | interface FrontWheelDrive{ 10 | 11 | driveOnPavement():void 12 | } 13 | 14 | 15 | class ToyotaMiniVan implements FrontWheelDrive{ 16 | 17 | driveOnPavement(){ 18 | console.log("I am driving on the road") 19 | } 20 | 21 | } 22 | 23 | 24 | class ToyotaTacoma implements FourByFour{ 25 | 26 | driveOnDrirt(){ 27 | console.log("I am driving on the dirt") 28 | } 29 | 30 | } 31 | 32 | 33 | class PowerTrainAdapter implements FourByFour{ 34 | 35 | private _fwdVehicle:FrontWheelDrive; 36 | 37 | constructor(vehicle:FrontWheelDrive){ 38 | this._fwdVehicle = vehicle 39 | } 40 | 41 | driveOnDrirt(){ 42 | console.log("This vehicle is converting to front wheel drive.") 43 | this._fwdVehicle.driveOnPavement() 44 | } 45 | } 46 | 47 | 48 | let minivan = new ToyotaMiniVan() 49 | let powerTrainAdapter = new PowerTrainAdapter(minivan); 50 | 51 | powerTrainAdapter.driveOnDrirt() 52 | -------------------------------------------------------------------------------- /Decorator.ts: -------------------------------------------------------------------------------- 1 | /* 2 | This is the experimental way of doing it within 3 | the TypeScript language itself. 4 | Run with 'tsc --target ES5 --experimentalDecorators' prefix 5 | */ 6 | 7 | // function wrapperOne() { 8 | // console.log("wrapperOne(): evaluated"); 9 | // return function (target, propertyKey: string, descriptor: PropertyDescriptor) { 10 | // console.log("wrapperOne(): called"); 11 | // } 12 | // } 13 | 14 | // function wrapperTwo() { 15 | // console.log("wrapperTwo(): evaluated"); 16 | // return function (target, propertyKey: string, descriptor: PropertyDescriptor) { 17 | // console.log("wrapperTwo(): called"); 18 | // } 19 | // } 20 | 21 | // class C { 22 | // @wrapperOne() 23 | // @wrapperTwo()( 24 | // someFunction() {} 25 | // } 26 | 27 | 28 | /* This is the way to create decorators without TypeScript's built in support */ 29 | abstract class Vehicle{ 30 | private _make: string; 31 | private _model: string; 32 | private _passengerCount: number; 33 | 34 | constructor(make:string, model: string, passengerCount:number){ 35 | this._make = make; 36 | this._model = model; 37 | this._passengerCount = passengerCount 38 | } 39 | 40 | get make():string{ 41 | return this._make 42 | } 43 | 44 | set make(newMake: string){ 45 | this._make = newMake; 46 | } 47 | 48 | get model():string{ 49 | return this._model 50 | } 51 | 52 | set model(newModel: string){ 53 | this._model = newModel; 54 | } 55 | 56 | get passengerCount():number{ 57 | return this._passengerCount 58 | } 59 | 60 | set passengerCount(newCount: number){ 61 | this._passengerCount = newCount; 62 | } 63 | 64 | describeCar(): string{ 65 | return `You are viewing the ${this._make} ${this._model}.` 66 | } 67 | 68 | countPassengers(): string{ 69 | return `You are can seat ${this._passengerCount} passengers in the ${this._make} ${this._model}.` 70 | } 71 | } 72 | 73 | class Camry extends Vehicle{ 74 | 75 | 76 | constructor(){ 77 | super('Toyota', 'Camry', 5) 78 | } 79 | 80 | 81 | 82 | } 83 | 84 | class Sienna extends Vehicle{ 85 | 86 | constructor(){ 87 | super('Toyota', 'Sienna', 5) 88 | } 89 | 90 | } 91 | 92 | abstract class VehicleOptions extends Vehicle{ 93 | decoratedVehicle: Vehicle 94 | 95 | //override the previous methods defined in the Abstract Vehicle class 96 | abstract describeCar():string; 97 | abstract countPassengers(): string; 98 | } 99 | 100 | class LeatherSeats extends VehicleOptions{ 101 | 102 | decoratedVehicle: Vehicle; 103 | 104 | constructor(vehicle:Vehicle){ 105 | super(vehicle.make, vehicle.model, vehicle.passengerCount); 106 | this.decoratedVehicle = vehicle; 107 | } 108 | describeCar(): string { 109 | return `${this.decoratedVehicle.describeCar()} It now has leather seats.` 110 | } 111 | countPassengers(): string { 112 | return `${this.decoratedVehicle.countPassengers()}` 113 | } 114 | 115 | } 116 | 117 | class CenterSeat extends VehicleOptions{ 118 | 119 | decoratedVehicle: Vehicle; 120 | 121 | constructor(vehicle:Vehicle){ 122 | super(vehicle.make, vehicle.model, vehicle.passengerCount); 123 | this.decoratedVehicle = vehicle; 124 | } 125 | 126 | describeCar(): string { 127 | 128 | if(this.decoratedVehicle['decoratedVehicle'] instanceof Sienna){ 129 | return `${this.decoratedVehicle.describeCar()} It now has the center seat on the second row.` 130 | } else{ 131 | return `${this.decoratedVehicle.describeCar()} This vehicle doesn't have the second row.` 132 | } 133 | } 134 | 135 | countPassengers(): string { 136 | if(this.decoratedVehicle['decoratedVehicle'] instanceof Sienna){ 137 | this.decoratedVehicle['decoratedVehicle'].passengerCount++ 138 | } 139 | return `${this.decoratedVehicle.countPassengers()}` 140 | } 141 | } 142 | 143 | let mySienna:Sienna = new Sienna() 144 | let myCamry:Camry = new Camry() 145 | 146 | //Add leather seats 147 | mySienna = new LeatherSeats(mySienna); 148 | myCamry = new LeatherSeats(myCamry); 149 | 150 | //Add the center seat for the minivan's second row 151 | mySienna = new CenterSeat(mySienna); 152 | myCamry = new CenterSeat(myCamry); 153 | 154 | console.log(mySienna.describeCar()) 155 | console.log(myCamry.describeCar()) 156 | 157 | console.log(mySienna.countPassengers()) 158 | console.log(myCamry.countPassengers()) -------------------------------------------------------------------------------- /Facade.ts: -------------------------------------------------------------------------------- 1 | //tsc Facade.ts && node Facade.js 2 | 3 | class DoorAssembly{ 4 | 5 | assembleHinges(){ 6 | console.log("Screw on the door hinges") 7 | } 8 | 9 | attachDoors(){ 10 | console.log("Attaching the door to the frame") 11 | } 12 | } 13 | 14 | class WheelAssembly{ 15 | 16 | makeWheelRim(){ 17 | console.log("Forging the wheel rim") 18 | } 19 | 20 | mountTire(){ 21 | console.log("Mounting the tire on the wheel") 22 | } 23 | 24 | installWheel(){ 25 | console.log("Putting the wheel on the hub") 26 | } 27 | 28 | } 29 | 30 | class SeatAssembly{ 31 | 32 | createSeatFrame(){ 33 | console.log("Creating the seat's frame") 34 | } 35 | 36 | attachSeatToFloor(){ 37 | console.log("Seat is being attached") 38 | } 39 | } 40 | 41 | class Electronics{ 42 | 43 | installNavigationSystem(){ 44 | console.log("Installing the navigation system in the dashboard") 45 | } 46 | 47 | installDashboard(){ 48 | console.log("Installing the dashboard") 49 | } 50 | } 51 | 52 | class CarAssemblyFacade{ 53 | 54 | private _doorAssembly:DoorAssembly; 55 | private _wheelAssembly:WheelAssembly; 56 | private _seatAssembly:SeatAssembly; 57 | private _electronics:Electronics; 58 | 59 | constructor(doorBuild: DoorAssembly, wheelBuild: WheelAssembly, seatBuild: SeatAssembly, electronicBuild:Electronics){ 60 | this._doorAssembly = doorBuild; 61 | this._wheelAssembly = wheelBuild; 62 | this._seatAssembly = seatBuild; 63 | this._electronics = electronicBuild 64 | } 65 | 66 | 67 | buildInternals(){ 68 | this._seatAssembly.createSeatFrame() 69 | this._seatAssembly.attachSeatToFloor() 70 | 71 | this._electronics.installDashboard() 72 | this._electronics.installNavigationSystem() 73 | } 74 | 75 | buildExternals(){ 76 | this._doorAssembly.assembleHinges() 77 | this._doorAssembly.attachDoors() 78 | 79 | this._wheelAssembly.makeWheelRim() 80 | this._wheelAssembly.mountTire() 81 | this._wheelAssembly.installWheel() 82 | } 83 | } 84 | 85 | const doorBuild = new DoorAssembly(); 86 | const wheelBuild = new WheelAssembly(); 87 | const seatBuild = new SeatAssembly(); 88 | const electronics = new Electronics(); 89 | 90 | const carBulder = new CarAssemblyFacade(doorBuild,wheelBuild,seatBuild,electronics); 91 | 92 | carBulder.buildExternals() 93 | carBulder.buildInternals() 94 | -------------------------------------------------------------------------------- /Factory.ts: -------------------------------------------------------------------------------- 1 | //tsc Factory.ts && node Factory.js 2 | 3 | class Car{ 4 | make: string; 5 | model: string; 6 | passengerCount: number; 7 | driveTrain: string 8 | } 9 | 10 | abstract class AutomobileFactory{ 11 | car: Car; 12 | 13 | constructor(){} 14 | 15 | abstract buildCar(type: Car) : void; 16 | 17 | } 18 | 19 | class AutomobileCreator extends AutomobileFactory{ 20 | 21 | buildCar(type: Car){ 22 | if(type.make == 'Toyota'){ 23 | return new ToyotaFactory().buildCar(type) 24 | } else if (type.make == 'Honda'){ 25 | return new HondaFactory().buildCar(type) 26 | } else{ 27 | return 'Not found' 28 | } 29 | 30 | } 31 | 32 | } 33 | 34 | class ToyotaFactory{ 35 | 36 | buildCar(type: Car){ 37 | console.log(`${type.passengerCount} passenger ${type.make} ${type.model} with a ${type.driveTrain} engine was just made!`) 38 | } 39 | 40 | } 41 | 42 | class HondaFactory{ 43 | 44 | buildCar(type: Car){ 45 | console.log(`You just built a ${type.passengerCount} passenger ${type.make} ${type.model} with a ${type.driveTrain} engine.`) 46 | } 47 | } 48 | 49 | const toyotaMinivan = new AutomobileCreator().buildCar({make: 'Toyota', model:'Sienna', passengerCount: 8, driveTrain:'V6'}) 50 | const hondaMinivan = new AutomobileCreator().buildCar({make: 'Honda', model:'Odyssey', passengerCount: 8, driveTrain:'V6'}) 51 | 52 | 53 | // class Car{ 54 | // model: string; 55 | // passengerCount: number; 56 | // driveTrain: string 57 | // } 58 | 59 | // abstract class AutomobileFactory{ 60 | // make: string; 61 | 62 | // constructor(make: string){ 63 | // this.make = make; 64 | // } 65 | 66 | // abstract buildCar(type: Car) : void; 67 | 68 | // } 69 | 70 | 71 | // class ToyotaFactory extends AutomobileFactory{ 72 | 73 | // buildCar(type: Car){ 74 | // console.log(`${type.passengerCount} passenger ${this.make} ${type.model} with a ${type.driveTrain} engine was just made!`) 75 | // } 76 | 77 | // } 78 | 79 | // class HondaFactory extends AutomobileFactory{ 80 | 81 | // buildCar(type: Car){ 82 | // console.log(`You just built a ${type.passengerCount} passenger ${this.make} ${type.model} with a ${type.driveTrain} engine.`) 83 | // } 84 | // } 85 | 86 | // const toyotaFactory = new ToyotaFactory('Toyota') 87 | // toyotaFactory.buildCar({model:'Sienna', passengerCount: 8, driveTrain:'V6'}) 88 | 89 | // const hondaFactory = new HondaFactory('Honda') 90 | // hondaFactory.buildCar({model:'Odyssey', passengerCount: 8, driveTrain:'V6'}) 91 | -------------------------------------------------------------------------------- /Iterator.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Using Generics - Basically allowing the interface to accept any type of data 3 | the user inputs, but enforcing the same data type is output. This is denoted by the 4 | suffix 5 | */ 6 | 7 | // run with tsc --target es2017 Iterator.ts && node Iterator.js 8 | 9 | class MyIteratorClass implements Iterator{ 10 | 11 | private _index: number = 0 12 | private _data: any[] =[] 13 | 14 | constructor(data: any[]) { 15 | this._data = data; 16 | } 17 | 18 | 19 | next(): IteratorResult { 20 | const result = this._data[this._index] 21 | this._index++; 22 | if(this._index <= this._data.length){ 23 | return {value: result, done: false} 24 | } else{ 25 | return {value: null, done: true} 26 | } 27 | } 28 | 29 | 30 | } 31 | 32 | const someData = [ "one", "two", "three"] 33 | const iterable = new MyIteratorClass(someData) 34 | 35 | console.log(iterable.next()) 36 | console.log(iterable.next()) 37 | console.log(iterable.next()) 38 | console.log(iterable.next()) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Observer.ts: -------------------------------------------------------------------------------- 1 | //tsc Observer.ts && node Observer.js 2 | 3 | interface CruiseControlSubject{ 4 | 5 | registerSpeed( object: SpeedObserver) 6 | removeSpeed( object: SpeedObserver) 7 | tellSpedometer() 8 | 9 | } 10 | 11 | interface SpeedObserver{ 12 | 13 | checkSpeed(speed: number) 14 | 15 | } 16 | 17 | class Automobile implements CruiseControlSubject{ 18 | 19 | private currentSpeed: number; 20 | private speedObservers : SpeedObserver[] = [] 21 | 22 | setCruiseSpeed(speed: number){ 23 | console.log(`Setting the speed to ${speed} miles per hour`) 24 | this.currentSpeed = speed 25 | this.tellSpedometer() 26 | } 27 | 28 | 29 | registerSpeed(speedObsv: SpeedObserver){ 30 | this.speedObservers.push(speedObsv) 31 | } 32 | 33 | removeSpeed(speedObsv: SpeedObserver){ 34 | let index = this.speedObservers.indexOf(speedObsv) 35 | this.speedObservers.splice(index, 1); 36 | } 37 | 38 | tellSpedometer(){ 39 | for(let observer of this.speedObservers){ 40 | observer.checkSpeed(this.currentSpeed) 41 | } 42 | } 43 | } 44 | 45 | class InstrumentCluster implements SpeedObserver{ 46 | 47 | private subject: CruiseControlSubject 48 | 49 | // Register Instrument cluster to watch the Automobile. In other words, 50 | // register it as an observer to be notified of speed change of the 51 | // cruise control subject 52 | 53 | constructor(automobile: CruiseControlSubject){ 54 | this.subject = automobile 55 | automobile.registerSpeed(this) 56 | //register instrument cluster to listen for changes in speed 57 | } 58 | 59 | checkSpeed(speed: number){ 60 | console.log(`Updating the speedometer. Setting it to ${speed} miles per hour`) 61 | } 62 | 63 | } 64 | 65 | class PoliceRadar implements SpeedObserver{ 66 | 67 | speedLimit: number = 55 68 | 69 | private subject: CruiseControlSubject 70 | 71 | constructor(automobile: CruiseControlSubject){ 72 | this.subject = automobile 73 | automobile.registerSpeed(this) 74 | } 75 | 76 | checkSpeed(speed: number){ 77 | if (speed > (this.speedLimit+5)){ 78 | console.log('Bad boy bad boy, whatcha gonna do? Whatcha gona do when they come for you') 79 | }else{ 80 | console.log('Patience...No tickets yet') 81 | } 82 | } 83 | } 84 | 85 | let fastCar = new Automobile() 86 | // Pass in the fast car subject 87 | let speedometer = new InstrumentCluster(fastCar) 88 | let cop = new PoliceRadar(fastCar) 89 | 90 | fastCar.setCruiseSpeed(40) 91 | 92 | fastCar.setCruiseSpeed(65) 93 | 94 | -------------------------------------------------------------------------------- /Prototype.ts: -------------------------------------------------------------------------------- 1 | //tsc Prototype.ts && node Prototype.js 2 | 3 | class Car{ 4 | 5 | make: string 6 | model: string 7 | 8 | constructor(make:string, model: string){ 9 | this.make=make; 10 | this.model=model 11 | } 12 | drive(){ 13 | console.log(`Hey! The ${this.make} ${this.model} is driving`) 14 | } 15 | stop(){ 16 | console.log(`Hey! The ${this.make} ${this.model} is stopping`) 17 | } 18 | } 19 | 20 | const civic = new Car('Honda','Civic') 21 | console.log(civic.drive()) 22 | 23 | 24 | // Traditional JavaScript 25 | 26 | // const carFunctions = { 27 | // drive(){ 28 | // console.log(`Hey! The ${this.make} ${this.model} is driving`) 29 | // }, 30 | // stop(){ 31 | // console.log(`Hey! The ${this.make} ${this.model} is stopping`) 32 | // } 33 | // } 34 | 35 | // function Car (make, model) { 36 | // let car = Object.create(carFunctions); 37 | // car.make = name; 38 | // car.model = model; 39 | 40 | // return car 41 | // } 42 | 43 | // const honda = Car('Honda','Civic') 44 | // console.log(honda.drive()) 45 | 46 | 47 | function CarPrototype(make, model){ 48 | this.make = make; 49 | this.model = model; 50 | } 51 | 52 | CarPrototype.prototype.drive = function() { 53 | console.log(`Heyt! The ${this.make} ${this.model} is driving`) 54 | } 55 | 56 | CarPrototype.prototype.stop = function(){ 57 | console.log(`Hey! The ${this.make} ${this.model} is stopping`) 58 | } 59 | 60 | const toyota = new CarPrototype('Toyota', 'Corolla') 61 | console.log(toyota.drive()) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TypeScriptPatterns -------------------------------------------------------------------------------- /Singleton.ts: -------------------------------------------------------------------------------- 1 | //tsc Singleton.ts && node Singleton.js 2 | 3 | class DBInstantiator { 4 | private static instance: DBInstantiator; 5 | 6 | private _connectionUser: string; 7 | private _connectionPassword: string; 8 | private _connectionHost: string; 9 | private _connectionPort: number; 10 | private _connectionDatabase: string; 11 | private _isConnected: boolean; 12 | 13 | private constructor() { } 14 | 15 | static getInstance() : DBInstantiator { 16 | if (!DBInstantiator.instance) { 17 | DBInstantiator.instance = new DBInstantiator(); 18 | DBInstantiator.instance._connectionUser = 'dbUser'; 19 | DBInstantiator.instance._connectionPassword = 'dbPass'; 20 | DBInstantiator.instance._connectionHost = 'localhost'; 21 | DBInstantiator.instance._connectionPort = 1234; 22 | DBInstantiator.instance._connectionDatabase = 'usersDb'; 23 | DBInstantiator.instance._isConnected = true; 24 | } 25 | return DBInstantiator.instance; 26 | } 27 | 28 | createAuthURL():string { 29 | return this._connectionUser + ":" + this._connectionPassword + "/" + this._connectionHost + ":" + this._connectionPort + "/" + this._connectionDatabase 30 | }; 31 | 32 | connectionStatus(){ 33 | return `this is the connection status: ${this._isConnected}` 34 | } 35 | connect():boolean{ 36 | return this._isConnected = true; 37 | } 38 | 39 | disconnect():boolean{ 40 | return this._isConnected = false; 41 | } 42 | 43 | } 44 | 45 | const dbConnection = DBInstantiator.getInstance() 46 | console.log(dbConnection.createAuthURL()) 47 | console.log(dbConnection.connectionStatus()) //true 48 | console.log(dbConnection.disconnect()) //sets to false 49 | console.log(dbConnection.connectionStatus()) //returns false 50 | 51 | const dbConnection2 = DBInstantiator.getInstance() 52 | console.log(dbConnection2.connectionStatus()) //returns false 53 | console.log(dbConnection2.connect()) //sets to true 54 | 55 | console.log(dbConnection.connectionStatus()) //true - shares the same instance of connectionStatus with dbConnection 2 56 | 57 | console.log(dbConnection === dbConnection2) //true 58 | -------------------------------------------------------------------------------- /State.ts: -------------------------------------------------------------------------------- 1 | //tsc State.ts && node State.js 2 | 3 | interface IVehicleOrderState{ 4 | 5 | buyVehicle(isSold?: boolean): void; 6 | payDeposit(payment?: number): void; 7 | buildVehicle(): void; 8 | shipVehicle(): void; 9 | } 10 | 11 | class OrderStatus{ 12 | 13 | currentState: IVehicleOrderState = new SoldState(this) 14 | 15 | constructor(){} 16 | 17 | buyVehicle(isSold? : boolean){ 18 | this.currentState.buyVehicle(isSold) 19 | } 20 | 21 | payDeposit(deposit?: number){ 22 | this.currentState.payDeposit(deposit) 23 | } 24 | 25 | buildVehicle(){ 26 | this.currentState.buildVehicle() 27 | } 28 | 29 | } 30 | 31 | class SoldState implements IVehicleOrderState{ 32 | 33 | isSold: boolean = false; 34 | deposit: number; 35 | 36 | constructor( private _orderStatus: OrderStatus, ){} 37 | 38 | buyVehicle(isSold?: boolean) { 39 | if(isSold == true){ 40 | this.isSold = isSold 41 | console.log('The car has been sold') 42 | this._orderStatus.currentState = new BalanceState(this._orderStatus, this.isSold) 43 | } else{ 44 | console.log('The car has not been sold') 45 | } 46 | } 47 | 48 | payDeposit(): void { 49 | throw new Error("Method not implemented."); 50 | 51 | } 52 | 53 | buildVehicle(): void { 54 | throw new Error("Method not implemented."); 55 | 56 | } 57 | shipVehicle(): void { 58 | throw new Error("Method not implemented."); 59 | } 60 | 61 | 62 | } 63 | 64 | class BalanceState implements IVehicleOrderState{ 65 | 66 | deposit: number = 0; 67 | soldStatus: boolean; 68 | 69 | constructor( private _orderStatus: OrderStatus, soldStatus){ 70 | this.soldStatus = soldStatus 71 | } 72 | 73 | buyVehicle(){ 74 | console.log('I think you may have already purchased a vehicle.') 75 | } 76 | 77 | payDeposit(deposit) { 78 | if(deposit > 0){ 79 | this.deposit = deposit 80 | console.log(`A $${this.deposit} deposit has been made`) 81 | this._orderStatus.currentState = new BuildState(this._orderStatus, this.deposit) 82 | } else{ 83 | console.log('No deposit has been made') 84 | } 85 | } 86 | buildVehicle(){ 87 | console.log("You have not made a deposit. Make a deposit to start building.") 88 | 89 | } 90 | shipVehicle(): void { 91 | throw new Error("Method not implemented."); 92 | } 93 | } 94 | 95 | class BuildState implements IVehicleOrderState{ 96 | 97 | deposit: number 98 | 99 | constructor( private _orderStatus: OrderStatus, deposit){ 100 | this.deposit = deposit 101 | } 102 | 103 | buyVehicle(): void { 104 | throw new Error("Method not implemented."); 105 | } 106 | 107 | payDeposit(): void { 108 | throw new Error("Method not implemented."); 109 | } 110 | buildVehicle(){ 111 | console.log('Building your vehicle') 112 | 113 | } 114 | shipVehicle(): void { 115 | throw new Error("Method not implemented."); 116 | } 117 | } 118 | 119 | class ShipState implements IVehicleOrderState{ 120 | 121 | constructor( private _orderStatus: OrderStatus){} 122 | 123 | buyVehicle(): void { 124 | throw new Error("Method not implemented."); 125 | } 126 | 127 | payDeposit(): void { 128 | throw new Error("Method not implemented."); 129 | } 130 | buildVehicle(): void { 131 | throw new Error("Method not implemented."); 132 | } 133 | shipVehicle(): void { 134 | throw new Error("Method not implemented."); 135 | } 136 | 137 | } 138 | 139 | const carPurhcase = new OrderStatus() 140 | carPurhcase.buyVehicle() 141 | carPurhcase.buyVehicle(true) 142 | carPurhcase.payDeposit() 143 | carPurhcase.buildVehicle() 144 | carPurhcase.payDeposit(200) 145 | carPurhcase.buildVehicle() 146 | --------------------------------------------------------------------------------