Giter Club home page Giter Club logo

make-class-singleton's Introduction

@m9ch/make-class-singleton

npm version npm downloads

Install

via pnpm, yarn or npm:

pnpm add @m9ch/make-class-singleton
# or
yarn add @m9ch/make-class-singleton
# or
npm i -S @m9ch/make-class-singleton

Usage

Use as factory function:

import { Singleton as makeSingleton } from '@m9ch/make-class-singleton'

class Foo {}

const Singleton = makeSingleton(Foo)

const foo = new Singleton()
const bar = new Singleton()
console.log(foo === bar) // true

Use as ClassDecorator

Note

If using TypeScript, you might need to enable compilerOptions.experimentalDecorators in tsconfig.json or something like that.

Here is an example:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "modeResolution": "node",
    "experimentalDecorators": true
  }
}
import { Singleton } from '@m9ch/make-class-singleton'

@Singleton
class Foo {}

const foo = new Foo()
const bar = new Foo()
console.log(foo === bar) // true

Options

  • container: Where singleton instance should create and stored, default is a WeakMap object in this module.

Note

It might be unsafe if using default instance container in multi-thread environment, such as nodejs in swarm mode, or WebWorker.

By passing a thread shared WeakMap object may save (not verified).

License

MIT © Mitscherlich

make-class-singleton's People

Contributors

mitscherlich avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.