473,785 Members | 2,298 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class Scoping Confusion

In writing a class library, one of the classes should only ever be
instantiated once, and its object should be accessible to every other
class in the library. How can I do that?

To provide some actual names for discussion, I'm trying to do this
with a custom log-writing class, named LogWriter.vb. So I would like
to declare ..

Class library project:
LogWriter.vb
Drives.vb
Folders.vb
Files.vb

Friend Logger As LogWriter = new LogWriter(LogFi lename)

and have Drivers, Folders, and Files classes all be able to use the
sole instantiation "Logger" in their code.

Hints on how to organize this properly?
Dec 18 '07 #1
6 1446
Grok wrote:
In writing a class library, one of the classes should only ever be
instantiated once, and its object should be accessible to every other
class in the library. How can I do that?
To provide some actual names for discussion, I'm trying to do this
with a custom log-writing class, named LogWriter.vb. So I would like
to declare ..

Class library project:
LogWriter.vb
Drives.vb
Folders.vb
Files.vb

Friend Logger As LogWriter = new LogWriter(LogFi lename)

and have Drivers, Folders, and Files classes all be able to use the
sole instantiation "Logger" in their code.

Hints on how to organize this properly?
Properly? Don't know, but here's how I'd throw it together:

Public Class LogWriter
Public ReadOnly Property Drives() as Drives
Get
Return New Drives( Me )
End Get
End Property
End Class

Public Class Drives
Private Sub New()
End Sub

Friend Sub New( ByVal parent as LogWriter )
m_parent = parent
End Sub

Private m_parent as LogWriter = Nothing

Private ReadOnly Property Parent() as LogWriter
Get
return m_parent
End Get
End Property

End Class

Note the accessors on the Classes and Constructors.

Anyone "out there" can create an instance of LogWriter - it's
constructor is Public. They can't, however, create an instance of
Drives /directly/ - it's constructor is only accessible /inside/ your
library [assembly].

To get one, they have to use the Drives property on the LogWriter class,
which means that your code gets a look in and can deal with linking the
two objects together.
Of course, the Drives property doesn't /have/ to be Public...

HTH,
Phill W.
Dec 18 '07 #2
Grok,

Normally it is just setting a reference to your library (dll).
This can using project or by right clicking on the reference tab in your
solution explorer

Cor
"Grok" <gr**@valhallal egends.comschre ef in bericht
news:qe******** *************** *********@4ax.c om...
In writing a class library, one of the classes should only ever be
instantiated once, and its object should be accessible to every other
class in the library. How can I do that?

To provide some actual names for discussion, I'm trying to do this
with a custom log-writing class, named LogWriter.vb. So I would like
to declare ..

Class library project:
LogWriter.vb
Drives.vb
Folders.vb
Files.vb

Friend Logger As LogWriter = new LogWriter(LogFi lename)

and have Drivers, Folders, and Files classes all be able to use the
sole instantiation "Logger" in their code.

Hints on how to organize this properly?
Dec 18 '07 #3


"Grok" wrote:
In writing a class library, one of the classes should only ever be
instantiated once, and its object should be accessible to every other
class in the library. How can I do that?

To provide some actual names for discussion, I'm trying to do this
with a custom log-writing class, named LogWriter.vb. So I would like
to declare ..

Class library project:
LogWriter.vb
Drives.vb
Folders.vb
Files.vb

Friend Logger As LogWriter = new LogWriter(LogFi lename)

and have Drivers, Folders, and Files classes all be able to use the
sole instantiation "Logger" in their code.

Hints on how to organize this properly?
I think your subject through the others off the track. You seem to want to
create a singleton class. One way that I use is to create a private
constructor, and public shared instance method. The instance method checks
to see if a copy exists.

public class Logger
private mLogger as Logger = Nothing

private property Instance as Logger
get
if (mLogger is Nothing) then
mLogger = new Logger()
endif
return mLogger
end get
end property

private sub New()
end sub
end class

Dec 18 '07 #4
public class Logger
private mLogger as Logger = Nothing

private property Instance as Logger
get
if (mLogger is Nothing) then
mLogger = new Logger()
endif
return mLogger
end get
end property

private sub New()
end sub
end class
Sorry, temporary insanity, and typing off the IDE. The Instance property
should be public, not private...

Dec 18 '07 #5


"Phill W." wrote:
Grok wrote:
In writing a class library, one of the classes should only ever be
instantiated once, and its object should be accessible to every other
class in the library. How can I do that?
To provide some actual names for discussion, I'm trying to do this
with a custom log-writing class, named LogWriter.vb. So I would like
to declare ..

Class library project:
LogWriter.vb
Drives.vb
Folders.vb
Files.vb

Friend Logger As LogWriter = new LogWriter(LogFi lename)

and have Drivers, Folders, and Files classes all be able to use the
sole instantiation "Logger" in their code.

Hints on how to organize this properly?

Properly? Don't know, but here's how I'd throw it together:

Public Class LogWriter
Public ReadOnly Property Drives() as Drives
Get
Return New Drives( Me )
End Get
End Property
End Class

Public Class Drives
Private Sub New()
End Sub

Friend Sub New( ByVal parent as LogWriter )
m_parent = parent
End Sub

Private m_parent as LogWriter = Nothing

Private ReadOnly Property Parent() as LogWriter
Get
return m_parent
End Get
End Property

End Class

Note the accessors on the Classes and Constructors.

Anyone "out there" can create an instance of LogWriter - it's
constructor is Public. They can't, however, create an instance of
Drives /directly/ - it's constructor is only accessible /inside/ your
library [assembly].

To get one, they have to use the Drives property on the LogWriter class,
which means that your code gets a look in and can deal with linking the
two objects together.
Of course, the Drives property doesn't /have/ to be Public...

HTH,
Phill W.
Sorry Phill. I missed this when I posted... I didn't copy your paper!

Dec 18 '07 #6
Thanks for the replies. Yes, I described the question poorly. It is
solved now. Here is the completed, working solution and test code.

Family Tree Mike, I was not grasping how to use the Instance property
as you intended, so was getting two LogWriter objects instead of one.

All your solution needed was the Shared keyword.

===== Implementation =====
'file: LogWriter.vb
Imports System.IO
Namespace GrokQuestion
'file: LogWriter.vb
'singleton to write logfile; used by public classes
Friend Class LogWriter
Shared mLogWriter As LogWriter = Nothing
Shared _filename As String
Friend Sub New()
End Sub
Shared ReadOnly Property Instance() As LogWriter
Get
Console.WriteLi ne("Get Instance() called.")
If (mLogWriter Is Nothing) Then
mLogWriter = New LogWriter()
End If
Console.WriteLi ne("Old Filename = """ + _filename +
"""")
Return mLogWriter
End Get
End Property
Public Property Filename() As String
Get
Return _filename
End Get
Set(ByVal value As String)
_filename = value
End Set
End Property
Public Sub WriteLine(ByVal Message As String)
'open file, write Message, close file
Console.WriteLi ne(" Message = """ + Message + """")
Dim sw As System.IO.Strea mWriter = New
System.IO.Strea mWriter(_filena me)
sw.WriteLine(Me ssage)
sw.Close()
End Sub
End Class
End Namespace

'file: Folders.vb
Namespace GrokQuestion
'file: Folders.vb
Public Class Folders
Private Logger As LogWriter
Public Sub New(ByVal LogFilename As String)
Logger = LogWriter.Insta nce()
Logger.Filename = LogFilename
Logger.WriteLin e("Folders class online!")
End Sub
End Class
End Namespace

'file: Files.vb
Namespace GrokQuestion
'file: Files.vb
Public Class Files
Private Logger As LogWriter
Public Sub New(ByVal LogFilename As String)
Logger = LogWriter.Insta nce()
Logger.Filename = LogFilename
Logger.WriteLin e("Files class online!")
End Sub
End Class
End Namespace

===== Test =====
Imports GrokQuestion

Module Module1

Sub Main()
TestFiles()
TestFolders()
End Sub

Private Sub TestFiles()
Console.WriteLi ne("TestFiles( ) .. expecting old filename =
""""" + vbCrLf)
Dim LogFilename As String = "C:\TEMP\First. txt"
Dim pFiles As GrokQuestion.Gr okQuestion.File s = New
GrokQuestion.Gr okQuestion.File s(LogFilename)
Console.WriteLi ne()
End Sub

Private Sub TestFolders()
Console.WriteLi ne("TestFolders () .. expecting old filename =
""C:\Test\First .txt""" + vbCrLf)
Dim LogFilename As String = "C:\TEMP\Second .txt"
Dim pFolders As GrokQuestion.Gr okQuestion.Fold ers = New
GrokQuestion.Gr okQuestion.Fold ers(LogFilename )
Console.WriteLi ne()
End Sub

End Module

===== Test Output =====
TestFiles() .. expecting old filename = ""

Get Instance() called.
Old Filename = ""
Message = "Files class online!"

TestFolders() .. expecting old filename = "C:\Test\First. txt"

Get Instance() called.
Old Filename = "C:\TEMP\First. txt"
Message = "Folders class online!"

--end
Dec 19 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
10039
by: Gaurav Veda | last post by:
Hi ! I am a poor mortal who has become terrified of Python. It seems to have thrown all the OO concepts out of the window. Penniless, I ask a basic question : What is the difference between a class and a function in Python ??? Consider the following code fragments : # Fragment 1 begins a = 1
16
2145
by: Michele Simionato | last post by:
I have read with interest the recent thread about closures. The funny thing is that the authors are arguing one against the other but I actually agree with all of them and I have a proposal that may be of some interest. To refresh your memory, I report here some quotation from that thread. Jacek Generowicz: > I sumbit to you that read-only closures are rare in Python because > they are a recent addition to the language.
166
8678
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
3
1938
by: Carmella | last post by:
Is it possible for a class to create an instance of a private nested class which raises events and then listen for those events? In the example below, when InnerClass sings, OuterClass should say Bravo . I am not sure about the scoping and I cannot get this to work. Thanks Mel Public Sub OuterClass Public Event Bravo() Protected WithEvents MyInnerClass as InnerClass
7
2116
by: WXS | last post by:
Vote for this idea if you like it here: http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=5fee280d-085e-4fe2-af35-254fbbe96ee9 ----------------------------------------------------------------------------- This is a consortium of ideas from another thread on topic ----------------------------------------------------------------------------- One of the big issues of organizing items within a class, is there are many...
9
1930
by: NevilleDNZ | last post by:
Can anyone explain why "begin B: 123" prints, but 456 doesn't? $ /usr/bin/python2.3 x1x2.py begin A: Pre B: 123 456 begin B: 123 Traceback (most recent call last): File "x1x2.py", line 13, in ? A() File "x1x2.py", line 11, in A
15
1818
by: Lighter | last post by:
I find a BIG bug of VS 2005 about string class! #include <iostream> #include <string> using namespace std; string GetStr() { return string("Hello");
17
2908
by: Chad | last post by:
The following question stems from Static vs Dynamic scoping article in wikipedia. http://en.wikipedia.org/wiki/Scope_(programming)#Static_versus_dynamic_scoping Using this sites example, if I go like this: #include <stdio.h> int x = 0;
1
1559
by: jholg | last post by:
Hi, regarding automatically adding functionality to a class (basically taken from the cookbook recipee) and Python's lexical nested scoping I have a question wrt this code: #----------------- import types # minor variation on cookbook recipee def enhance_method(cls, methodname, replacement):
0
9481
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,...
0
10155
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10095
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,...
0
9954
tracyyun
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...
0
8979
agi2029
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...
0
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2881
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.