473,698 Members | 2,942 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

factory method

hello, im trying to solve my problem using factory method but im not
sure if im doing it correctly this is my sample code

class Base {
public:
Base();
virtual ~Base;
virtual void draw();
};

class Item1 : public Base {
public:
Item1();
~Item1();
void draw();
};

class Item2 : public Base {
public:
Item2();
~Item2();
void draw();
};

// factory method ?!
Base * getItem(int code)
{
if (code == 1 || code == 2)
return new Item1();
else if (code == 3 || code == 4)
return new Item2();
else
return 0;
}

Base * item = getItem(code);
if (item)
item->draw();
delete item;

the sad part is, "code" should have atleast 50 possible values and i
have atleast 8 classes derived from a single base class. am i doing
this right?! any suggestions would be appreciated, thanks...

Apr 6 '06 #1
3 3152
Well if you have 8 different items to draw then you have to impilement
8 different classes. If there are some common things you are doing in
those 8 classes then you can write some utility class and use it.

Also you can improve the getItem() like this:

Base * getItem(int code)
{
Base* newInstance = 0;
seitch( code )
{
case 1:
case 2: //You may add some more casese for which u have
return Item1.
newInstance = new Item1();
break;

case 3:
case 4: //Same here as above comment.
newInstance = new Item2();
break;

default:
newInstance = 0;
break:
}

return newInstance;
}

Apr 6 '06 #2
ji*********@gma il.com wrote:
hello, im trying to solve my problem using factory method but im not
sure if im doing it correctly this is my sample code

class Base {
public:
Base();
virtual ~Base;
virtual void draw();
};

class Item1 : public Base {
public:
Item1();
~Item1();
void draw();
};

class Item2 : public Base {
public:
Item2();
~Item2();
void draw();
};

// factory method ?!
Base * getItem(int code)
{
if (code == 1 || code == 2)
return new Item1();
else if (code == 3 || code == 4)
return new Item2();
else
return 0;
}

Base * item = getItem(code);
if (item)
item->draw();
delete item;

the sad part is, "code" should have atleast 50 possible values and i
have atleast 8 classes derived from a single base class. am i doing
this right?! any suggestions would be appreciated, thanks...


You could replace the if/else cascase with switch/case, wich makes it a bit
more readable IMHO:

switch (Code)
{
case 1:
case 2:
return new Item1();
case 3:
case 4:
return new Item2();
default:
return 0;
}

Generally, you should use an enum or constants instead of magic numbers.
Another possibility is to make the classes register with the factory. Then
you can write your program in such a way that the factory doesn't need to
know which derived classes exist.

Apr 6 '06 #3

ji*********@gma il.com wrote:
hello, im trying to solve my problem using factory method but im not
sure if im doing it correctly this is my sample code

class Base {
public:
Base();
virtual ~Base;
virtual void draw();
};

class Item1 : public Base {
public:
Item1();
~Item1();
void draw();
};

class Item2 : public Base {
public:
Item2();
~Item2();
void draw();
};

// factory method ?!
Base * getItem(int code)
{
if (code == 1 || code == 2)
return new Item1();
else if (code == 3 || code == 4)
return new Item2();
else
return 0;
}

Base * item = getItem(code);
if (item)
item->draw();
delete item;

the sad part is, "code" should have atleast 50 possible values and i
have atleast 8 classes derived from a single base class. am i doing
this right?! any suggestions would be appreciated, thanks...


I'm wrestiling with something similar to what you're doing so I'm
curious to see how the more seasoned veterans here respond. Implement
a 'Collection' - if you will class. So now:

#include <iostream>
#include <functional>
#include <algorithm>
#include <cassert>
# include <vector>

using namespace std;
class Base;
class Item1;
class Item2;

class ItemInteface
{
public:
virtual void draw( Base& ) { assert(false && "Not implemented."); }

virtual void draw( Item1& ) { assert(false && "Not implemented"); }

virtual void draw( Item2& ) { assert(false && "Not implemented"); }

virtual ~ItemInteface() ;
} ;

class Base {
public:
Base();
virtual ~Base();
virtual void draw(ItemIntefa ce& i ) { i.draw (*this); }

};
class Item1 : public Base {
public:
Item1();
~Item1();
virtual void draw(ItemIntefa ce& i ) { i.draw (*this); }
};

class Item2 : public Base {
public:
Item2();
~Item2();
virtual void draw(ItemIntefa ce& i ) { i.draw (*this); }
};

#if 0
// factory method ?!
Base * getItem(int code)
{
if (code == 1 || code == 2)
return new Item1();
else if (code == 3 || code == 4)
return new Item2();
else
return 0;
}
#endif

template<class T>
class Collection : public Base
{
vector<T*> t;
public:
Collection()
{
// determine some way to store base objects .. in t. this is 'a
hack' but
// hopefully illustrates the point
for (size_t i = 0; i < 2; ++i)
t.push_back( new T );
}
virtual void invoke( ItemInteface& toDraw ) // just invoke ..
{
cout << "Collection invoked.\n";
for (size_t i = 0; i < t.size(); ++i)
t[i]->draw( toDraw );
}
};
So you have a Collection of 'items' if you will.
An aside:
The difference between what you've alluded to and what I'm trying to do
surrounds the fact that each of my _items_ takes different arguments.
This complicates my 'draw' function ( in mine it's called 'process' )
so I'm stuck.

Apr 6 '06 #4

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

Similar topics

17
6640
by: Medi Montaseri | last post by:
Hi, Given a collection of similar but not exact entities (or products) Toyota, Ford, Buick, etc; I am contemplating using the Abstraction pattern to provide a common interface to these products. So I shall have an Abstract Base called 'Car' implemented by Toyota, Ford, and Buick. Further I'd like to enable to client to say Car *factory;
2
2977
by: Ryan Mitchley | last post by:
Hi all I have code for an object factory, heavily based on an article by Jim Hyslop (although I've made minor modifications). The factory was working fine using g++, but since switching to the Intel compiler it has stopped working. I think the singleton pattern static instance thing may be at the root of the problem, but I'm not sure. I had to add calls to instance() in regCreateFn, which gets the behaviour more in line with what I was...
4
8232
by: Eric | last post by:
Perhaps this question has been posed before (I'd be surprised if it hasn't) but I just gotta know... Is it possible to combine the Singleton and Factory Method design patterns in the same class? Let's start with your basic Singleton class: class Singleton {
10
1887
by: Chris Croughton | last post by:
What do people call their factory functions? 'new' is not an option (yes, it can be overloaded but has to return void*). The context is: class MyClass { public: // Factory functions static MyClass* new(int);
4
2523
by: max | last post by:
Hello, I analyze this design pattern for a long time but I do not understand how this pattern work and what the purpose is? (I looked a this site http://www.dofactory.com/Patterns/PatternAbstract.aspx). Could anybody try to explain me in his own words how this pattern work and what the purpose is? thanks in advance
10
5137
by: Mark | last post by:
I have an abstract class, and a set of classes that inherit from my abstract class. The fact that it is abstract is likely irrelevant. I have a static factory method in my abstract class that creates subclasses. The constructor in my subclasses must be able to call the constructor in my base class. For the factory method in my abstract class to call the constructor on my subclasses, the constructor in the subclass MUST be public (or...
8
1766
by: googlegroups | last post by:
Hi, I need to parse a binary file produced by an embedded system, whose content consists in a set of events laid-out like this: <event 1<data 1<event 2<data 2... <event n<data n> Every "event" is a single byte in size, and it indicates how long is the associated "data". Thus, to parse all events in the file, I need to take it like a stream and read one event at a time, consuming bytes
1
1748
by: =?Utf-8?B?RXJpYw==?= | last post by:
I am using the factory method to solve a problem where a factory can produce product. I have a base factory class and a base product class. The problem that I am having is that for every product subclass type I am having to create a factory subclass to handle differences in logic. They are becoming one to one. Is this ok? Should I look at another pattern to solve the problem? abstract Product Product1: inherits Product Product2:...
8
1731
by: Steven D'Aprano | last post by:
I'm writing a factory function that needs to use keywords in the produced function, not the factory. Here's a toy example: def factory(flag): def foo(obj, arg): if flag: # use the spam keyword to method() return obj.method(spam=arg) else: # use the ham keyword
4
5010
by: Pallav singh | last post by:
Hi , when should i select Factory Method / Prototype Design Pattern during my design phase ?? as both look similar to me Thanks in Advance Thanks Pallav
0
8683
marktang
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...
0
8610
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
9170
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...
0
9031
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
8902
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
7740
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...
1
6528
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4372
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...
1
3052
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

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.