Suppose I have a class called CommandLineOperation
. This class accesses API resources. Thus I have defined one instance member of type APIAccessor
.
class CommandLineOperation {
APIAccessor apiAccessor;
void create() {
apiAccessor = new APIAccessor(email,password);
//do work for creation
}
void update() {
apiAccessor = new APIAccessor(email,password);
//do work for update
}
}
class APIAccessor {
String email;
String password;
APIAccessor(email,password) {
this.email = email;
this.password = password;
}
}
The operations in CommandLine, are infrequent, is it a better approach to instantiate APIAccessor
under every operations or create once using constructor of CommandLineOperation
class. e.g.
CommandLineOperation(String email,String password) {
this.apiAccessor = new APIAccessor(email,password);
}
Please let me know or suggest good coding design pattern. Or suggest any reference book so that I can improve my coding standard based on the analysis. Thanks in advance.
Using the Code. So, in summary, an Instance member is a member that belongs to an Instance of an object (in our example, the objects are c1, c2, and c3) whereas a static member belongs to the class itself and does not require an instance of an object as was demonstrated by making a call to CloneGenerator.countClones().
Home/C#, Design Principles & Patterns/Use Provider Pattern to Make Code More Extensible. Provider pattern is an extremely useful pattern that allows you to write loosely coupled components in .Net framework. .Net CLR injects these components at run-time. The concept of provider model is very simple, yet extremely powerful.
In this post, we will go through one basic design pattern for each classified type. The Singleton Design Pattern is a Creational pattern, whose objective is to create only one instance of a class and to provide only one global access point to that object.
I've seen implementations of Singleton patterns where instance variable was declared as static variable in GetInstance method. Like this: The code is simpler, because it's compiler who responsible for creating this object only when GetInstance called for the first time.
Answer is: it depends - on your context/requirements.
Advantages of creating an ApiAccessor once when creating a CommandLineOperation instance:
Disadvantages:
But when you think about it: those disadvantages aren't much of an issue in the real world anyway.
Regarding the comments that the required credentials come from parsing files: that boils down to dependency injection!
Meaning: the CommandLineOperation class should not contain code to construct an ApiAccessor instance. That object should either be injected (via a dependency injection framework) - or provided via the constructor for example.
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