473,614 Members | 2,487 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.WriteLi ne("Arf!")
End Sub

For Cat:

Overrides Sub Speak()
Console.WriteLi ne("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.Visua lBasic
Imports System
Imports System.Collecti ons

Public MustInherit Class Animal

Public MustOverride Sub Speak()

End Class

Public Class Dog
Inherits Animal

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

Public Class Cat
Inherits Animal

Public Overrides Sub Speak()
Console.WriteLi ne("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.C reate()
Dim objCat As Animal = objCatCreator.C reate()

objDog.Speak()
objCat.Speak()

Console.ReadLin e()
End Sub

Jul 21 '05 #1
2 1288
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.Con tains( PossibleNewPet. GetType() ).

--

www.midnightbeach.com
Jul 21 '05 #2
Jon Shemitz <jo*@midnightbe ach.com> wrote in message news:<42******* ********@midnig htbeach.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.Con tains( 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
2029
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 to /whatever/ when need arises and everything should still work. function foo () { var callee = arguments.callee
13
8296
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 created within the getInstance() method. The classes which are derived from the Singleton class, have to implement a static constructor, where they load an instance into the static unique variable. Now I have to problems with that:
21
2453
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 maybe a Template can be use for that, but C# does not support Templates (will be C# generics in mid 2005). Does anyone have a solution on how the singleton pattern can be written, in C#, as a framework/ infrastructure class, so users can use this...
13
3052
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 code looks like this: public sealed class Reference { private static readonly Reference instance = new Reference(); // Make the default constructor private, so that nothing can directly create it.
10
1691
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
330
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 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 >> |<-----+
2
6326
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 kind of inheritance: singletonObj = new function() { this.prop = true; } Here are two ways to create a singleton with inheritance:
0
901
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; static void Main(string args) {
4
2864
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. I've got a C++/CLI program with a wrapper around some functions in the singleton of the native lib. 3. When I run my program, the wrappers instantiate their own copy of the singleton, i.e.
0
8142
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
8642
Oralloy
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...
1
8294
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
7115
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
4058
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
4138
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2575
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
1
1758
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1438
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.