473,320 Members | 1,896 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,320 software developers and data experts.

Singleton/Abstract Factor issue

Consider the following problem (which I state with a simple example,
but it corresponds to a real problem that I'm facing): Junior loves
pets, and that's fine with Mom and Dad, as long as he only has no more
than one of any given species.

Now, how can I use a Singleton to restrict Junior from having too many
pets?

+----------------+
+ ----->| << abstract >> |<-----+
| | Animal | |
| +----------------+ |
| | | |
| +----------------+ |
| | | |
| | Speak() | |
| | \ | |
| +-----\----------+ |
| \ |
| <<abstract>> |
+-----+ +-----+
| Dog | | Cat |
+-----+ +-----+

So, we could implement our Speak() methods like this:

For Dog:

Overrides Sub Speak()
Console.WriteLine("Arf!")
End Sub

For Cat:

Overrides Sub Speak()
Console.WriteLine("Meow!")
End Sub

The problem I'm facing is this: how do I restrict the creation of Dog and Cat
classes while avoiding redundant code. I mean, it's easy simple to implement
each class as separate singletons, but that's going to get old after a while
if I also have to create a Hampster, a Parrot, a Mouse, a Rat, a Guinea Pig, etc.

I started working with an Abstract Factory--or something like it:

+----------------------+
| << abstract >> |
| AnimalCreator |
+----------------------+
| m_objAnimal: Animal |
+--->+----------------------+
| | Create(): Animal |
| +----------------------+
| /|\
| |
+------------------+ |
| DogCreator | |
+------------------+ |
| Create(): Animal | |
+------------------+ |
|
+------------------+ |
| CatCreator | |
+------------------+------+
| Create(): Animal |
+------------------+

(Animal, Dog, and Cat as above)

Problem is: I wanted to use a static variable (AnimalCreator.m_objAnimal) to store a reference
to a single instance of each animal. Little did I know (until the code behaved incorrectly)
that a single instance of m_objAnimal is shared by all classes derived from AnimalCreator.

So, what's a good way around this problem?

The code follows at the end of this message.

Pierre the Perplexed Programmer
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections

Public MustInherit Class Animal

Public MustOverride Sub Speak()

End Class

Public Class Dog
Inherits Animal

Public Overrides Sub Speak()
Console.WriteLine("Arf!")
End Sub
End Class

Public Class Cat
Inherits Animal

Public Overrides Sub Speak()
Console.WriteLine("Meow")
End Sub
End Class

Public MustInherit Class AnimalCreator

Protected Shared m_objAnimal As Animal

Public MustOverride Function Create() As Animal

End Class

Public Class DogCreator
Inherits AnimalCreator

Public Overrides Function Create() As Animal
If m_objAnimal Is Nothing Then
m_objAnimal = New Dog
End If
Return m_objAnimal
End Function
End Class

Public Class CatCreator
Inherits AnimalCreator

Public Overrides Function Create() As Animal
If m_objAnimal Is Nothing Then
m_objAnimal = New Cat
End If
Return m_objAnimal
End Function
End Class

Public Class Test
Public Shared Sub Main()
Dim objDogCreator As AnimalCreator = New DogCreator()
Dim objCatCreator As AnimalCreator = New CatCreator()

Dim objDog As Animal = objDogCreator.Create()
Dim objCat As Animal = objCatCreator.Create()

objDog.Speak()
objCat.Speak()

Console.ReadLine()
End Sub

Jul 21 '05 #1
2 1268
Pete the Perplexed Programmer wrote:

Consider the following problem (which I state with a simple example,
but it corresponds to a real problem that I'm facing): Junior loves
pets, and that's fine with Mom and Dad, as long as he only has no more
than one of any given species.

Now, how can I use a Singleton to restrict Junior from having too many
pets?


This strikes me as overkill. Why not just maintain a list of the Type
of each pet? Then, whenever Jr is thinking of adding a new pet, you
can just see if the PetTypeList.Contains( PossibleNewPet.GetType() ).

--

www.midnightbeach.com
Jul 21 '05 #2
Jon Shemitz <jo*@midnightbeach.com> wrote in message news:<42***************@midnightbeach.com>...
Pete the Perplexed Programmer wrote:

Consider the following problem (which I state with a simple example,
but it corresponds to a real problem that I'm facing): Junior loves
pets, and that's fine with Mom and Dad, as long as he only has no more
than one of any given species.

Now, how can I use a Singleton to restrict Junior from having too many
pets?


This strikes me as overkill. Why not just maintain a list of the Type
of each pet? Then, whenever Jr is thinking of adding a new pet, you
can just see if the PetTypeList.Contains( PossibleNewPet.GetType() ).


O.K, you want to have a singleton behavior for many classes with no
redundant code. To do that let's first define Singleton: A single
object instance class that has a global access and it is known to all.
There are two classic singleton implementations: 1) declare all the
methods as "static" (shared) and put the class constructor as private.
2) Control the object creation, and let only one instance to be
creating (private constructor, static member to hold the instance, and
static access method to that specific instance).
To make many objects singleton you need to control their creation and
you need to give them a well known access. You may use a repository (a
collection) that will hold your singleton instance. The repository
will be implemented as a classic singleton. Each of your singleton
class should have a private constructor (control creation). In each of
the singleton class static constructor, register the unique instance
in the repository (give it a name, so client will be able to query
your object by name). When ever a client needs the instance, he will
go to the repository and ask for that instance using the name you gave
for your instance. The CLR class loader will load your class as soon
as the client asks for it, then the static constructor will do its
magic and the client will get that instance.

Alon Fliess
Jul 21 '05 #3

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

Similar topics

1
by: Richard A. DeVenezia | last post by:
foo() generates elements with event handlers that invoke foo function properties. Is this an abhorrent or misthought pattern ? It allows just the one occurence of identifier /foo/ to be changed...
13
by: Stampede | last post by:
I woundered if the following would be possible: I want to create an abstract Singleton class, which implements the singleton behaviour with the limitation, that the unique object will not be...
21
by: Sharon | last post by:
I wish to build a framework for our developers that will include a singleton pattern. But it can not be a base class because it has a private constructor and therefore can be inherit. I thought...
13
by: Robert W. | last post by:
At the beginning of my C# days (about 6 months ago) I learned about the Singleton pattern and implemented for Reference data, such as the kind that appears in an Options dialog box. My Singleton...
10
by: Senna | last post by:
Hi Have a singleton class like this. public sealed class ProductAdapter { private static readonly ProductAdapter instance = new ProductAdapter(); private ProductAdapter(){}
2
by: Pete the Perplexed Programmer | last post by:
Consider the following problem (which I state with a simple example, but it corresponds to a real problem that I'm facing): Junior loves pets, and that's fine with Mom and Dad, as long as he only...
2
by: Kevin Newman | last post by:
I have been playing around with a couple of ways to add inheritance to a JavaScript singleton pattern. As far as I'm aware, using an anonymous constructor to create a singleton does not allow any...
0
by: Jeff Louie | last post by:
Johns ? got me to thinking so here is some prototype code that attempts to subclass a singleton. namespace SubclassSingleton { class NoahsArkWithOneMale { private Animal afa = new Animal;...
4
by: joes.staal | last post by:
Hi, I know this has been asked earlier on, however, none of the other threads where I looked solved the following problem. 1. I've got a native C++ library (lib, not a dll) with a singleton. 2....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.