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

Similar Messages

  • Abstract Factory Pattern

    Hi All
    I have created the abstract class as shown below and I've got a number of concrete classes which implements it. When getFactory(String name) is called it addes an instance of a concrete class to the hashtable in the abstract class.
    My issue is that I would like all the concrete class to be added automatically (somehow) to the hashtable or have a method that gives my an overview of the available concrete classes so that a client can ask for them and then choose which one to pick. Is there a way to achieve this
    (PS: the KPI interface which is implemented only holds some public static fields)
    Thanks in advance
    Thomas
    import java.util.Collection;
    import java.util.Hashtable;
    * KPIFactory is declared abstract and requires implementation of the business methods
    * for each KPI.
    public abstract class KPIFactory implements KPI {
         * public static Hashtable which containes all the added KPIFactories
         * instances
        private static Hashtable KPI_FACTORIES = new Hashtable();
         * addFactory returns a KPIFactory from the given name.
         * <p/>
         * If the KPIFactory isn't already in the static Hashtable it will be
         * added if it can be found. All the Factories extending this class
         * will have a static body which adds it when class.forname is called.
         * If it cannot be found a KPINotFoundexcpetion is thrown
         * @param name of the class which implementes the KPIFactory
         * @return returns a KPIFactory if the
        public static KPIFactory getFactory(String name)
                throws KPINotFoundException {
            KPIFactory s = (KPIFactory) KPI_FACTORIES.get(name);
            if (s == null) // KPI not found
                try {
                    Class.forName(name);
                    // By now the static block in the KPI implemenation
                    // would have been executed, which addes a new instance
                    // to the static hashtable.
                    s = (KPIFactory) KPI_FACTORIES.get(name);
                    if (s == null) // Error is KPI isn't found now
                        throw (new KPINotFoundException());
                } catch (ClassNotFoundException e) {
                    // throws an exception to indicate that
                    // the KPIFactory could not be created
                    throw(new KPINotFoundException());
            return (s.create());   // Returns an instance of the KPIFactory
         * addFactory takes the manufactored object kpi and
         * puts it into the hashtable with the name as the key
         * <p/>
         * The method is syncronized in order to avoid problems with mutliple
         * factories writting to the hashtable at the same time
        public static synchronized void addFactory(String name, KPIFactory kpi) {
            KPI_FACTORIES.put(name, kpi);
         * create is abstract and returns a KPIFactory.
         * <p/>
         * create is implemented in every concrete class which
         * extends the KPIFactory and it returns an instance of
         * the concrete class (and therefore KPIFactory as the
         * super class)
         * @return returns a KPIFactory
        public abstract KPIFactory create();
        public abstract void calculate(KPIDataset dataset);
    }

    Hi,
    One "elegant" solution that comes to mind is to use AspectJ, for which you'd define as Aspect something like this:
    public aspect FactoryRegistrationAspect {
    /* A pointcut for calls to all implementing classes of KPIFactory */
    pointcut registerFactory (KPIFactory kpif, String name) :
    call (* * KPIFactory.getFactory(String)
    && within(KPIFactory+)
    && target(kpif)
    && args(name);
    /* When the above pointcut occurs, execute the following advice and invoke the registerIfNecessary
    method in your Abstract Factory clalss */
    before(KPIFactory kpif, String name) : registerFactory(kpif, name) {
    kpif.registerIfNecessary(name);
    In your abstact factory class, you'd then have the registerIfNecessary(String name) method. Which would look something like this:
    public boolean registerIfNecessary(String name) {
    if (!KPI_FACTORIES,containsKey(name)) {
    try {
    Class clazz = Class.forName(name);
    KPI_FACTORIES.add(name, (KPIFactory)clazz.newInstance());
    return true;
    catch (Exception e) { return false}
    The "magic" behind aspectJ is that it weaves the addition from the aspect into your implementing classes during compile time such that you don't need any property files etc to define your implementing classes, its all done by the aspecJ compiler during compile time.
    If the above is unlike what you've seen, check out the magic at eclipse.org/aspecj and get in on the greatest thing ever devised since OOP.
    Cheers
    Bones

  • 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.

  • Abstract Factory Design Pattern

    Could someone please explain the abstract factory design pattern in simple english. As far as I understand it is used to create a bunch of related objects based on parameter/s provided at runtime.
    However, why would one use this compared to an Interface.
    I actually am reading a great book on design patterns (Design Pattern by James Cooper) but having a bit of problem really understanding this one.
    Cheers

    As far as I
    understand it is used to create a bunch of related
    objects based on parameter/s provided at runtime. There may be variations but as I understand it basically an Abstract Factory defines two interfaces, one is the factory and one is the product. A good example is iterators in Java. The iterator factory is the Iterable interface and the iterator product is the Iterator interface.
    ArrayList implements Iterable so it's an iterator factory. If you call the iterator() method of an ArrayList object you'll get an Iterator object. The same applies to TreeSet and many other classes.
    The Iterator objects sport the same Interface but they're quite different internally of course (Iterating an array is not the same as iterating a tree) so they're a "family of related products".

  • Examples of the Abstract Factory Design Pattern

    Could someone please give an example about situations in which you would definitly use the Abstract Factory Design Pattern?

    Ok, but they are coupled because Abstract Factory uses Factory methods. Without getting too detailed here, Abstract Factory is useful when you want to swap out entire sets of things (ie. pluggable look and feels). So one subclass of AbstractGUIFactory is MotifGUIFactory while another is WindowsGUIFactory. Your application can gets a specific factory but puts it in an AbstractFUIFactory variable.
    AbstractGUIFactory factory = new WindowsGUIFactory();
    AbstractButton = factory.makeButton();So you can program generically and swap out entire sets of widgets by changing one line of code.
    You should really read Design Patterns by Gamma et al. because it is the definitive book on this topic.

  • BlazeDS and JSF

    I have an existing JSF (really Oracle ADF) application that I'd like to connect to a Flex front-end rather than rewrite totally in Flex + JSPs for the back-end. BlazeDS will properly instantiate the managed beans through remote object requests, but the FacesContext references in my managed beans are null, as BlazeDS seems to have nothing to do with this context. Does anyone have experience connecting a Flex application to a JSF application properly, maybe through creating his/her own FacesContext factory?

    <div class=Section1><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'>Hi,<o:p></o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'><o:p> </o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'>It&#8217;s pretty easy to integrate blazeds into an existing application. <br />The war is just an example of how to configure and package blazeds.  BlazeDS<br />itself is just a servlet, with a collection of jars and some configuration<br />files.  You put the required jars into your WEB-INF/lib, the configuration files<br />into WEB-INF/flex (If I remember correctly), and then map the blazeds message<br />broker servlet in your web.xml file. You can open up the war file and see how it&#8217;s<br />configured there and base your configuration on that.  Depending on your needs<br />and your servlet container you may have to add a jar file to your container&#8217;s lib<br />or classpath.<o:p></o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'><o:p> </o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'>One of the benefits of blazeds is that if you&#8217;ve structured your<br />application so that you&#8217;ve abstracted the view then you can just plop bds right<br />in there and expose all your services through bds views.  It&#8217;s very powerful<br />that way.  <o:p></o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'><o:p> </o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'>If you&#8217;re still having trouble just write a response and I&#8217;ll<br />see what I can do.<o:p></o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'><o:p> </o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'>/r <o:p></o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'><o:p> </o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'><o:p> </o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'><o:p> </o:p></span></p><br /><br /><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";<br />color:#1F497D'><o:p> </o:p></span></p><br /><br /><div style='border:none;border-top:solid #B5C4DF 1.0pt;padding:3.0pt 0in 0in 0in'><br /><br /><p class=MsoNormal><b><span style='font-size:10.0pt;font-family:"Tahoma","sans-serif"'>From:</span></b><span<br />style='font-size:10.0pt;font-family:"Tahoma","sans-serif"'> Larry Guros<br />[mailto:[email protected]] <br><br /><b>Sent:</b> Thursday, July 24, 2008 8:28 AM<br><br /><b>To:</b> [email protected]<br><br /><b>Subject:</b> Re: BlazeDS and JSF<o:p></o:p></span></p><br /><br /></div><br /><br /><p class=MsoNormal><o:p> </o:p></p><br /><br /><p class=MsoNormal style='margin-bottom:12.0pt'>A new message was posted by<br />Larry Guros in <br><br /><br><br /><b>General Discussion</b> --<br><br />  BlazeDS and JSF<br><br /><br><br />Ditto. I am guessing the answer is no one knows. <br><br /><br><br />Seems Blazeds is much better suited to flex-only applications and doesn't<br />integrate easily with other J2EE apps. <o:p></o:p></p><br /><br /><div class=MsoNormal><br /><br /><hr size=2 width=200 style='width:150.0pt' align=left><br /><br /></div><br /><br /><p class=MsoNormal style='margin-bottom:12.0pt'>View/reply at <a<br />href="http://www.adobeforums.com/webx?13@@.59b4b834/0">BlazeDS and JSF</a><br><br />Replies by email are OK.<br><br />Use the <a<br />href="http://www.adobeforums.com/webx?280@@.59b4b834!folder=.3c061a83">unsubscribe</a>< br />form to cancel your email subscription.<o:p></o:p></p><br /><br /></div>

  • 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.

  • 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.

  • Create client classes in Abstract Factory

    Hi!
    Let's we have one of the next classes in AbstractDesign patterns:
    1.WindowFactory - abstract factory
    2.MotifWindowFactory, MacWindowFactory - concrete factory
    3.Window - abstract product
    4.MotifWindow, MacWindow - concrete products
    5.Client - client class
    6.ClientCreator - class that creates our client class
    The source code of Client is like this:
    public class Client {
    private AbstractFactory af = null;
    public Client(AbstractFactory af) {
    this.af = af;
    af.createAbstractProduct();
    The code of ClientCreator will be like this:
    public class ClientCreator {
    Client client = new Client(new MotifWindowFactory());
    OK!
    But we can have many client classes. And this client classes can create from different places (many ClientCreator classes) in our project.In our project we have:
    public class ClientCreator1 {
    Client client1 = new Client(new MotifWindowFactory());
    public class ClientCreator2 {
    Client client2 = new Client(new MotifWindowFactory());
    public class ClientCreatorN {
    Client clientN = new Client(new MotifWindowFactory());
    And what will happen when I need to change concrete factory. I must go to EVERY ClientCreator classe and change code to create client classes with another concrete factory:
    public class ClientCreator1 {
    Client client1 = new Client(new MacWindowFactory());
    public class ClientCreator2 {
    Client client2 = new Client(new MacWindowFactory());
    public class ClientCreatorN {
    Client clientN = new Client(new MacWindowFactory());
    I think that this is not flexibility.
    Can any tell me what I wrong understand in AbstractFactory pattern?
    Thanks.

    The code
    Client client1 = new Client(new MacWindowFactory());
    Client clientN = new Client(new MacWindowFactory());results in the creation of a factory for each client. This is unnecessary. Typically, you'd use a singleton here - this is mentioned in GoF 1995:
    Client client1 = new Client(MacWindowFactory.getInstance());
    Client clientN = new Client(MacWindowFactory.getInstance());This means that only one factory is created (assuming a singleton implementation within MacWindowFactory.getInstance).
    This approach ties each client creation to a given factory type. If you want all clients to use the same factory type, then you would change the code to:
    Client client1 = new Client(WindowFactory.getInstance());
    Client clientN = new Client(WindowFactory.getInstance());where WindowFactory would return the appropriate factory type. Now if WindowFactory is an interface, then you create a "Factory Factory", or "Factory Manager". i.e.
    Client client1 = new Client(WindowFactoryManager.getFactoryInstance());
    Client clientN = new Client(WindowFactoryManager.getFactoryInstance());The implemenetation of getFactoryInstance can work any of many ways. If you've only one concrete WindowFactory for now, then hard code it into getFactoryInstance. If you have many, then you could have a setFactoryInstance method on WindowFactoryManager. Or getFactoryInstance could use reflection to create a factory based on a Property, etc.

  • 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.

  • 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

  • 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 pattern

    Hello everyone,
    I am trying to architect part of an application that accepts a user's choice from a drop-down menu and creates an object based on that choice. I decided that the best way to do this was to represent each object with an enum that could be used to populate the drop-down list on a web page. The enum that is chosen is then given to a factory, which builds the object.
    Here is some example code:
    /* The objects */
    public interface Option {
        public boolean validate(String input);
    public class IntegerOption implements Option {
        public boolean validate(String input) {
            try {
                Integer.parseInt(input);
                return true;
            catch (NumberFormatException ex) {
                return false;
    public class StaticEnumerationOption implements Option {
        private Set<String> choices;
        public StaticEnumerationOption(Set<String> choices) {
            this.choices = choices;
        public Set<String> getChoices() {
            return choices;
        public boolean validate(String input) {
            return choices.contains(input);
    // Note: this class has been dummied down for the sake of simplicity
    public class DynamicEnumerationOption implements Option {
        private Database db;
        private String sql;
        public DynamicEnumerationOption(Database db, String sql) {
            this.db = db;
            this.sql = sql;
        public boolean validate(String input) {
            return db.getChoices(sql).contains(input);
    /* The enum */
    public enum OptionType {
        INTEGER,
        STATIC_ENUMERATION,
        DYNAMIC_ENUMERATION
    /* The factory that creates the objects */
    public class OptionFactory {
        public Option getOption(OptionType type, HttpServletRequest request) {
            switch (type) {
                case INTEGER:
                    return new IntegerOption();
                case STATIC_ENUMERATION:
                    Set<String> choices = getChoices(request);
                    return new StaticEnumerationOption(choices);
                case DYNAMIC_ENUMERATION:
                    Database db = getDatabase(request);
                    String sql = getSQL(request);
                    return new DynamicEnumerationOption(db, sql);
                default:
                    throw new UnsupportedOptionException(type);
        private Set<String> getChoices(HttpServletRequest request) { ... }
        private Database getDatabase(HttpServletRequest request) { ... }
        private String getSQL(HttpServletRequest request) { ... }
    /* inside a Servlet method */
    OptionType type = Enum.valueOf(OptionType.class, request.getParameter("option_type"));
    Option option = new OptionFactory().getOption(type, request);
    try {
        dao.saveOption(option);
    catch (DataAccessException ex) {
        request.setAttribute("error_msg", ex.getMessage());
    }This seems like a bad design to me because the factory should not be coupled to an HTTP request.
    Here is the only thing I can think of to try and decouple the two:
    public interface OptionFactoryHelper {
        public Set<String> getChoices();
        public Database getDatabase();
        public String getSQL();
    public class HttpOptionFactoryHelper {
        private HttpServletRequest request;
        public HttpOptionFactoryHelper(HttpServletRequest request) {
            this.request = request;
        public Set<String> getChoices() {
            // pull the choices out of the request and return them
        public Database getDatabase() {
            // pull the database out of the request and return it
        public String getSQL() {
            // pull the SQL out of the request and return it
    public class OptionFactory {
        public Option getOption(OptionType type, OptionFactoryHelper helper) {
            switch (type) {
                case INTEGER:
                    return new IntegerOption();
                case STATIC_ENUMERATION:
                    Set<String> choices = helper.getChoices();
                    return new StaticEnumerationOption(choices);
                case DYNAMIC_ENUMERATION:
                    Database db = helper.getDatabase();
                    String sql = helper.getSQL();
                    return new DynamicEnumerationOption(db, sql);
                default:
                    throw new UnsupportedOptionException(type);
    /* inside a Servlet method */
    OptionType type = Enum.valueOf(OptionType.class, request.getParameter("option_type"));
    OptionFactoryHelper helper = new HttpOptionFactoryHelper(request);
    Option option = new OptionFactory().getOption(type, helper);
    try {
        dao.saveOption(option);
    catch (DataAccessException ex) {
        request.setAttribute("error_msg", ex.getMessage());
    }This seems to do the trick...but I'm not sure if it is a good solution. Any opinions? Is there a formal name for the "helper" I am using?

    The solution I gave does not require this be the case. The get()
    method could take 0 parameters if that's what you want.If you want to use an enum as the factory itself, then I see no way to build objects from different contexts without passing in a Context object to the "get" method. You could accomplish this with a class, but not an enum.
    For example:
    public class ContextOptionFactory implements OptionFactory {
        private OptionContext context;
        public ContextOptionFactory(OptionContext context) {
            this.context = context;
        public Option getOption(OptionType type) {
            switch (type) {
                case INTEGER: return new IntegerOption();
                case STATIC_ENUMERATION: return new StaticEnumerationOption(context.getChoices());
                case DYNAMIC_ENUMERATION: return new DynamicEnumeration(context.getDatabase(), context.getSQL());
    public interface OptionContext {
        public Collection<String> getChoices();
        public Database getDatabase();
        public String getSQL();
    public class HttpOptionContext implements OptionContext {
        private HttpServletRequest request;
        public HttpOptionContext(HttpServletRequest request) {
            this.request = request;
    public class DatabaseOptionContext implements OptionContext {
        private Connection connection;
        public DatabaseOptionContext(Connection connection) {
            this.connection = connection;
    // then you can load the option from either context ...
    OptionContext httpContext = new HttpOptionContext(request);
    OptionFactory httpFactory = new ContextOptionFactory(httpContext);
    Option httpOption = httpFactory.getOption(OptionType.INTEGER);
    OptionContext dbContext = new DatabaseOptionContext(connection);
    OptionFactory dbFactory = new ContextOptionFactory(dbContext);
    Option dbOption = dbFactory.getOption(OptionType.INTEGER);This same effect cannot be accomplished with an enum. You must choose to use one of the contexts at compile-time:
    public enum OptionFactory {
        INTEGER {
            public Option newInstance() {
                return new IntegerOption();
        STATIC_ENUMERATION {
            public Option newInstance() {
                return new StaticEnumerationOption(context.getChoices());
        DYNAMIC_ENUMERATION {
            public Option newInstance() {
                return new DynamicEnumerationOption(context.getDatabase(), context.getSQL());
        private static final OptionContext context = new DatabaseContext(...);
        public abstract Option newInstance();
    }However, even this doesn't work under the circumstances I have described because each new Http request requires a new factory, whereas this implementation is static.
    Assuming it were possible to set the context as I did above, this still limits you to ONE context per enum. To use both an Http context and a Database context, you would need two different enum classes, each with its own context.
    Thus, if you want to stick with 1 enum class, then you are forced to pass the context into the "newInstance" method:
    public enum OptionFactory {
        INTEGER {
            public Option newInstance(OptionContext context) {
                return new IntegerOption();
        STATIC_ENUMERATION {
            public Option newInstance(OptionContext context) {
                return new StaticEnumerationOption(context.getChoices());
        DYNAMIC_ENUMERATION {
            public Option newInstance(OptionContext context) {
                return new DynamicEnumerationOption(context.getDatabase(), context.getSQL());
        public abstract Option newInstance(OptionContext context);
    Perhaps it is an acceptable design practice to pass a
    "Context" object to a factory method. I can't think
    of any real reasons not to allow such an
    architecture. All you are really doing is delegating
    part of the object construction to another class.I don't think there is anything wrong with it. There are tradeoffs, just as
    there are with the factory approach. After some further thinking, I believe the main disadvantage of using this approach is readability:
    /* using a straight factory method */
    OptionFactory factory = getOptionFactory(...);
    Option option = factory.getOption(OptionType.INTEGER);
    /* using a context passed into the factory method */
    // via an enum...
    OptionContext context = getOptionContext(...);
    Option option = OptionFactory.INTEGER.newInstance(context);
    // via a class...
    OptionContext context = getOptionContext(...);
    Option option = OptionFactory.getOption(OptionType.INTEGER, context);However, as I mentioned in one of my previous posts, the context approach can save a certain amount of code redundancy. So in the end, it just depends on the requirements of your application. I would say that sacrificing a little readability is worth it if you have several different contexts to load objects from and the logic to load those objects is complex.
    In essence, what a Context object does is gather the information that is required to construct the object, and the factory uses that information to actually perform the construction. As long as the information used to construct objects can be converted into a common format, then the logic to build the object will be the same for each context. This saves a ton of code if the logic to build the object is complex but the logic to gather the data is not.
    Very interesting discussion...

  • Business Delegate and Session Facade Pattern

    Hi!
    The only way to use the Session Facade Pattern, is if I use EJB for Persistence.
    Is valid to do this?:
    I use Ejb for simple update, insert querys. From my business delegate I call the Session Facade Layer, and from this I invoque Entyties for persistence.
    But if I have complex querys, is correct to make PL SQL Procedures and do the following:
    From my business delegate I call to the Dao layer, and from this via JDBC I call the Procedure.
    Please explain me the best form to do this, having complex querys for reporting and simple querys for inserts/update.
    Is valid to combine the use of CMP (for simple persistence cases), BMP (for complex persistence cases), and JDBC for complex select querys with multiple result rows.
    Thanks!!

    It depends on your design goals. One of the forces driving the use of patterns is the desire to tier an application and abstract the internals of each tier away from the other tiers. One (normal) benefit of this methodology is that the application should become more portable. Now, if you are using PL/SQL, BMP and CMP, you are mixing and matching portable versus proprietary. This is okay. But you should abstract away whether you are using PL/SQL, BMP or CMP from the business layer (or domain model). Ideally, you could completely swap database technologies (say from relational to object) and only have to re-write your integration tier (your DAO's).
    Session facade is simply a glorified Facade pattern. It abstracts the lower-level details of what you are persisting and instead forces you to think in terms of objects. You can use a facade without even remotely touching EJB's. It just so happens that, historically, EJB containers made a mess out of scalability when it came to entity beans. The "session" facade refers to a facade pattern implemented in session beans (that have fewer scalability problems) communicating with the entity beans which do have scalability problems.
    So... to make a long story short, use whatever persistence mechanism you desire. Remember that you should be able to completely switch your persistent store from one type or another and simply re-write your DAO's (or CMP deployment descriptors). Using a facade pattern can help towards this end, but don't make it a straightjacket.
    - Saish
    "My karma ran over your dogma." - Anon

Maybe you are looking for

  • What cable do I need..Please Help Thanks

    What do I need to purchase to connect that audio out on the back of the iPhone docks to my stereo? Also if it is connected and I buy the remote and stand does that mean I can control my music with the remote? And lastly is the cable I need available

  • Displaying news

    Hello @ all, I want store news in an other repository than documents/news. So long that is not the problem. The problem is when I open the news I just see a xml file. The aim is that I want to see the news in that way they a presented when you open t

  • HT4623 my iPhone 5 says no service

    why is this happening currently i am in saudia using zain network

  • #TAB_LINK# not showing a link

    Hi all, when i hover over the standard tabs the following is shown: javascript: apex.submit('TAB_NAME') When i hover over the parent tabs is shows f?p=122:120:<session>:....... How can i show the url with the standard tabs also ? regards, Marco Edite

  • When is Adobe going to support 64bit, I7 CPU's in Elements and Lightroom?

    I have an I7, 64bit computer almost exclusively for multitasking photoshop exercises.  It appears that both elements and Lightroom only use one of the eight cores.  this is very inefficient for me.  Any clues as to when support for these high end com