Dear all,
I have a problem where I need to re-use the same instance of several classes over and over in my application. Like collections classes.
Is there a way, with reflection for example, of finding out at runtime if an instance of a class already exists and then using that instance?
Or do I have to create Singleton's for each of those classes?
Should I make a class that keeps track of all my other class instances? Is there maybe a pattern to do so?
Thanks in advance for any help.
7 2542 tlhintoq 3,525
Recognized Expert Specialist
If you only need ONE instance of a class, like a collection, you could make it STATIC and just use it with a variable that has global scope.
finding out at runtime if an instance of a class already exists
If it does exist didn't you have to assign it *to* something? Wouldn't you just check whatever variable you would have assigned that instance to?
Ok on the first bit. Yes I could make it static. The problem is that I need this instance in several other different classes then where it was created.
So - Class A
-
{
-
/// Some methods
-
}
-
-
Class B
-
{
-
A = new A();
-
a.DoSomething();
-
}
-
-
Class C
-
{
-
// need same instance of A that B created...
-
}
You see what my problem is? An I have like 10 classes where I would need a particular instance of this one class? @tlhintoq
Yes, but that variable is in another class as above.
Markus 6,050
Recognized Expert Expert
Hmm, they'd have to be singletons, no? Also, one class creating a concrete instance of another class breaks encapsulation, doesn't it (unless the object is passed in as an argument)?
I agree Markus, I think that I would need to implement the Factory pattern or some such to get around my problem. Unless there's another way?
GaryTexmo 1,501
Recognized Expert Top Contributor
What I took from what tlhintoq said was make a public class with a public static member that you can access... - public class GlobalContainer
-
{
-
public static A MyA = new A();
-
}
then... - Class B
-
{
-
//A = new A();
-
//a.DoSomething();
-
GlobalContainer.MyA.DoSomething();
-
}
-
-
Class C
-
{
-
// need same instance of A that B created...
-
GlobalContainer.MyA.<whatever>
-
}
To be honest, I don't know what a singleton is... wikipedia seems to suggest that it's basically what I just wrote. I don't know what this has to do with "the Factory pattern" though...
Hopefully I've been of some help. Good luck!
tlhintoq 3,525
Recognized Expert Specialist - Class B
-
{
-
A = new A();
-
a.DoSomething();
-
}
Shouldn't this be -
A a = new A(); // so that a is a new instance of A so you can
-
a.DoSomething();
-
tlhintoq 3,525
Recognized Expert Specialist
What about this? Make lists of your classes at program level so all can see. - Class Program()
-
{
-
List<A> myAs = new List<A>;
-
List<B> myBs = new List<B>;
-
}
Then add to those lists: -
Class A
-
{
-
/// Some methods
-
}
-
-
Class B
-
{
-
A newA = new A();
-
newA.CreatedByProperty = "B";
-
program.MyAs.add(newA);
-
newA.DoSomething();
-
}
-
-
Class C
-
{
-
// need same instance of A that B created...
-
program.MyAs[MyAs.Count-1] {blah blah}
-
// The most recently added 'A' is the last one in the list
-
}
Now you have a List<> for each class that any other class can access.
You can add and search properties that let you know what type of class created it.
If you need to know any 'A' already just check the List<> MyA's.
If there is more than zero in the count, then an A exists.
If you need to know who made the existing 'A', check the CreatedBy property of each 'A' in the list
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Robert Oschler |
last post by:
Hello,
I am a Python newbie (by experience, not chronologically :) ), so if any of
this doesn't make sense my apologies in advance.
I am reading the chapter in The Python Cookbook on databases and the MySQLdb
module. In it they show an example of a recipe that lets you access fields
in a MySQL row by name rather than by column number. For example, given a
MySQL row object from a fetchone() call:
|
by: Peter |
last post by:
I use dynamically loaded dll's a lot in my programs. The one thing i cannot
figure out how do is too to sucessfully pass the address of a class instance
created within the dynamically loaded dll. I step thru the code and confirm
that the class is correctly created in the dll, but as soon as it steps out
of the dll i loose the address. For example:
hLib = LoadLibrary("RasterIO.dll");
ImageIOClass *ImageIO = (ImageIOClass...
|
by: Graham |
last post by:
This has to do with class variables and instances variables.
Given the following:
<code>
class _class:
var = 0
#rest of the class
|
by: keith |
last post by:
I created a class libery which has name space Assembly
and class Assembly and compiled it.
Then created a C# project and called a method in
the external class
e.g.
Assembly dll;
dll=Assembly.LoadFrom(@"c:\app\Assembly.dll");
|
by: Buddy Ackerman |
last post by:
I created this class
Public Class HTMLFileInput : Inherits System.Web.UI.HtmlControls.HtmlInputFile
Public Property Data As String
Get
Return ViewState("HTMLFileInput.Data")
End Get
Set (ByVal Value As String)
| |
by: sashang |
last post by:
Hi
I'd like to use metaclasses to dynamically generate a class based on a
parameter to the objects init function.
For example:
class MetaThing(type):
def __init__(cls, name, bases, dict, extra_information):
super(MetaThing, cls).__init__(name, bases, dict)
|
by: wilkinson.philip |
last post by:
I have a javascript object which dynamically generates a table adding,
deleting and moving rows as the user clicks on buttons or links.
Problem is when I generate a table row and add the javascript method
call to my class, I have to put the object instance name variable of
the class in order for it to be called from the onclick=function().
This is seriously limiting, but I'm stuck for a way round it. Heres a
edited of the code so you get...
|
by: jeff_j_dunlap |
last post by:
Hello,
Whenever I need class wide access to an object, I declare it
dynamically:
class myClass
{
...
myObject* obj; // declared dynamically
...
|
by: =?Utf-8?B?Sko=?= |
last post by:
I have a logging component that I will access in other assemblies. So it was
brought up to me that I should pass an instance around to these components
instead of just making the logging class static. If I make it static I
wouldn't need to
pass an instance around. What is your take on this?
|
by: =?Utf-8?B?SmVzc2ljYQ==?= |
last post by:
Hi All,
I know that I can use the GetProcAddress to get the proc address of a global
exported function from a WIn32 dll.
But if I have an exported class in the dll, is there a way to dynamically
load this dll and get an instance of this class? (No static linking with the
lib file) I am currently thinking about having global exported functions
which internally calls the member functions of the class's single instance.
These global...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |