class Foo{
}
var instance: Foo;
export function getFooInstance(){
/* logic */
}
or
export class Foo{
private static _instance;
private constructor(){};
public getInstance(){/* logic */}
}
// Use it like this
Foo.getInstance()
I want to make sure there is only one way instance of the object ? Any other suggestions apart from this ?
Typescript Playground link for both:
If you want to use the getter in the class then it needs to be static:
export class Foo{
private static _instance;
private constructor(){};
public static getInstance(){/* logic */}
}
The thing is that while the compiler will enforce this private visibility, in runtime it will still be possible to bypass it, even unintentionally, if for example someone uses that from javascript directly.
If you enforce it using a module/namespace then you can completely hide it:
Using a module:
export interface IFoo {}
class Foo implements IFoo {}
var instance: Foo;
export function getFooInstance(): IFoo {
/* logic */
return instance;
}
It's your code, I just aded the IFoo
interface (which is also exported) so that who ever gets an instance will know the interface but not the class.
Using a namespace:
namespace Foo {
export interface IFoo {}
class FooClass implements IFoo {}
const instance = new FooClass();
export function getInstance(): IFoo {
return instance;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With