473,404 Members | 2,195 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

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(LogFilename)

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 1433
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(LogFilename)

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**@valhallalegends.comschreef in bericht
news:qe********************************@4ax.com...
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(LogFilename)

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(LogFilename)

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(LogFilename)

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.WriteLine("Get Instance() called.")
If (mLogWriter Is Nothing) Then
mLogWriter = New LogWriter()
End If
Console.WriteLine("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.WriteLine(" Message = """ + Message + """")
Dim sw As System.IO.StreamWriter = New
System.IO.StreamWriter(_filename)
sw.WriteLine(Message)
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.Instance()
Logger.Filename = LogFilename
Logger.WriteLine("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.Instance()
Logger.Filename = LogFilename
Logger.WriteLine("Files class online!")
End Sub
End Class
End Namespace

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

Module Module1

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

Private Sub TestFiles()
Console.WriteLine("TestFiles() .. expecting old filename =
""""" + vbCrLf)
Dim LogFilename As String = "C:\TEMP\First.txt"
Dim pFiles As GrokQuestion.GrokQuestion.Files = New
GrokQuestion.GrokQuestion.Files(LogFilename)
Console.WriteLine()
End Sub

Private Sub TestFolders()
Console.WriteLine("TestFolders() .. expecting old filename =
""C:\Test\First.txt""" + vbCrLf)
Dim LogFilename As String = "C:\TEMP\Second.txt"
Dim pFolders As GrokQuestion.GrokQuestion.Folders = New
GrokQuestion.GrokQuestion.Folders(LogFilename)
Console.WriteLine()
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
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...
16
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...
166
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
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...
7
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...
9
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,...
15
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
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...
1
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: #-----------------...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.