Advertisement
Idanref

Drones Factory Example

Aug 11th, 2023 (edited)
1,516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Drone Interface
  2. interface Drone {
  3.   fly(): string;
  4. }
  5.  
  6. // Concrete Drone 1: Simple Plastic Drone
  7. class SimplePlasticDrone implements Drone {
  8.   fly(): string {
  9.     return 'Flying a simple plastic drone';
  10.   }
  11. }
  12.  
  13. // Concrete Drone 2: Drone With Missiles
  14. class DroneWithMissiles implements Drone {
  15.   fly(): string {
  16.     return 'Flying a drone with missiles';
  17.   }
  18. }
  19.  
  20. // Concrete Drone 3: Kamikaza Drone
  21. class KamikazaDrone implements Drone {
  22.   fly(): string {
  23.     return 'Flying a kamikaza drone';
  24.   }
  25. }
  26.  
  27. // Drone Factory
  28. class DronesFactory {
  29.   createDrone(type: string): Drone {
  30.     switch (type) {
  31.       case 'simple':
  32.         return new SimplePlasticDrone();
  33.       case 'missiles':
  34.         return new DroneWithMissiles();
  35.       case 'kamikaza':
  36.         return new KamikazaDrone();
  37.       default:
  38.         throw new Error('Invalid drone type');
  39.     }
  40.   }
  41. }
  42.  
  43. // Client Code
  44. const factory = new DronesFactory();
  45. const simpleDrone = factory.createDrone('simple');
  46. console.log(simpleDrone.fly()); // Output: 'Flying a simple plastic drone'
  47.  
  48. const missileDrone = factory.createDrone('missiles');
  49. console.log(missileDrone.fly()); // Output: 'Flying a drone with missiles'
  50.  
  51. const kamikazaDrone = factory.createDrone('kamikaza');
  52. console.log(kamikazaDrone.fly()); // Output: 'Flying a kamikaza drone'
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement