Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Counter {
- private static instance: Counter;
- private static count: number = 0;
- private constructor() { }
- public static getInstance(): Counter {
- if (!Counter.instance) {
- Counter.instance = new Counter();
- }
- return Counter.instance;
- }
- public getCount(): number {
- return Counter.count;
- }
- public increment(): void {
- Counter.count++;
- }
- }
- function clientCode() {
- const s1 = Counter.getInstance();
- const s2 = Counter.getInstance();
- if (s1 !== s2) throw new Error('Singleton doesnt work');
- s1.increment();
- console.log('s1:', s1.getCount());
- console.log('s2:', s2.getCount());
- }
- clientCode();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement