Factory pattern question

Hi, I'm using a factory pattern to return different objects depending on whats needed:
synchronized Worker getWorker(final byte[] request, String type) {
        int poolIndex = -1;
        for (int i = 0; i < workerCount; i++) {
            if (workerPool[i] == null) {
                poolIndex = i;
                if (type.equals("TypeA")) {
                    workerPool[i] = new TypeA(request, poolIndex);
                    workerPool.setType("TypeA");
} else if (type.equals("TypeB")) {
workerPool[i] = new TypeB(request, poolIndex);
workerPool[i].setType("TypeB");
return workerPool[poolIndex];
return null;
My problem is that they return ok, however. If TypeA has a function called Test1. and TypeB has a function Test6. If I try Worker.Test6 it wont recognise it. Is this just my ignorance? Should both just contain the same methods as Worker and override them?

Hi, I'm using a factory pattern to return different
objects depending on whats needed:
synchronized Worker getWorker(final byte[] request,
String type) {
int poolIndex = -1;
for (int i = 0; i < workerCount; i++) {
if (workerPool[i] == null) {
poolIndex = i;
if (type.equals("TypeA")) {
workerPool[i] = new
workerPool[i] = new TypeA(request, poolIndex);
workerPool.setType("TypeA");
} else if (type.equals("TypeB")) {
workerPool[i] = new
workerPool[i] = new TypeB(request, poolIndex);
workerPool[i].setType("TypeB");
return workerPool[poolIndex];
return null;
My problem is that they return ok, however. If TypeA
has a function called Test1. and TypeB has a function
Test6. If I try Worker.Test6 it wont recognise it. Is
this just my ignorance? Should both just contain the
same methods as Worker and override them?
indeed, the factory pattern is intended to shield the user code from implementation details of the returned interface. It (ie. the user code) MUST NOT know about which actual implementations it receives, otherwise, the factory has no use.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Problems with Factory pattern

    Sorry... I know this topic has been done to death but I still have some questions.
    In my development, I keep encountering a recurring problem that I believe should be solved by the 'factory pattern'. (Note: I'm not a patterns nut so I am only guessing about the correct pattern).
    Here is the problem:
    I develop an abstract base class. I extend the base class with several subclasses. Exterior objects use the instances via a base class reference and I don't want to them to have to know which is the correct subclass or how to create the instance.
    My solution is to make a create(param, param,...) method in the base class and using the param(s) construct the instance something like:static Foo create(int type)
    Foo instance = null;
    String className = "com.myco.foos.DefaultFoo";
    if(CONST_A == type)
      className = "com.myco.foos.FooA";
    else if(CONST_B == type)
      className = "com.myco.foos.FooB";
    {on and on...}
    {using reflection create a new instance from the className String}
    return instance;
    }The obvious problem with the create() method is that it becomes a maintenence point and I don't like the idea of a base class knowing about subclasses.
    Anyone know better a solution? Comments?
    Thanks in advance.

    Yes, that is the Factory pattern you describe. The client programs are going to call your createFoo() method and get back an instance of a subclass of Foo. Typically this pattern is used where there is some external entity that determines what subclass will be returned -- for example a system property -- and the client programs call createFoo() with no arguments. In this case reflection is used to create the instance, and your base class does not need to know anything about any subclasses.
    However, if your client programs can influence the choice of subclass, then they will have to pass some kind of parameter into createFoo(). At this point, createFoo() requires some decision logic that says "create this, or that, depending on the input parameter". And if that parameter is simply a code that enables the client programs to say "Give me a ChocolateFoo instance", then returning "new ChocolateFoo()" is the most straightforward design. But in this case, why can't the client program do that?
    If you don't like the base class having to know about subclasses (and you shouldn't be happy if it does), then you could have a helper class -- FooFactory -- that contains only the static method createFoo(). This class would know about Foo, and about any of its subclasses that it can produce instances of. It's still a maintenance point, no avoiding that, but at least it is off by itself somewhere.

  • RMI & Factory Patterns

    Hey,
    I'm developing a Chat RMI app for a college assignment. One of the features that's required is to use the Factory Pattern(FP). I've read about Factory patterns and have a bit of an understanding of them but I'm not sure what I developed actually implements a FP. Would the code below be considered a Factory Pattern?
    I've created an interface class called ChatServer and a class which implements this interface called ChatServerImpl. The server with the main method is as follows:
    public class Server {
      public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
          System.setSecurityManager(new RMISecurityManager());
        try {
          ChatServerImpl server = new ChatServerImpl();
          Naming.rebind("DSChat",server);
          System.out.println("DSChat bound in registry");
        catch (RemoteException remoteExc) {
          remoteExc.printStackTrace();
        catch(MalformedURLException malformedURLExc){
          malformedURLExc.printStackTrace();
      }I have a ChatServer, the interface class, object in the Client UI class that calls the server methods, e.g.
    ClientUI
    public class ClientUI extends JApplet implements ActionListener, ClientMonitor
         ChatServer server;
         public void init()
              try
                   server = (ChatServer) Naming.lookup("//" + getCodeBase().getHost()
                             + "/" + serviceName);
              catch (NotBoundException notBoundExc)
                   notBoundExc.printStackTrace();
              catch (MalformedURLException malformedURLExc)
                   malformedURLExc.printStackTrace();
              catch (RemoteException remoteExc)
                   remoteExc.printStackTrace();
         public void start()
              try
                   authenticate = server.authenticate(sessionUser);
              catch (RemoteException remoteExc)
                   remoteExc.printStackTrace();
              if (authenticate)
                   this.componentInit();
                   this.layoutComponents();
                   try
                        UnicastRemoteObject.exportObject(this); // Allow server to
                        // connect.
                        server.registerClient(this);
                   catch (RemoteException remoteExc)
                        remoteExc.printStackTrace();
              else
                   String errMsg = "Sorry you are already logged on to this chat room";
                   JOptionPane.showMessageDialog(this, errMsg, "You're already here",
                             JOptionPane.OK_OPTION);
                   server = null;
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == btnSend)
              {//Checks if textbox is empty
              if (txtInput.getText().compareTo("") != 0)
                   String input = txtInput.getText();
                   txtInput.setText(""); // Clear text field.
                   txtInput.requestFocus();
                   Message msg = new Message(input);
                   server.sendMessage(msg);               
         public void receiveMessage(Message msg)
              // Display received message.
              txtMessages.setText(txtMessages.getText() + "\n" + msg.toString());
              txtMessages.setCaretPosition(txtMessages.getText().length());
    ChatServer Interface
    //Interface
    public interface ChatServer extends Remote{
      public void sendMessage(Message msg) throws RemoteException;
      public boolean authenticate(ChatUser usr) throws RemoteException;
    ChatServerImpl
    public class ChatServerImpl extends UnicastRemoteObject implements ChatServer
         public ChatServerImpl() throws RemoteException
              super();
         public boolean authenticate(ChatUser usr) throws RemoteException
              ClientMonitor client = registeredUsersTMap.get(usr.getUsername());
              if (client == null)
                   return true;
              return false;
          * ChatServer interface method implementation. Sends messages between two
          * users.
         public void sendMessage(Message msg) throws RemoteException
              //Thread sends message to client
              SendMessageThread sendMessage = new SendMessageThread(
                        this.roomUsersHMap, this.registeredUsersTMap, msg);
              Thread tSendMsg = new Thread(sendMessage);
              tSendMsg.run();
    }Any help would be appreciated.

    Question: Does the code compile and run properly?
    Since the Gang of Four published their pattern book, everyone is obsessed with patterns.
    A factory basically creates and returns a new object. The following does that and technically could be called a factory.
    public MyObject createA() {};Just what object does your code create and return to the caller?

  • Need a little help with this factory pattern thing..

    Evening all,
    I have an assignment to do over easter, before i start i will say i dont want any code or anything so this isnt 'cheating' or whatever..
    This was the brief:
    A vending machine dispenses tea and coffee, to which may be added milk, and 0, 1 or 2 doses of sugar. When the machine is loaded it initially contains 100 doses of tea, 100 doses of coffee 50 doses of milk and 70 doses of sugar. After it has been in use for a while it may run out one or more items. For example, it may run out of sugar, in which case it would continue to vend tea, coffee, tea with milk, and coffee with milk. Periodically, an attendant recharges the machine to full capacity with doses of coffee, tea, milk and sugar. A user selects the required beverage, selects the required amount of sugar, and selects milk if required. The machine responds with a message telling the user the cost of the drink (coffee is 30P, tea 20P, milk 10P, and sugar 5P per dose). The user inserts coins (the machine accepts 10P and 5P coins), and when the required sum or more has been inserted, the machine dispenses the beverage, and possibly some change.
    You are to write a program that simulates the above vending machine. Your solution must use the class factory pattern, and make use of the code templates provided. The user interface should be constructed with a Swing JFrame object.
    We were suppled with code for all of the classes required except for the JFrame.. They are as follows:
    public abstract class Beverage
      int sugar;
      boolean milk;
      public String getMessage()
        String name = this.getClass().getName();
        String sugarMessage = "";
        if (sugar == 1) sugarMessage = "one sugar";
        if (sugar == 2) sugarMessage = "two sugars";
        if (sugar == 0) sugarMessage = "";
        return  "Vended 1 " + name  +  (milk ? " with milk " : "") + (sugar==1 || sugar == 2 ? (milk ? "and " + sugarMessage : " with " + sugarMessage) : "");
    public class Coffee extends Beverage
      public Coffee( int sugar, boolean milk)
        this.sugar = sugar;
        this.milk = milk;
    public class Tea extends Beverage
      public Tea(int sugar, boolean milk)
        this.sugar = sugar;
        this.milk = milk;
    public class SugarButtonsGroup
      private JRadioButton jRadioButton0Sugar = new JRadioButton();
      private JRadioButton jRadioButton1Sugar = new JRadioButton();
      private JRadioButton jRadioButton2Sugar = new JRadioButton();
      private ButtonGroup sugarButtons = new ButtonGroup();
      public SugarButtonsGroup()
        jRadioButton0Sugar.setText("No sugar");
        jRadioButton1Sugar.setText("1 sugar");
        jRadioButton2Sugar.setText("2 sugars");
        sugarButtons.add(this.jRadioButton0Sugar);
        sugarButtons.add(this.jRadioButton1Sugar);
        sugarButtons.add(this.jRadioButton2Sugar);
      public int numberOfSugars()
        if (this.jRadioButton1Sugar.isSelected()) return 1;
        if (this.jRadioButton2Sugar.isSelected()) return 2;
        return 0;
      public ButtonGroup getButtonGroup()
        return sugarButtons;
      public JRadioButton getJRadioButton0Sugar()
        return jRadioButton0Sugar;
      public JRadioButton getJRadioButton1Sugar()
        return jRadioButton1Sugar;
      public JRadioButton getJRadioButton2Sugar()
        return jRadioButton2Sugar;
    public class BeverageButtonsGroup
      private JRadioButton jRadioButtonTea = new JRadioButton();
      private JRadioButton jRadioButtonCoffee = new JRadioButton();
      private ButtonGroup buttonGroup = new ButtonGroup();
      public BeverageButtonsGroup()
        buttonGroup.add(jRadioButtonTea);
        buttonGroup.add(jRadioButtonCoffee);
        jRadioButtonTea.setText("Tea");
        jRadioButtonCoffee.setText("Coffee");
        jRadioButtonCoffee.setSelected(true);
      public String getBeverageName()
        if (jRadioButtonTea.isSelected()) return "tea";
        if (jRadioButtonCoffee.isSelected()) return "coffee";
        return "";
      public ButtonGroup getBeverageButtonGroup()
        return buttonGroup;
      public JRadioButton getJRadioButtonTea()
        return jRadioButtonTea;
       public JRadioButton getJRadioButtonCoffee()
        return jRadioButtonCoffee;
    public class MilkCheck
      private JCheckBox jCheckBoxMilk = new JCheckBox();
      public MilkCheck()
        this.jCheckBoxMilk.setText("Milk");
      public JCheckBox getJCheckBoxMilk()
        return jCheckBoxMilk;
      public boolean withMilk()
        return this.jCheckBoxMilk.isSelected();
    public class CoinMechanism
      private JButton jButton5P = new JButton();
      private JButton jButton10P = new JButton();
      private JTextField jTextFieldTotal = new JTextField();
      private BeverageFactory b;
      public CoinMechanism (BeverageFactory b)
        this.b = b;
        reset();
        jTextFieldTotal.setEditable(false);
        jButton5P.setText("Insert 5 pence");
        jButton5P.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
              jButton5P_actionPerformed(e);
        jButton10P.setText("Insert 10 pence");
        jButton10P.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
              jButton10P_actionPerformed(e);
      private void jButton5P_actionPerformed(ActionEvent e)
        // to be completed
      private void jButton10P_actionPerformed(ActionEvent e)
        // to be completed
      private void notifyVend()
        b.getCoinCurrentTotal(jTextFieldTotal.getText());
      public void reset()
         this.jTextFieldTotal.setText("0");
      public JButton getJButton5P()
        return this.jButton5P;
      public JButton getJButton10P()
        return this.jButton10P;
      public JTextField getJTextFieldTotal()
        return this.jTextFieldTotal;
    public class BeverageFactory
      private int coffees;
      private int teas;
      private int milks;
      private int sugars;
      public BeverageButtonsGroup beverageButtons = new BeverageButtonsGroup();
      public SugarButtonsGroup sugarButtons = new SugarButtonsGroup();
      public MilkCheck milkCheck = new MilkCheck();
      public CoinMechanism slots = new CoinMechanism(this);
      public void setUIState()
        // sets the states of the widgets on the frame accoording to the
        // quantities of supplies in the machine
        // to be finished
      public void getCoinCurrentTotal (String o)
        // this is should be executed whenever a user puts a coin into the machine
        int foo = Integer.parseInt(o);
        // to be finished
      private int cost()
        // returns the cost of the currently selected beverage
        // to be finished
      public BeverageFactory( int coffees, int teas, int milks, int sugars)
        this.coffees = coffees;
        this.teas = teas;
        this.milks = milks;
        this.sugars = sugars;
      public void refill(int coffees, int teas, int milks, int sugars)
        // to be completed
      public Beverage makeBeverage(String name, boolean milk, int sugar)
        if (name.compareTo("coffee") == 0)
          coffees--;
          if (milk) milks--;
          sugars = sugars - sugar;
          return new Coffee(sugar,milk);
        if (name.compareTo("tea") == 0)
          teas--;
          if (milk) milks--;
          sugars = sugars - sugar;
          return new Tea(sugar, milk);
        return null;
    }Okay, well if you read through all that, blimey thanks a lot!.
    My question relates to this method in the BeverageFactory class:
    public void getCoinCurrentTotal (String o)
        // this is should be executed whenever a user puts a coin into the machine
        int foo = Integer.parseInt(o);
        // to be finished
      }I don't understand what the heck its supposed to be for..
    I can obtain the current amount of coins inserted from the textbox in the CoinMechanism class. The only thing i could think of, would be for this to enable the 'Vend' button, but it doesnt have access anyway..
    Any suggestions would be hugely appreciated, I have tried to contact the lecturer but he isnt around over easter i guess..
    Many thanks.

    I'm not going to read all that, and I don't do GUIs, so this is just a guess, but it looks like the CoinMechanism class is intended to be just a dumb processor to accept coins and determine what each coin's value is, but no to keep a running total.
    That in itself is an arguably acceptable design--one class, one job and all that. But I don't know that it makes sense to have the BeverageFactory keep the running total.
    Overall, I gotta say, I'm not impressed with your instructor's framework. Maybe it's just because I didn't look at it closely enough, or maybe it's more of a naming problem than a design problem, but it seems to me he's mixing up GUI code with business logic.
    Good luck.

  • Help building an executable that uses a factory pattern

    Hello,
    I'm trying to build an .exe from a VI that uses the factory pattern. The VI gives me the error that it can't find the classes to load and is looking outside the .exe file to find them. The specific error is:
    "Get LV Class Default Value.vi<APPEND>
    <b>Complete call chain:</b>
         Get LV Class Default Value.vi
         Main.vi
    <b>LabVIEW attempted to load the class at this path:</b>
    C:\ATE\Experiments\Build Testing\Builds\Virtual Classes\High Class\High Class.lvclass"
    I thought those classes were bundled into the .exe when it was built? I have included the class folders in the "Always Included" window of the build script.
    Any help would be appreciated. I'm fairly new to classes and I haven't built an .exe with an app using the factory pattern.
    Thanks,
    Simon
    Attachments:
    Build Testing.zip ‏491 KB

    This might be the answer.  I found the following checklist on Building Executables.  It really is referencing things other than Objects, but maybe Object folders also need to be properly located ...
    Bob Schor  [the stuff I found is below this line ...]
    Ensure paths generate correctly.
    Details
    If a VI loads other VIs dynamically using VI Server or calls a dynamically loaded VI through a Call By Reference node, make sure the application or source distribution creates the paths for the VIs correctly. To ensure paths generate correctly, use relative paths to load the VIs. The following table depicts the relative paths for a top-level VI, foo.vi, which calls a.vi and b.vi. C:\..\Application.exe represents the path to the application.
    Path to source files
    Path to files in application
    C:\Source\foo.vi
    C:\..\Application.exe\foo.vi
    C:\Source\xxx\a.vi
    C:\..\Application.exe\xxx\a.vi
    C:\Source\yyy\b.vi
    C:\..\Application.exe\yyy\b.vi
    If you use the LabVIEW 8.x file layout and you include dynamically loaded VIs in the application, the paths to the VIs change. For example, if you build b.vi into an application, its path is C:\..\Application.exe\b.vi whereC:\..\Application.exe represents the path to the application and its filename.

  • Factory Patterns with Generics

    I am trying to combine the good old factory pattern with generics and could use some advice.
    I have the following
    //Base class from which all my things extend
    public abstract class Thing {
    //one kind of thing
    public class ThingOne extends Thing {
    //another kind of thing
    public class ThingTwo extends Thing {
    //interface for my factory
    public interface ThingFactory<T> {
    public T create(long id);
    //a factory for thingones
    public class ThingOneFactory<T> implements ThingFactory<T> {
    public T create(long id) {
    return (T) new ThingOne();
    public class TestClass{
    public <T extends Thing> T getThing(ThingFactory<T> tf){
    //do a bunch of generic stuff to figure out id to call create
    ThingFactory<T> instance = tf;
    return (T) instance.create(Long id);
    }My calling code would know what kind of thing it needs but necessarily the things id. Which can be computed in a generic way.
    TestClass gt = new TestClass();
    gt.getThing(new ThingOneFactory<ThingOne>());This all seems to work properly but I am getting "Type safety: Unchecked cast from ThingOne to T" in my ThingOneFactory
    My T's will always extend Thing, what am I missing? Is there a better way to do this?
    Edited by: nedry on Dec 29, 2009 5:39 PM

    I thought of that after I posted. But that just moves my unsafe cast warning into TestClass.Why?
    return (T) instance.create(Long id);That can't have ever compiled. What is the exact code? And why did you have to cast (what was the warning/error)?

  • Builder vs Factory Patterns

    Hi,
    I read about builder and factory patterns. But both of them look quite similar.
    Can u plz help me to understand the difference between them.
    Thanking You,
    Chamal.

    I puzzled over this too. The UML is almost identical for both patterns. A great example of how UML class diagram leave a lot to be desired.
    This is my take, which may not be absolutely correct or orthodox.
    The difference is that in the abstract factory, the point is to hide the implementation of the abstract type. In the builder it's other way around. The point is to hide the implementation of the callers of the builder or really, what is being built.
    So a user of a abstract factory should not know (or care) about what type the abstract factory returns. In the builder pattern, the code could potentially make references to specific builder types (a text builder for debugging or console mode, for example) but the implementation of what is being built is not known to the builder.
    You can easily combine the two and get a lot of flexibility.

  • LVOOP Factory Pattern

    Factory Pattern..
    I am using factory pattern for its advantage of loading classes into memory when it is called dynamically.
    But I am able to see all the classes loaded into memory by looking into LabVIEW Class Hierarchy window and VI Hierarchy window.
    Where this not happen. Please suggest solution for this query.
    nilesh
    Attachments:
    Factory Pattern.zip ‏136 KB

    I'll reply but I am no OOPer expert.
    THe factory pattern as implemented in LV is just anum driven case structure where each case can have a different instance of a class constant. All of the Class constants exit through the same tunnel that LV cast as the common ancestor class of all of the constants in the case structre.
    The exiting wire can be wired to any method available for the common parent class.
    So it is a code construct that lets you choose the type of data on the wire.
    The Actor Frame work is another fancy term for a generic barckground task.
    Actors can be instaciated using using teh Factory Pattern to choose the "flavor" of background task.
    Re: All in memory
    If the classes are in the project and the project is open then all of the classes are loaded to make sure they are healty.
    In an exe that is not always the case as is the situation when the classes are not part of the project or the project is closed.
    This image (and the others in that album) show a method I used to find and use compatable classes to create the background task (Active Object).
    Active Object (as I understand them) are instances of a Class that function indepenently once created and provided a method to allow other objects to invoke its exposed methods.
    Example DAQ_Collector
    Child of an I/O class that runs in the background and acepts commands(invoked methods) like "Start", Stop, Exit.
    I will now step back to let those who know more correct what I havge posted.
    Have fun!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Difference between Builder Pattern and Factory Pattern

    difference between Builder Pattern and Factory Pattern

    You are right Both of these patterns are creational design patterns Purpose of these two patterns is very different as Abstract Factory Patterns (which is commonly known as Factory pattern ) is used to create a object in a scenario when you have a product & there is a possibility of many vandors providing implementation for it. So it is good to come up with a abastract factory which provides create method for the product. Each vendor can implement you abstract factory & provide a concrete implementation which will return a product of Vendor implementation.
    Builder patter is used in case you have a very complex object creation process involved & you realy want to abstract the client from doing all those complex steps. In such situation you create a builder class which takes care of all complex steps & client just needs to use this builder class to create your complex object.
    Hope it clarifies your doubts.

  • BlazeDS and Abstract Factory Pattern

    Hi All,
    I was trying to extend my application using the Factory Method. But, I identified that I need to use an abstract Factory pattern to meet my design requirements. In other words I need to create a FactoryInstance based on a input. Will that be possible.
    Any help?????
    -Ram V

    The Factory pattern is meant to give you the ability to generically construct objects (rather than explicitly declare what you want to create via the "new" keyword you defer to a factory and take what it gives you) The Abstract Factory pattern is meant to give you the ability to generically construct Factories. So, for instance, say you want to create widgets with a certain look and feel. You could use the Factory pattern and ask a ButtonFactory to make buttons and a TextArea factory to make TextAreas, but since you want the same look and feel for all widgets you could just ask the WidgetFactory to give you a WidgetFactory for a given Look and Feel and then ask it to make Buttons and TextAreas and whatever else, knowing that it has handled which kind of button and whatever else you need.
    Hope that made sense, good luck
    Lee

  • Beginner Factory Pattern help needed please

    hi people,
    Can someone please explain to me in laymans terms what the use of the Factory pattern is. I went to http://www.research.umbc.edu/~tarr/dp/lectures/Factory.pdf
    and it did nit help me too much.
    I'd really appreciate it if someone could give me an abstract example of when the Factory pattern would be useful. The reason I ask is because I am researching into JDO and have come across PersistenceManagerFactory and think I would underdstand this better if I understand Factory's.
    Many thanks.

    Is the reason for the ConnectionHelper to allow us to use that as the return type in the getHelper() method, thus allowing us to have either the OracleConnectionHelper or DB2ConnectionHelper?
    Yes. You want to achieve polymorphism. You are interested in the connect() method, not necessarily what database is used (not the best example in the world, normally you would care as different vendors have slightly different SQL syntax, but assume you were using no triggers, procedures or non-ANSI SQL).
    So, are you basically saying that a Factory is a class that can be used to decide which of the two databases we are going to connect to?
    Depends. In this instance, you name the database you want and the factory is responsible for returning the proper class. In other cases, you might have developed a program that works across databases and only uses one at a time. In this case, you would probably read in a setting at application startup, and the factory would always return the same object type.
    If there is a PersistentManagerFactory, does it mean this would be used to decide what PersistentDataStore we are going to use (i.e. flat file, database, serialised object etc)?
    Again, it depends. You can make your factories 'smart' by deciding where to serialize a given object (say, every domain model object has a method save() and your DAO uses the factory to get a connection to do its work). In other cases, you have a 'bare-bones' factory that simply returns the requested object type. Why go through all that effort? Well, one advantage is that I can put the factory, interface and any implementations in the same package. The only ones that (normally) would need to be public would be the interface and the factory. You can hide the implementation details using the security features of the language.
    Also, why is OracleConnectionHelper a final class?[i]
    In general, I make all variables, method signature parameters and classes final. Once I need to sub-class or re-assign a variable value, I remove the final clause. I can't count the number of times the compiler caught an error (rather than at runtime) because of the additional 'safety' declaring everything final gives you. Only make variables and classes (and method signature variables) non-final when you need to. IMHO, of course.
    - Saish

  • My Factory Pattern

    Here is the factory pattern I have implemented. I want to know, exactly which pattern this belongs to. I liked this. Comments and suggestions are welcome.
    // ViewFactory.java
    // Implementation of the Class ViewFactory
    // Generated by Enterprise Architect
    // Created on: 9/28/02
    // Original author: Vijendra Kotian
    // Modification history:
    public class ViewFactory implements ViewFactoryInterface {
         private ViewFactoryInterface vf;
         protected ViewFactory(){
         public ViewFactory(String type){
              System.out.println("ViewFactory created");
              vf=createNewView(type);
         public void finalize() throws Throwable {
              super.finalize();
         private ViewFactoryInterface createNewView(String type){
              char c=(char)type.charAt(0);
              switch(c){
              case 'a':
              case 'A':
                   return new AWTViewFactory();
              case 'm':
              case 'M':
                   return new MotifViewFactory();
              return null;
         public void openView(ViewFactoryInterface param){
              vf=param;
         public void print(){
              if(vf!=null) vf.print();
              else System.out.println("Vf is null!!!");
         public static void main(String[] s){
              ViewFactoryInterface vf=new ViewFactory("MOTIF");
              vf.print();
              ViewFactoryInterface vf1=new ViewFactory("Awt");
              vf1.print();
              vf1.openView(vf);
              vf1.print();
              ViewFactoryInterface vf2=new ViewFactory();
              vf2.print();
    public interface ViewFactoryInterface {
         public void print();
         public void openView(ViewFactoryInterface vfi);
    import ViewFactory;
    public class MotifViewFactory extends ViewFactory{
         public MotifViewFactory(){
              //super("Motif");
              System.out.println("New Motif view factory created");
         public void finalize() throws Throwable {
              super.finalize();
         public void print(){
              System.out.println("Motif print");
    import ViewFactory;
    public class AWTViewFactory extends ViewFactory{
         public AWTViewFactory(){
              //super("AWT");
              System.out.println("Awt View Factory created");
         public void finalize() throws Throwable {
              super.finalize();
         public void print(){
              System.out.println("AWT Print");
    -Vijendra K

    http://forum.java.sun.com/faq.jsp#messageformat

  • Singleton pattern over Factory pattern

    What is the difference between the Factory and Singleton pattern.
    Can we use a singleton (pattern) class to create other object instances and return them.
    What are the advantages and disadvantages for using the Singleton pattern here.
    Or do we have to use only a factory (pattern) class to do the above type of task.

    The Factory pattern and the Singleton pattern are used to achieve different things. That's not to say they can't be used together. A Singleton pattern is used to force the use of a single instance of a class, hence the name. The Factory pattern is used to determine at runtime what class will be used.

  • Trying to understand factory pattern - having some problems

    hi,
    I am tryin to learn the implementation of Factory design pattern and I came across this link after searching this forums:
    http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
    My question is:
    In the example they have different DAOFactories that have the database specific details like:
    // Cloudscape concrete DAO Factory implementation
    import java.sql.*;
    public class CloudscapeDAOFactory extends DAOFactory {
      public static final String DRIVER=
        "COM.cloudscape.core.RmiJdbcDriver";
      public static final String DBURL=
        "jdbc:cloudscape:rmi://localhost:1099/CoreJ2EEDB";
      // method to create Cloudscape connections
      public static Connection createConnection() {
        // Use DRIVER and DBURL to create a connection
        // Recommend connection pool implementation/usage
      public CustomerDAO getCustomerDAO() {
        // CloudscapeCustomerDAO implements CustomerDAO
        return new CloudscapeCustomerDAO();
      public AccountDAO getAccountDAO() {
        // CloudscapeAccountDAO implements AccountDAO
        return new CloudscapeAccountDAO();
      public OrderDAO getOrderDAO() {
        // CloudscapeOrderDAO implements OrderDAO
        return new CloudscapeOrderDAO();
    }But in my application I have stored all the database specific information in the server.xml of my tomcat server.So,how can I read different database configuration information for different databases like Oracle,Cloudbase,MySQL etc ????
    Please help.

    Thanks duffmo,
    But atleast provide some link then that shows wats inHere's two:
    http://www.springframework.org
    http://www-128.ibm.com/developerworks/java/library/j-dao/
    Personally, I don't worry about DAO factory classes.
    If I have a class Foo that I want to persist I'll have a companion DAO interface that will look like this:
    public interface FooDao
        public Foo find(long id);
        public List<Foo> findAll();
        public void saveOrUpdate(Foo foo);
        public void delete(Foo foo);
    }There are more finders if I have other candidate keys.
    I want to have all the datasource information out of
    my code in server.xml,context .xml or some other xml
    file from which my java code should read the
    information,so which is the ideal way to do if you
    want to make your application generic in the sense it
    can be used with any database.Yes, I agree. Your database stuff will be in the Spring context and your app server's JNDI data source.
    %

  • Factory design question

    Is it gospel that a Factory be static? For instance, I'd like to have a Factory class that I maintain a reference to and returns me the correct instance of an object, which I invoke methods on. However, I want the Factory class to hold onto all the references while I have another object which maintains the reference to the Factory. I know this is possible, but I don't know if I'm violating a best practice here. Every time I read about an Abstract Factory, it is used with a static reference. Or is this a completely different kind of design pattern?

    No, for instance, I'd like it to be this way. Assume Dog and Cat inherit Animal and have all the required methods.
    MyObject will maintain a reference to the Factory, which will in turn maintain all my necessary references. The client code will only call feedAnimal or walkAnimal on MyObject. My question is, is this poor design or violating any best practices?
    public class MyObject {
       AnimalFactory af;
       public MyObject() {
           af = new AnimalFactory();
       private Animal getAnimal(String name) {
            Animal al = af.getInstance(name);
            return al;
       public void feedAnimal(String name) {
            getAnimal(name).feed();
       public void walkAnimal(String name) {
            getAnimal(name).walk();
    public class AnimalFactory {
       public AnimalFactory() {
       public Animal getInstance(String s) {
             Animal al;
             if (s.equals(ROVER)) {
                  al = new Dog();
             } else if (s.equals(WHISKERS)) {
                  al = new Cat();
             return al;
    }

Maybe you are looking for

  • Newbie: should I use a JDialog or JPanel ?

    I have inherited an app that is 50% complete and I need to add a new popup window that is displayed in response to a Pulldown menu selection. The popup window will have 5 different text fields that will need to be passed back to the calling routine.

  • BAPI or FM for CHANGING Internal Order

    Hi all, I am looking for a BAPI or Function module for changing a End of Work field (DATE field) for that Internal Order.  Transaction for internal order KO02 Please suggest. Edited by: Anu on Jul 6, 2009 3:30 PM

  • How to check if my function is MT-safe?

    I wrote some functions in a multi-thread program. I can check if a function is MT-safe by man it. But I'm not sure, if a function calls only MT-safe functions means this function is MT-safe too? Any help is appreciated. Jenny

  • A new wait event

    Hi all, We have a 2 node RAC 10.2.0.3 database.From quite sometime we are experiencing "transaction" wait event apart from "enq:TX". What is this "transaction wait event"? How does it differ from enq:TX row lock contention event. I have searched a lo

  • Request for URL Link in SmartForm

    Hi Experts, I am working on ECC5.0. I am developing PO smrtform and got a requirement to have HTML links in Smartform Layout. Example Scenario: I have html link as follows for item number 1 details in PDF format. Whe I copy and paste the following li