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

Similar Messages

  • 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

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

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

  • 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

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

Maybe you are looking for

  • My iphone stopped downloading apps! :S help me

    Hello! my iphone stopped downloading apps that when i go to download i press install and it shows the download on home screen and "Waiting..." then it hides and go away from screen!!! help me i tried many apps but same problem that happened suddenly

  • Using Google Base + eBay + Mac

    Many eBay sellers have found they get the majority of their hits from Google Base, not directly from eBay. As an otherwise happy Mac user, I'm frustrated by the incompatability of Base and my Mac!! Does anyone here use their Mac to upload store items

  • Help not syncing problem?

    I've got 20 imacs all syncing perfectly but i noticed one of them doesn't sync at all. in the status bar it says it never synced i've checked the account and redone it on the server but it still says its never been synced. Which is odd as the progres

  • Terminated original iphone won't be able to download 2.0 software?

    I have an original iphone that has been terminated from it's AT&T account & given to me, I use it as an ipod touch with a camera, but I recently heard I won't be able to install the 2.0 software upgrade for it since it's no longer activated, is this

  • Search the Contacts using "Contains" or "LIKE" way

    How can i search for a contact in the contacts list, the name is "Norazmi" i just type in "azmi" but it doesn't work. Same problem for the phone no, the phone no is "0196556390" i type "6556" but can find. I used Windows Mobile and few other phone be