简体   繁体   中英

Initializing a Class to access Methods

I am wondering what the best approach is to initialize a new instance of a class to access methods within my class. My Class establishes data connection and then has some methods to fetch data. In my controller i have multiple functions which make use of that class. So my question is can initialize the class once per Controller or do i need to do this per function or even per call to method as some function might call multiple methods or the same method multiple times. Currently i initialize the class once per function but what to make sure i am doing it the right way going forward.

To clarify a bit more, my class looks something like this

const couchbase = require("couchbase")
var config = require('../config/config')

 class CouchController {
    constructor() {
        this.cluster = new couchbase.Cluster(config.cluster);
        this.cluster.authenticate(config.userid, config.password)
        this.N1qlQuery = couchbase.N1qlQuery;

        this.bucket = this.cluster.openBucket('Contacts', function(err) {
        if (err) {
        console.error('Got error: %j', err);
        }
    });
        this.bucket2 = this.cluster.openBucket('mail_store', function(err) {
        if (err) {
        console.error('Got error: %j', err);
        }
    });

      }

      bucketWithName(name) {
        let buckets = { "mail": this.bucket2, "contacts": this.bucket}
        return buckets[name] || this.bucket // this.bucket is default
    }
               n1qlQuery_wId(bucketName,n1qlStr, id){

            let bucket = this.bucketWithName(bucketName)
            return new Promise((resolve,reject)=>{
                let statement = this.N1qlQuery.fromString(n1qlStr)
                statement.consistency(this.N1qlQuery.Consistency.REQUEST_PLUS)
                bucket.query(statement, id, (err, result, meta)=>{

                if(err){
                    console.log(err)
                    return reject(err)
                } 
                return resolve([result, meta])

                })
            })
            }

and in my controller i call it like this currently

farmRoutes.get('/list', async(req, res) => {
    try {

    var couchdb = new couch
    var myQuery = await cbQ.farmGrid(req.query, true)
    var myCount = await couchdb.n1qlQuery_wId("contacts",myQuery[0],[])
    var result = await couchdb.n1qlQuery_wId("contacts",myQuery[1],[] )

    res.status(200).json({ Success: true , Error: "", Message: "", "RowsAffected" : result[1].metrics.resultCount, "RowCount" : myCount[0][0].count,  Data: result[0]})

    } catch (error) {

        console.log(error)
        res.status(200).json({ Success: false , Error: error.code , Message: error.message})
    }
    })

I'm not sure you understand what classes and instantiation are used for. If you're having everything share the same methods from this class, and it's not storing data, then you can just use static methods on it and not instantiate it at all. If it's storing data, but that data is shared everywhere, you can just have a single global instance of it that everything uses (the "singleton pattern"). If you need multiple versions of the class with different data in each, THAT is when you'd instantiate multiple instances of the class.

Objects with methods exist so that they can have state stored in the object. So, you should create an instance of the object and keep it as long as you need its state.

If the object you are discussing has no lasting state, then there is typically no reason to keep it around and you would create one when you need it, then release it when done.

If there is no actual state in the object, then the methods should probably be made into static methods that you can just call anytime without creating a new instance.

We could help you a lot more specifically if we could see and understand your actual code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM