Processing math: 100%

Tuesday, March 3, 2020

Factory Design Pattern in Typescript

Javascript is not enough to implement ordinary factory design patternt that I want to mimic from C#, therefore I try to do it on Typescript, though nested class declaration is still not that straight forward in typescript:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Point {
  x: number;
  y: number;
 
  private constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
 
  static Factory = class {
    static pointXY(x: number, y: number) {
      return new Point(x, y);
    }
    static pointPolar(r: number, theta: number) {
      return new Point(
        r * Math.cos((theta * Math.PI) / 180),
        r * Math.sin((theta * Math.PI) / 180)
      );
    }
  };
}
now we can create our point by calling
1
const pt = Point.Factory.pointXY(10, 20);

No comments:

Post a Comment