In need of a pattern for a common problem - what to instantiate?

I'm sure this is a common problem with a standard solution (in a form of well known pattern), but I am not aware of one nor do I have any idea how would I Google for it... So, here it goes (exemplified):
a user is presented with a combo box that enables him to choose what item he wishes to purchase. Depending on his choice, the application is supposed to instantiate an appropriate class that represents the purchased item. So, if the user chooses a book from the combo box, the class Book should be instantiated, if he chooses a comic book, the ComicBook class would be instantiated etc.
Apart from introducing a naming convention and instantiating the classes through Class.forName(), how would this problem be solved, in a way as generic as possible?
This is supposed to be used in a Web app, but I hardly believe that's relevant...

Hmmm... I'm using JSF but it's my first project so I don't really know it's powers.
I instantiated all classes that will eventually populate the combo box (through reflection) and now I'm trying to find one which of the objects did the user select.
Would it be a problem for you to give me at least a rough scatch of what I should do?
I tried it like this:
in my managed bean:
public HtmlSelectOneMenu getProductsMenu() {
        //instantiate and populate the list of products (prodlist)
        for (Product p : prodlist){
            optionlist.add(new SelectItem(p, p.getName()));
        final UISelectItems items = new UISelectItems();
        items.setValue(optionlist);
        productsMenu.getChildren().add(items);
        return productsMenu;
    }and in my JSP:
<h:selectOneMenu binding="#{managedBean.productsMenu}" />but then, in the bean, when I try:
((Product)productsMenu.getValue())I get a Class cast exception. it says it can't can't cast String to Product...
What am I doing wrong?
Thank you!

Similar Messages

  • Do I need a Singleton pattern for this case

    Hello,
    I'm writing a game in Java and I have a very simple score manager class which just tracks the points the player so far has. I need to access this class in different pars of my app (gui, game core ...) so I created a singleton class which looks like this
    public class ScoreManager {
            private static ScoreManager instance = new ScoreManager();
            private int score = 0;
         private int highScore = 0;
         public static ScoreManager getInstance() {
              return instance;
         public int getScore() {
              return score;
         public int getHighScore() {
              return highScore;
         public void addScore(int scoreToAdd){
              score += scoreToAdd;
              if(score > highScore) {
                   highScore = score;
    }so far so good ..
    I would like to read the "highScore" from a file when the game starts and write it back when the game ends. I added those two methods:
         public void init(File highScoreFile) {
              highScore = readFromFile(highScoreFile);
                    score = 0;               
         public void dispose(File highScoreFile) {
                   writeToFile(highScoreFile);
         }So basically I call the init() method when the game stars and the dispose() when the game ends.
    It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place.
    What would be a better way to do this ?
    Thanks for your help,
    Jesse

    safarmer wrote:
    You could keep track of the state (initialised, destroyed etc) in the manager and only perform the action if it is an expected state.
    private enum State { NOT_INITIALISED, INITIALISED, DESTROYED};
    private State currentState = State.NOT_INITIALISED;
    // i will leave the rest up to your imagination :) this looks good, thanks
    anotherAikman wrote:
    >
    It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place. And who would that be? You´re the only one using the code, aren´t you?
    If not, you could still include in the documentation where to call those methods.
    no I'm not the only one working on this. Documentation can be useful but does not prevent calling wrong methods.
    YoungWinston wrote:
    I don't see any constructor. Usually, a singleton class should have a private one, even if it has no parameters. If you don't have any, Java will create a public no-parameter one as default.ok I forgot the private constructor.
    It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place. Then my advice would be not to make them public. After all, your code is the only one calling these methods - yes?yes only the code of the app calls it.
    If you are convinced that your game requires one and only one score manager, then a singleton is probably the best way to go.
    I'm a little worried about the init() and dispose() methods though, because these suggest state changes, which is unusual for the singleton pattern. You may want to think about synchronizing them.
    An alternative might be to use properties to get and store your scores.ok for the synchronization. What would using the properties ? It would be just another type of storage backend and I'd still need to read/write it.
    Thanks for your help,
    J

  • HT5364 I need to download ios6 for my iPad two what do I do

    I need to download iOS 6 for iPad 2 I need help

    Sorry, that's not possible. Any upgrade will be to the latest compatible version, in this case 7.0.4

  • I need a Video Card for Adobe Premiere Elements, what is recommended?

    I wish to buy the Adobe Premiere Elements Video Editing. I shoot on a Cannon GL1 & GL3 mini dvd and need a video card to capture my video footage. What Video Card is recommended for use with the Premieire Elements software? and what is the price? Please advise...

    farney1946
    Is the purchased Premiere Elements 12 still in its sealed packaging?
    If you have not already, I would suggest that you install Premiere Elements 12 from the purchased installation disc
    and evaluate its performance in your computer environment.
    a. Does the program fail to install?
    b. Do you get Display Card errors?
    If you are worried about not being able to return 12 once the package is opened, then you can try the following
    a. Download the Premiere Elements 12 tryout files from the following web site and evaluate it as a tryout (full
    featured).
    http://prodesigntools.com/photoshop-elements-12-direct-download-links-premiere.html
    Read and carry out carefully the Note: Very Important Instructions section on the web page to avoid Access Denied message.
    b. If the tryout performs well for you, then delete the tryout and install your purchased version with the purchased
    serial number included on the packaging.
    ....other possibilities, but just the above for now.
    ATR

  • I need to ask a new question, but I need to include images for a better explanation, what source do you recommend?

    Hello everyone,
    I need to ask a new question, but i would like to do it more illustrative, showing some images, I am new on this forum and I would like to follow the best practices and standards on how to ask a "picture" question, is there a way i can refer to
    a source? i tried Instagram in the past is that ok?
    Thank you.

    After your forums account is verified, you can directly post/upload pictures into your posts, using the editor toolbar in the question/reply. This forum limits to two images per post/message.
    you can request your account be verified, by adding on to the thread here: (Verify your account NN)
    http://social.technet.microsoft.com/Forums/en-US/home?forum=reportabug
    Don
    (Please take a moment to "Vote as Helpful" and/or "Mark as Answer", where applicable.
    This helps the community, keeps the forums tidy, and recognises useful contributions. Thanks!)

  • My iPhone overheated while I was using it. An  error icon same up on the lock screen and in place of the clock it was written 'Temperature' and in place of the wallpaper it was written "Your iPhone needs to cool down for normal use".  What to do?

    The iPhone has become extremely hot where the camera is located and as one moves his hands away from the camera, the temperature gets cooler. Any solution?
    It is so hot around the camera that I cannot touch it.

    Leave the phone alone and let it cool down.

  • Flex design pattern for BlazeDS transfer objects

    Dear Community,
    I have a question regarding the nature of objects transferd from BlazeDS backend to the Flex client.
    According to some adobe docs all the presentation logic should be in flex and BlazeDS should provide only services.
    The question is what kind of transfer objects should be used? with what level of abstraction?
    To make it more clear let's talk about a simple forum application like adobe forums.
    I have created a Forum service, which returns a Forum transfer object, which has a List of Threads, with each thread having a List of Messages.
    Flex gets the Forum transfer object and does all the presentaiton work.
    This is a very nice seperatin of concerns architecture BUT there are two major performance issues:
    - when the forum becomes bigger the transfer object will be huge
    - the flex will use huge client resources to create the presentation of the forum transfer object.
    So my question is what is your strategy/ design pattern for such a problem.
    An obvious answer would be create services that include the presentation logic and use transfor objects like ThreadListPage which will include only the first 10 threads.
    Thanks in advance

    I think you are going to get a few varied types of answers to a general question like this, but I will comment on a few things.  First, you should only be transmitting the data that you need to use or display to the user at the time.  If this forum was implemented in Flex (I wish) you wouldn't transfer the text for all the threads.  You might not transfer the thread text at all (just the subjects), you'd make calls back to the server to fetch that data when and if you need it.
    Also, I think you are overestimating the resources required for the Flex "presentation layer".  If you think about it, these workstations we have here are pretty idle most of the time when you're at a website.  Nowadays there's plenty of processing power just sitting there waiting, so as long as your design isn't flawed the CPU or memory are rarely going to be a bottleneck with Flex.
    The way I design, BlazeDS (or GraniteDS etc) should mostly just be "serving data".  There is some flexibility available, for example I don't see a problem with putting certain types of business rules (such as a limit on the number of results that can be recieved in a search) within server side code, and validation rules on the Flex side.  So there's not too many "industry standards" in Flex yet beyond maybe what's done in the various standard architectures, at least not that I'm aware of.
    You might find it beneficial to look into some of the various frameworks/architectures available like Cairngorm, Mate, Swiz, and so on.  Learning how they work (looking at examples) would probably answer some of your questions too.

  • Trying to add a VPN but must enter password for credential storage.  What is that?  I never set a password for credential storage.

    I am trying to add a VPN and need to enter password for credential storage.  What is that?  I never set a password for credential storage.  Where do I get it?

    I've been trying to set up a VPN from my LG G2 and it also asks for the password for credential storage. However, entering the password associated with the VPN, does nothing. What are they asking for?

  • Radiation pattern for 1140 - need readable file

    Hello,
    I need a legible radiation pattern graph for the 1140 AP -- the antenna pattern
    This is for a wireless deployment application which models signal strength.
    It needs to be specific for the 1140 AP as the antenna has a Maximum gain of 3 dBi which is different than the antenna gain on the 1130 AP.
    Can anyone help?
    Thanks in advance
    Some manufacturers will provide a file of the the antenna plot coordinates - that would ideally be what I need.

    I found this file previously, but I can't read it. It seems like there should be an image of the antenna pattern that has better resolution than this. The application I use requires that 360 numbers be entered for the E-plane and 360 numbers for the H-plane.
    So a file of the antenna plot coordinates would really be what I need. Does cisco provide these?
    Thanks....

  • Books about MVVM, architecture, design patterns for Windows Phone 8.1

    Hi,
    I'm looking for a book or books (or other resources) that explain how to develop an app with a proper architecture. I mean what each layer (bussines layer, data layer, network access) should do and how should it look like. I'm also looking for a book about
    MVVM.
    Right now I'm struggling with how to create a layer for network communication - how to separate classes for requests and responses, how to manage requests and create some queue of requests and also to provide some way to cancel them when they are no longer
    needed, how to work with servers that use some level of security (cookies, certificates etc.).
    Another thing is caching - how to design a short-term cache or a persistant cache (database), what technologies I can use etc.
    Last thing that I'm struggling with is also naming. How to name classes in those layers, e.g. to distinguish between classes mapping data from some ORM database, for mapping on JSON in network communication. etc.
    I hope you got the idea :)
    Thanks.

    Currently, I don't find a book about MVVM pattern for Windows Phone 8.1, but I think MSDN and some blogs have some useful samples and conceptions: http://msdn.microsoft.com/en-us/library/windows/apps/jj883732.aspx
    http://channel9.msdn.com/Series/Windows-Phone-8-1-Development-for-Absolute-Beginners
    And I think your question includes too much scopes, maybe you need to split it into some blocks and get help in the related forum
    Best Regards,
    Please remember to mark the replies as answers if they help

  • CVP Opsconsole: Patterns for RNA timeout on outbound SIP calls - Dialed Number (DN) text box does not take any input

    Hi there,
    I'm having problems modifying the 'Dialed Number (DN)' text box under 'Advanced Configuration->Patterns for RNA timeout on outbound SIP calls' of the SIP tab in the Cisco Unified Customer Voice Portal 8.5(1) opsconsole. In a nut shell, I need to change the RNA timeout but some reason when typing into the Dialed Number text box, the input is not taken. The reason I want to change this settings is because my ICM Rona is not working with CVP:
    https://supportforums.cisco.com/thread/2031366
    Thanks in advance for any help.
    Carlos A Trivino
    [email protected]

    Hello Dale,
    CVP doesn't allow you to exceed the RNA more than 60  Seconds. If you want to configure the timer for DN Patterns you should  do it via OPS console, It would update the sip.properties files in  correct way, the above way is incorrect.
    Regards,
    Senthil

  • Volume on iphone is very low, this is a common problem, Apple Needs to FIX!

    I have a new iphone 3GS that I got at the end of July, 2009. Since then i've been having problems with the volume! I called support because i had this problem along with my screen turning blank and freezing up. Support said to take the case off and this might help. well it did help the screen issue (which is kind of dumb when you think about it because the case is supposed to protect the phone and instead it caused it to malfunction!!,wierd), but the volume issue never really changed. I am hearing impaired and I do wear hearing aids, BUT....I have ALWAYS been able to use cell phones that have good loud volume, as i need to remove my aids to use the phone. My LG phone had BEAUTIFUL volume, never had a problem!
    So, then I started to do some research and saw this is a very common problem! everyone I know that has an iphone has this problem, and all these people are normal hearing people! So then i decided to just get some really good, superduper headphones, because the headphones that came with the phone were ok, but i had to hold them in my ears.
    The other day i bought the new Bose in-ear headphones with superior sound quality and at $130 bucks, they better be and the are compatable with the iphone. But.....again, while actually talking to someone on the phone the sound, even with the headphones and all volumes max'd, was still very low!! and i know its not the headphones because listening to the ipod is fantastic! it must be the phone!!!
    I even used the "accessibility" setting that is on the phone and selected the mono audio feature which pushes both L&R sounds through one channel, and still doesnt help!
    I even called support back today and one guy said i had to "restore" my phone by plugging it into my computer (not really sure what he means) but we got disconnected and the other guy said that i should bring my phone into the apple store. Both tech guys denied that there are lots of calls or complaints about this....but as you all know from reading the many posts, that this is a very common problem!!!
    I think Apple should do the right thing and recall these phones or at least fix them or SOMETHING!!!! this volume issue is internally, because when i make a call and an automated voice comes on, it works fine (majority of the time) but as soon as a live voice comes on the phone, the volume drops! there must be some type of automatic voice adjuster that is just not working properly. I mean i love my phone!!! But....i cant use it!!! And now, im going to have to return my Bose headphones and try to find something else.
    Can anyone really help me?????

    stewa348 wrote:
    I agree with you about the volume on the phone itself. (I have 3Gs). It needs to be louder. I also wear hearing aids. However I do think there may be something wrong with your phone because when I connect my earbuds (Klipsh) I get very good volume through them. In fact at full volume it's way too loud. I would push for a replacement phone.
    FWIW, my daughter (who also wears hearing aids) has trouble hearing her iphone. It appears to have more to do with the speaker not being lined up with the hearing aid's input. Her audiologist pointed out that some current hearing aids support bluetooth, I think we will get those next time we replace her hearing aids.

  • What is the best design pattern for this problem?

    No code to go with the question. I am trying to settle on the best design pattern for the problem before I code. I want to use an Object Oriented approach.
    I have included a basic UML diagram of what I was thinking so far. 
    Stated simply, I have three devices; Module, Wired Modem, and Wireless Modem.
    In the Device Under Test parent class, I have put the attributes that are variable from device to device, but common to all of them.
    In the child classes, I have put the attributes that are not variable to each copy of that device. The attributes are common across device types. I was planning to use controls in the class definition that have the data set to a default value, since it doesn't change for each serial number of that device. For example, a Module will always have a Device Type ID of 1. These values are used to query the database.
    An example query would be [DHR].[GetDeviceActiveVersions] '39288', 1, '4/26/2012 12:18:52 PM'
    The '1' is the device type ID, the 39288 is the serial number, and the return would be "A000" or "S002", for example.
    So, I would be pulling the Serial Number and Device Type ID from the Device Under Test parent and child, and passing them to the Database using a SQL string stored in the control of the Active Versions child class of Database.
    The overall idea is that the same data is used to send multiple queries to the database and receiving back various data that I then evaluate for pass of fail, and for date order.
    What I can't settle on is the approach. Should it be a Strategy pattern, A Chain of Command pattern, a Decorator pattern or something else. 
    Ideas?

    elrathia wrote:
    Hi Ben,
    I haven't much idea of how override works and when you would use it and why. I'm the newest of the new here. 
    Good. At least you will not be smaking with a OPPer dOOPer hammer if I make some gramatical mistake.
    You may want to look at this thread in the BreakPoint where i trie to help Cory get a handle on Dynamic Dispatching with an example of two classes that inherit from a common parent and invoke Over-ride VIs to do the same thing but with wildly varying results.
    The example uses a Class of "Numeric"  and a sibling class "Text" and the both implement an Add method.
    It is dirt simple and Cory did a decent job of explaining it.
    It just be the motivation you are looking for.
    have fun!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Best practice for using common VIs

    Hi,
    I have some projects, which use some common VIs (like open/close file format and similar). What is the best practice to use these common VIs? Now I copy these to the project folders, but now I have multiple copies of some VIs, which is difficult to maintian, if I need to modify something in these common files. 
    What sould i use? Still copy, or link the common folder to my project, or use a packed project, or something else?
    Thanks

    dont know if it is the best practice but with every new project, I create a new folder in my project (right click on my computer -> new -> virtual folder) and link that virtual folder to my folder that contains all my common code (vi/ctl/class) by right clicking on the newly created virtual folder and choosing "Convert to auto-populating folder".
    One downside is that if you modify one of those vis for your new application, it might break it for one of your older projects.
    I also use source code control (svn / git / mercurial / etc..) so if that happens, I can always go back to a previous working version.

  • Thread-safe design pattern for encapsulating Collections?

    Hi,
    This must be a common problem, but I just can't get my head around it.
    Bascially I'm reading in data from a process, and creating/updating data structuers from this data. I've got a whloe bunch of APTProperty objects (each with a name/value) stored in a sychronized HashMap encapsulated by a class called APTProperties. It has methods such as:
    addProperty(APTProperty) // puts to hashmap
    getProperty(String name) // retreives from hashmap
    I also want clients to be able to iterate through all the APTProperties, in a thread safe manner . ie. they aren't responsible for sychronizing on the Map before getting the iterator. (See Collections.synchronizedMap() API docs).
    Is there any way of doing this?
    Or should I just have a method called
    Iterator propertyIterator() which returns the corresponding iterator of the HashMap (but then I can't really make it thread safe).
    I'd rather not make the internal HashMap visible to calling clients, if possible, 'cause I don't want people tinkering with it, if you know what I mean.
    Hope this makes sense.
    Keith

    In that case, I think you need to provide your own locking mechanism.
    public class APTProperties {
    the add, get and remove methods call lock(), executes its own logic, then call unlock()
    //your locking mechanism
    private Thread owner; //dont need to be volatile due to synchronized access
    public synchronized void lock() {
    while(owner != null) {
    wait();
    th = Thread.currentThread();
    public synzhronized void unlock() {
    if(owner == currentThread()){
    owner = null;
    notifyAll();
    }else {
    throw new IllegalMonitorStateException("Thread: "+ Thread.currentThread() + "does not own the lock");
    Now you dont gain a lot from this code, since a client has to use it as
    objAPTProperties.lock();
    Iterator ite = objAPTProperties.propertyIterator();
    ... do whatever needed
    objAPTProperties.unlock();
    But if you know how the iterator will be used, you can make the client unaware of the locking mechanism. Lets say, your clients will always go upto the end thru the iterator. In that case, you can use a decorator iterator to handle the locking
    public class APTProperties {
    public Iterator getThreadSafePropertyIterator() {
    private class ThreadSafeIterator implements Iterator {
    private iterator itr;
    private boolean locked;
    private boolean doneIterating;
    public ThreadSafeIterator(Iterator itr){
    this.itr = itr;
    public boolean hasNext() {
    return doneIterating ? false : itr.hasNext();
    public Object next() {
    lockAsNecessary();
    Object obj = itr.next();
    unlockAsNecessary();
    return obj;
    public void remove() {
    lockAsNecessary();
    itr.remove();
    unlockAsNecessary();
    private void lockAsNecessary() {
    if(!locked) {
    lock();
    locked = true;
    private void unlcokAsNecessary() {
    if(!hasNext()) {
    unlock();
    doneIterating = true;
    }//APTProperties ends
    The code is right out of my head, so it may have some logic problem, but the basic idea should work.

Maybe you are looking for

  • Computer sees monitor-but monitor does not see computer.

    I have a MacBookPro with the older 29 pin DVI out. I own an 8.4" HD monitor for video production and want to use it for editing. I am trying to get my Marshall V-R84DP-HD monitor to see the computer and it does not recognize it. I have Mac OS X Versi

  • Errors were found during the burning process!?!?

    I finished importing a movie off of my DV Camera and clicked "share" in the iDVD '06 menu. I selected iDVD and my movie was sent into iDVD 6. After customizing a menu, and inserting a blank disc, the burning process was started. After iDVD6 has finis

  • Not enough Ram memory in photoshop -please help

    Hi When I try to save any of my work in photoshop as a jpeg (not large files-even only 5Mb size ones) it comes up with an error message saying not enough Ram to save. IM using windows xp, I have 2.5Gigs of ram, 100Gigs free space on C drive and 100gi

  • Quicktime crashes on startup/launch in Snow Leopard

    I've Googled and cannot find a solution! Every time I launch Quicktime or Quicktime 7, it chrashes immediately. I can submit the error readout if you think it will be useful. I've tried deleting the user .plist, and creating a second account and laun

  • Project resources with different working weeks

    Hi All,  I have a project with resources in different locations (Australia and the Middle East) who have different work weeks.  Australia (Monday-Friday) Middle East (Sunday-Thursday) Basically, common work week is Monday-Thursday, while the Australi